diff --git a/docs/en/guide/github.mdx b/docs/en/guide/github.mdx index d630c9263f..2e02efe16d 100644 --- a/docs/en/guide/github.mdx +++ b/docs/en/guide/github.mdx @@ -37,7 +37,7 @@ OpenIDEA works with GitHub through the [GitHub CLI](https://cli.github.com) (`gh ### GitHub Enterprise Server -Sign in to the server with `gh auth login --hostname ghe.example.com`. When gh resolves the project's repository on that host, its remotes there count as GitHub remotes, and every API call goes to that host with gh's active account for it. Choosing a project account (above) applies to `github.com` only; switch the Enterprise account with `gh auth switch --hostname ghe.example.com`. +Sign in to the server with `gh auth login --hostname ghe.example.com`. When gh resolves the project's repository on that host, its remotes there count as GitHub remotes, and every API call goes to that host with gh's active account for it. Choosing a project account (above) applies to `github.com` only; switch the Enterprise account with `gh auth switch --hostname ghe.example.com`. OpenIDEA doesn't handle the server's certificate itself: gh checks it against the system's trust store, so a server with a self-signed or internal CA certificate needs that certificate trusted there. GitLab is covered by the community plugin `aritti.gitlab`. Bitbucket is not supported. diff --git a/docs/zh/guide/github.mdx b/docs/zh/guide/github.mdx index 7558ff49c2..2dc8106504 100644 --- a/docs/zh/guide/github.mdx +++ b/docs/zh/guide/github.mdx @@ -29,7 +29,7 @@ OpenIDEA 通过 [GitHub CLI](https://cli.github.com)(`gh`)对接 GitHub: ### GitHub Enterprise Server -先用 `gh auth login --hostname ghe.example.com` 登录服务器。gh 把项目仓库解析到该主机后,指向该主机的远程都算作 GitHub 远程,所有 API 调用都发往该主机,使用 gh 在该主机上的活动账户。上面的项目账户选择只对 `github.com` 生效;要切换 Enterprise 账户,请用 `gh auth switch --hostname ghe.example.com`。 +先用 `gh auth login --hostname ghe.example.com` 登录服务器。gh 把项目仓库解析到该主机后,指向该主机的远程都算作 GitHub 远程,所有 API 调用都发往该主机,使用 gh 在该主机上的活动账户。上面的项目账户选择只对 `github.com` 生效;要切换 Enterprise 账户,请用 `gh auth switch --hostname ghe.example.com`。OpenIDEA 本身不处理服务器证书,由 gh 按系统信任库校验;服务器使用自签名或内部 CA 证书时,需要先在系统中信任该证书。 GitLab 由社区插件 `aritti.gitlab` 提供。不支持 Bitbucket。 diff --git a/src/features/github/api/client.ts b/src/features/github/api/client.ts index fd84fff4a8..2a09f99d40 100644 --- a/src/features/github/api/client.ts +++ b/src/features/github/api/client.ts @@ -66,15 +66,15 @@ export async function rest( method: GHApiMethod, endpoint: string, body?: unknown, - opts: { paginate?: boolean } = {}, + opts: { paginate?: boolean; host?: string | null; root?: string | null } = {}, ): Promise { const text = await call( - commands.ghApi(current?.root ?? null, { + commands.ghApi(opts.root === undefined ? (current?.root ?? null) : opts.root, { method, endpoint, body: body === undefined ? null : JSON.stringify(body), paginate: opts.paginate ?? false, - host, + host: opts.host === undefined ? host : apiHost(opts.host), }), ); return parseRest(text, opts.paginate ?? false); @@ -93,9 +93,13 @@ export function parseRest(text: string, paginated: boolean): T { let host: string | null = null; +/** `gh api --hostname` for `value`: null for github.com, gh's default. */ +export const apiHost = (value: string | null | undefined): string | null => + value && value.toLowerCase() !== "github.com" ? value : null; + /** The GitHub host requests go to (`ghe.example.com`; null: gh's default, github.com). */ -export function setApiHost(value: string | null) { - host = value && value.toLowerCase() !== "github.com" ? value : null; +export function setApiHost(value: string | null | undefined) { + host = apiHost(value); } let current: (GHRepositoryCoordinates & { id: string | null; root?: string | null }) | null = null; diff --git a/src/features/github/api/requests.ts b/src/features/github/api/requests.ts index e3db755661..77bb640de8 100644 --- a/src/features/github/api/requests.ts +++ b/src/features/github/api/requests.ts @@ -4,7 +4,7 @@ * repository is passed. Mutations only send; `data/operations.ts` refreshes what they * change. */ -import { graphql, repoPath, repoVariables, rest } from "./client"; +import { apiHost, graphql, repoPath, repoVariables, rest } from "./client"; import * as Q from "./queries"; import type { GHCollaborator, @@ -64,8 +64,13 @@ export async function allPages(page: (cursor: string | null) => Promise { - const data = await graphql<{ repository: GHRepository | null }>(Q.findRepository, repoVariables(repo)); +/** `repo` on its `host`, gh running in `root` (defaults: the connected repository's). */ +export async function findRepository( + repo: GHRepositoryCoordinates, + root?: string | null, +): Promise { + const host = repo.host === undefined ? undefined : apiHost(repo.host); + const data = await graphql<{ repository: GHRepository | null }>(Q.findRepository, repoVariables(repo), root, host); return data.repository; } @@ -98,9 +103,9 @@ export function restUser(u: RestUser): GHUser { }; } -/** The signed-in user (REST `user`, IntelliJ's `CurrentUser.get`). */ -export async function currentUser(): Promise { - return restUser(await rest("GET", "user")); +/** The signed-in user on `host`, gh running in `root` (defaults: the connected repository's; REST `user`, IntelliJ's `CurrentUser.get`). */ +export async function currentUser(host?: string | null, root?: string | null): Promise { + return restUser(await rest("GET", "user", undefined, { host, root })); } /** Page `page` (1-based) of a REST list; `next` is null on the last page. */ diff --git a/src/features/github/api/types.ts b/src/features/github/api/types.ts index b7f8356303..74345d48a8 100644 --- a/src/features/github/api/types.ts +++ b/src/features/github/api/types.ts @@ -142,10 +142,12 @@ export interface GHRepository { sshUrl: string; } -/** Where a request goes: `owner/name` on github.com. */ +/** Where a request goes: `owner/name`, on `host` (gh's name for it: `github.com`, `ghe.example.com`). */ export interface GHRepositoryCoordinates { owner: string; name: string; + /** Absent where it isn't known (a repository named in a URL or a branch's config). */ + host?: string; } /** REST collaborator (`repos/{o}/{r}/collaborators`) mapped to a user, with its permissions. */ diff --git a/src/features/github/data/model.ts b/src/features/github/data/model.ts index 315334fbe5..b82e4424c7 100644 --- a/src/features/github/data/model.ts +++ b/src/features/github/data/model.ts @@ -415,18 +415,24 @@ export function repositoryDisplayName( /** * `owner/name` and host of a remote URL on github.com or one of `hosts` (GitHub Enterprise - * Server, `ghe.example.com`), https, ssh or scp-like (SSH also via ssh.github.com), else null. + * Server, `ghe.example.com[:port]` as gh names it), https, ssh or scp-like (SSH also via + * ssh.github.com), else null. A host matches whatever port the URL uses, and comes back as given. */ export function parseGitHubRemote( url: string, hosts: readonly string[] = [], ): (GHRepositoryCoordinates & { host: string }) | null { - const names = ["github\\.com", ...hosts.map((h) => h.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))].join("|"); + const hostname = (h: string) => h.toLowerCase().replace(/:\d+$/, ""); + const names = ["github\\.com", ...hosts.map((h) => hostname(h).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))].join("|"); const m = new RegExp( `^(?:(?:https?:\\/\\/(?:[^@/]+@)?|git:\\/\\/)(?:www\\.)?|(?:ssh:\\/\\/(?:[^@/]+@)?|(?:[^@/]+@)?)(?:www\\.|ssh\\.)?)(${names})(?::\\d+(?=\\/))?[:/]+([^/]+)\\/([^/]+?)(?:\\.git)?\\/?$`, "i", ).exec(url.trim()); - return m ? { owner: m[2]!, name: m[3]!, host: m[1]!.toLowerCase() } : null; + if (!m) return null; + const matched = m[1]!.toLowerCase(); + const host = + matched === "github.com" ? matched : (hosts.find((h) => hostname(h) === matched)?.toLowerCase() ?? matched); + return { owner: m[2]!, name: m[3]!, host }; } /** The host of a repository URL from gh (`https://ghe.example.com/o/r` → `ghe.example.com`). */ diff --git a/src/features/github/data/repository.test.ts b/src/features/github/data/repository.test.ts index 3c21f81937..bad099dcc2 100644 --- a/src/features/github/data/repository.test.ts +++ b/src/features/github/data/repository.test.ts @@ -25,14 +25,16 @@ vi.mock("@/platform/ipc", () => ({ }, })); +import { useProject } from "@/platform/project"; import { rest } from "../api/client"; -import { connectedRoot, connectedRemotes, connect, refreshConnection, useGhRepository } from "./repository"; +import { connectedRoot, connectedRemotes, connect, disconnect, refreshConnection, useGhRepository } from "./repository"; afterEach(() => { ghApi.mockReset(); ghAvailability.mockReset(); localStorage.clear(); layout = FOLDER; + useProject.setState({ project: null }); }); describe("a folder holding several git repositories", () => { @@ -100,3 +102,72 @@ describe("a GitHub Enterprise Server repository", () => { expect(ghApi).toHaveBeenLastCalledWith("/w/app", expect.objectContaining({ host: null })); }); }); + +describe("GitHub Enterprise Server hosts beside github.com", () => { + const ready = (url: string) => ok({ kind: "ready", repo: { nameWithOwner: "acme/app", url }, login: "al" }); + const answer = (_repo: string | null, req: { endpoint: string }) => + ok( + req.endpoint === "user" + ? JSON.stringify({ id: 1, node_id: "U1", login: "al", avatar_url: "", html_url: "" }) + : JSON.stringify({ data: { repository: { id: "R1", owner: { login: "acme" }, name: "app" } } }), + ); + const remotesOf = () => useGhRepository.getState().remotes.map((r) => `${r.remote}=${r.host}/${r.owner}/${r.name}`); + + it("keeps a repository of the same name on each host apart, and remembers which", async () => { + layout = { + "/w/app": [ + { name: "origin", url: "git@ghe.example.com:acme/app.git" }, + { name: "public", url: "https://github.com/acme/app.git" }, + ], + }; + ghAvailability.mockReturnValue(ready("https://ghe.example.com/acme/app")); + ghApi.mockImplementation(answer); + await refreshConnection(); + expect(remotesOf()).toEqual(["origin=ghe.example.com/acme/app", "public=github.com/acme/app"]); + const [ghe, dotcom] = useGhRepository.getState().remotes; + expect(await connect(dotcom!)).toBe(true); + expect(ghApi).toHaveBeenLastCalledWith("/w/app", expect.objectContaining({ host: null })); + useProject.setState({ project: { root: "/w" } as never }); + expect(await connect(ghe!)).toBe(true); + expect(localStorage.getItem("openidea.github.repository.v1:/w")).toBe("ghe.example.com/acme/app"); + // Reopening the project reconnects to the one chosen last, on its host. + disconnect({ forget: false }); + ghApi.mockClear(); + await refreshConnection(); + expect(useGhRepository.getState().connection?.coordinates).toMatchObject({ host: "ghe.example.com" }); + expect(ghApi.mock.calls.every(([, req]) => req.host === "ghe.example.com")).toBe(true); + }); + + it("stays on the connected host when connecting elsewhere fails", async () => { + layout = { + "/w/app": [ + { name: "origin", url: "git@ghe.example.com:acme/app.git" }, + { name: "mirror", url: "https://github.com/acme/app-mirror.git" }, + ], + }; + ghAvailability.mockReturnValue(ready("https://ghe.example.com/acme/app")); + ghApi.mockImplementation((repo: string | null, req: { endpoint: string; host: string | null }) => + req.host === null ? Promise.resolve({ status: "error", error: new Error("HTTP 401") }) : answer(repo, req), + ); + await refreshConnection(); + const [ghe, mirror] = useGhRepository.getState().remotes; + expect(await connect(ghe!)).toBe(true); + expect(await connect(mirror!)).toBe(false); + expect(useGhRepository.getState().connection?.coordinates).toMatchObject({ owner: "acme", name: "app" }); + await rest("POST", "repos/acme/app/issues/1/comments", { body: "x" }); + expect(ghApi).toHaveBeenLastCalledWith("/w/app", expect.objectContaining({ host: "ghe.example.com" })); + }); + + it("recognises SSH remotes of a server whose web address has a port", async () => { + layout = { + "/w/app": [ + { name: "origin", url: "git@ghe.example.com:acme/app.git" }, + { name: "fork", url: "ssh://git@ghe.example.com/al/app.git" }, + ], + }; + ghAvailability.mockReturnValue(ready("https://ghe.example.com:8443/acme/app")); + ghApi.mockImplementation(answer); + await refreshConnection(); + expect(remotesOf()).toEqual(["origin=ghe.example.com:8443/acme/app", "fork=ghe.example.com:8443/al/app"]); + }); +}); diff --git a/src/features/github/data/repository.ts b/src/features/github/data/repository.ts index 773ed974a9..2ab307f257 100644 --- a/src/features/github/data/repository.ts +++ b/src/features/github/data/repository.ts @@ -102,11 +102,19 @@ function saveSelection(root: string | null, nameWithOwner: string | null) { } } +/** Same `owner/name`, and the same host when both say which (`acme/app` on GHE is not the one on github.com). */ export const sameRepository = (a: GHRepositoryCoordinates | null | undefined, b: GHRepositoryCoordinates | null) => - !!a && !!b && a.owner.toLowerCase() === b.owner.toLowerCase() && a.name.toLowerCase() === b.name.toLowerCase(); + !!a && + !!b && + a.owner.toLowerCase() === b.owner.toLowerCase() && + a.name.toLowerCase() === b.name.toLowerCase() && + (!a.host || !b.host || a.host.toLowerCase() === b.host.toLowerCase()); export const nameWithOwner = (r: GHRepositoryCoordinates) => `${r.owner}/${r.name}`; +/** `host/owner/name`: one repository among the remotes, and the saved choice. */ +export const repositoryKey = (r: GHRepositoryCoordinates) => `${r.host ?? "github.com"}/${r.owner}/${r.name}`; + /** * The GitHub remotes among `remotes` of the repository at `root`, one per GitHub repository; * `hosts`: GitHub Enterprise Server hosts recognised besides github.com. @@ -151,9 +159,11 @@ export function reviewRoot( return own ? selected : (connection.root ?? vcs.roots[0] ?? vcs.root); } +/** `owner/name`, or a saved `host/owner/name`. */ function parseNameWithOwner(s: string | null | undefined): GHRepositoryCoordinates | null { - const m = s ? /^([^/\s]+)\/([^/\s]+)$/.exec(s) : null; - return m ? { owner: m[1]!, name: m[2]! } : null; + const m = s ? /^(?:([^/\s]+)\/)?([^/\s]+)\/([^/\s]+)$/.exec(s) : null; + if (!m) return null; + return m[1] ? { owner: m[2]!, name: m[3]!, host: m[1].toLowerCase() } : { owner: m[2]!, name: m[3]! }; } let checkSeq = 0; @@ -205,7 +215,8 @@ export async function refreshConnection(): Promise { ? [...found.all].flatMap(([root, list]) => githubRemotes(list, root, [host])) : found.remotes; const remotes = uniqueRepositories(localRemotes); - const defaultRemote = availability.kind === "ready" ? parseNameWithOwner(availability.repo.nameWithOwner) : null; + const resolved = availability.kind === "ready" ? parseNameWithOwner(availability.repo.nameWithOwner) : null; + const defaultRemote = resolved && { ...resolved, host: host ?? "github.com" }; if (defaultRemote && !remotes.some((r) => sameRepository(r, defaultRemote))) { const own = remoteOfRepository(found.all.get(probe) ?? [], defaultRemote); const remote = { @@ -213,7 +224,6 @@ export async function refreshConnection(): Promise { remote: own?.name ?? "", url: own?.url ?? (availability.kind === "ready" ? availability.repo.url : ""), root: probe, - host: host ?? undefined, }; remotes.unshift(remote); localRemotes = [remote, ...localRemotes]; @@ -243,13 +253,18 @@ export async function connect( opts: { remember?: boolean } = {}, ): Promise { const seq = ++connectSeq; - const coordinates = { owner: repo.owner, name: repo.name }; const root = repo.root !== undefined ? repo.root : (localRemotes.find((r) => sameRepository(r, repo))?.root ?? null); + const host = + repo.host ?? localRemotes.find((r) => sameRepository(r, repo) && (r.root ?? null) === root)?.host ?? "github.com"; + const coordinates = { owner: repo.owner, name: repo.name, host }; const remotes = localRemotes.filter((r) => (r.root ?? null) === root); useGhRepository.setState({ connecting: true, connectionError: null }); - setApiHost(localRemotes.find((r) => sameRepository(r, repo) && (r.root ?? null) === root)?.host ?? null); try { - const [repository, currentUser] = await Promise.all([api.findRepository(coordinates), api.currentUser()]); + // The current connection's requests keep their host until this one succeeds. + const [repository, currentUser] = await Promise.all([ + api.findRepository(coordinates, root), + api.currentUser(host, root), + ]); if (seq !== connectSeq) return false; if (!repository) throw new Error(`Repository ${nameWithOwner(coordinates)} not found`); const previous = useGhRepository.getState().connection; @@ -259,13 +274,14 @@ export async function connect( previous?.currentUser.login !== currentUser.login ) resetRepositoryData(); + setApiHost(host); setCurrentRepository({ ...coordinates, id: repository.id, root }); useGhRepository.setState((s) => ({ connection: { coordinates, repository, currentUser, root, remotes }, connecting: false, revision: s.revision + 1, })); - if (opts.remember ?? true) saveSelection(projectRoot(), nameWithOwner(coordinates)); + if (opts.remember ?? true) saveSelection(projectRoot(), repositoryKey(coordinates)); return true; } catch (e) { if (seq !== connectSeq) return false; diff --git a/src/features/github/reviewMode/reviewMode.test.tsx b/src/features/github/reviewMode/reviewMode.test.tsx index 58884f289b..cc846a659a 100644 --- a/src/features/github/reviewMode/reviewMode.test.tsx +++ b/src/features/github/reviewMode/reviewMode.test.tsx @@ -183,6 +183,14 @@ describe("model", () => { owner: "o", name: "r", }); + // A GitHub Enterprise Server remote is the connected repository's by its path, like an alias. + const ghe = { owner: "o", name: "r", host: "ghe.example.com" }; + const enterprise = [{ name: "origin", url: "git@ghe.example.com:o/r.git" }]; + expect(trackedBranch("origin", "refs/heads/x", enterprise, ghe)).toEqual({ + repository: ghe, + branch: "x", + pullRequest: null, + }); expect(trackedBranch("gitlab", "refs/heads/x", [{ name: "gitlab", url: "git@gitlab.com:o/r.git" }])).toBeNull(); }); diff --git a/src/features/github/toolwindow/PullRequestsToolWindow.tsx b/src/features/github/toolwindow/PullRequestsToolWindow.tsx index 5096905382..611a0935d2 100644 --- a/src/features/github/toolwindow/PullRequestsToolWindow.tsx +++ b/src/features/github/toolwindow/PullRequestsToolWindow.tsx @@ -29,6 +29,7 @@ import { connect, disconnect, nameWithOwner, + repositoryKey, refreshConnection, sameRepository, useGhRepository, @@ -179,8 +180,10 @@ function RepositorySelector() { const [chosen, setChosen] = useState(null); const value = chosen ?? - nameWithOwner(remotes.find((r) => sameRepository(r, defaultRemote)) ?? remotes[0] ?? { owner: "", name: "" }); - const target = remotes.find((r) => nameWithOwner(r) === value); + repositoryKey(remotes.find((r) => sameRepository(r, defaultRemote)) ?? remotes[0] ?? { owner: "", name: "" }); + const target = remotes.find((r) => repositoryKey(r) === value); + // Remotes on more than one host (an Enterprise server and github.com) say which. + const hosts = new Set(remotes.map((r) => r.host ?? "github.com")).size > 1; return (
{status && status.accounts.length > 0 && ( @@ -217,9 +220,9 @@ function RepositorySelector() {