From 2ea7d6c41b30869720d5680106a992bfb4c76d4b Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Sat, 28 Nov 2026 22:00:14 +0900 Subject: [PATCH] feat(github): support GitHub Enterprise Server hosts in pull requests (#6729) gh api does not take the host from the remote as gh pr does, so requests for an Enterprise repository went to github.com. GhApiRequest now carries an optional host passed as gh api --hostname (validated as host[:port]); the GitHub tool window sends the connected repository's host, availability reads the login on that host, and remotes on the host gh resolved count as GitHub remotes. Commit checks in the Git log keep github.com. Fixes #6717 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-github/src/lib.rs | 41 ++++++++++++++- crates/ide-github/tests/parse.rs | 26 +++++++++- docs/en/guide/github.mdx | 11 +++-- docs/zh/guide/github.mdx | 11 +++-- src/bindings.ts | 5 ++ src/features/agents/SessionAssets.tsx | 1 + src/features/github/api/client.ts | 18 ++++++- src/features/github/data/data.test.ts | 27 +++++++++- src/features/github/data/logCommitChecks.ts | 6 +-- src/features/github/data/model.ts | 30 ++++++++--- src/features/github/data/repository.test.ts | 55 +++++++++++++++++---- src/features/github/data/repository.ts | 23 +++++++-- src/features/github/reviewMode/model.ts | 9 ++-- 13 files changed, 223 insertions(+), 40 deletions(-) diff --git a/crates/ide-github/src/lib.rs b/crates/ide-github/src/lib.rs index 3bf434694..dfc83d5da 100644 --- a/crates/ide-github/src/lib.rs +++ b/crates/ide-github/src/lib.rs @@ -111,7 +111,17 @@ pub fn availability(root: &Path) -> GhAvailability { let login = login.ok().and_then(Result::ok).map(|l| l.trim().to_owned()).filter(|l| !l.is_empty()); match repo { Ok(Ok(out)) if out.success => match parse_repo(&out.stdout) { - Ok(repo) => GhAvailability::Ready { repo, login }, + Ok(repo) => { + // The login above is github.com's; an Enterprise repository has its own. + let login = match url_host(&repo.url).filter(|h| !h.eq_ignore_ascii_case("github.com")) { + Some(host) => run(root, &["api", "--hostname", host, "user", "--jq", ".login"]) + .ok() + .map(|l| l.trim().to_owned()) + .filter(|l| !l.is_empty()), + None => login, + }; + GhAvailability::Ready { repo, login } + } Err(e) => GhAvailability::Error { message: format!("unexpected gh output: {e}") }, }, Ok(Ok(out)) => classify_failure(if out.stderr.trim().is_empty() { &out.stdout } else { &out.stderr }), @@ -286,6 +296,10 @@ pub struct GhApiRequest { pub body: Option, /// Follow REST `Link` pages; the result is the array of all pages (`--slurp`). pub paginate: bool, + /// The repository's GitHub host (`ghe.example.com`); none: gh's default host. `gh api` + /// doesn't take the host from the remote as `gh pr` does. + #[serde(default)] + pub host: Option, } const METHODS: &[&str] = &["GET", "POST", "PATCH", "PUT", "DELETE"]; @@ -301,6 +315,13 @@ pub fn api_args(req: &GhApiRequest) -> IdeResult> { return Err(IdeError::invalid(format!("not a GitHub API endpoint: {endpoint}"))); } let mut args: Vec = vec!["api".into(), "--method".into(), method, endpoint.into()]; + if let Some(host) = req.host.as_deref().map(str::trim).filter(|h| !h.is_empty()) { + if !is_host(host) { + return Err(IdeError::invalid(format!("not a GitHub host: {host}"))); + } + args.push("--hostname".into()); + args.push(host.into()); + } if req.body.is_some() { args.push("--input".into()); args.push("-".into()); @@ -312,6 +333,24 @@ pub fn api_args(req: &GhApiRequest) -> IdeResult> { Ok(args) } +/// `host` or `host:port`, as gh's `--hostname` takes it. +fn is_host(host: &str) -> bool { + let (name, port) = host.split_once(':').unwrap_or((host, "1")); + !name.is_empty() + && !name.starts_with(['-', '.']) + && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.') + && !port.is_empty() + && port.bytes().all(|b| b.is_ascii_digit()) +} + +/// The host of a repository URL from gh (`https://ghe.example.com/o/r` → `ghe.example.com`). +pub fn url_host(url: &str) -> Option<&str> { + let rest = url.split_once("://")?.1; + let host = rest.split('/').next()?; + let host = host.rsplit_once('@').map_or(host, |(_, h)| h); + is_host(host).then_some(host) +} + /// Runs `req`; returns the response body (JSON text, empty for `204 No Content`). pub fn api(root: &Path, req: &GhApiRequest) -> IdeResult { let args = api_args(req)?; diff --git a/crates/ide-github/tests/parse.rs b/crates/ide-github/tests/parse.rs index 4b6226cd9..9c6aeded1 100644 --- a/crates/ide-github/tests/parse.rs +++ b/crates/ide-github/tests/parse.rs @@ -101,14 +101,28 @@ fn list_arguments() { #[test] fn api_arguments() { - let req = - GhApiRequest { method: "post".into(), endpoint: "graphql".into(), body: Some("{}".into()), paginate: false }; + let req = GhApiRequest { + method: "post".into(), + endpoint: "graphql".into(), + body: Some("{}".into()), + paginate: false, + host: None, + }; assert_eq!(api_args(&req).unwrap(), ["api", "--method", "POST", "graphql", "--input", "-"]); + let ghe = GhApiRequest { host: Some("ghe.example.com:8443".into()), ..req.clone() }; + assert_eq!( + api_args(&ghe).unwrap(), + ["api", "--method", "POST", "graphql", "--hostname", "ghe.example.com:8443", "--input", "-"] + ); + for bad in ["--x", "evil.example/x", "a b", ".x", "h:", "h:8x"] { + assert!(api_args(&GhApiRequest { host: Some(bad.into()), ..req.clone() }).is_err(), "{bad}"); + } let req = GhApiRequest { method: "GET".into(), endpoint: "repos/{owner}/{repo}/labels".into(), body: None, paginate: true, + host: Some(" ".into()), }; assert_eq!( api_args(&req).unwrap(), @@ -119,3 +133,11 @@ fn api_arguments() { } assert!(api_args(&GhApiRequest { method: "TRACE".into(), ..req }).is_err()); } + +#[test] +fn repository_url_hosts() { + assert_eq!(url_host("https://ghe.example.com/acme/app"), Some("ghe.example.com")); + assert_eq!(url_host("https://github.com/o/r"), Some("github.com")); + assert_eq!(url_host("https://user@ghe.example.com:8443/o/r"), Some("ghe.example.com:8443")); + assert_eq!(url_host("ghe.example.com/o/r"), None); +} diff --git a/docs/en/guide/github.mdx b/docs/en/guide/github.mdx index cf2156495..d630c9263 100644 --- a/docs/en/guide/github.mdx +++ b/docs/en/guide/github.mdx @@ -21,7 +21,7 @@ OpenIDEA works with GitHub through the [GitHub CLI](https://cli.github.com) (`gh **Retry** when you are done. - The project needs a Git remote on `github.com`. With one GitHub remote, OpenIDEA connects to it automatically. With + The project needs a Git remote on `github.com` or on a GitHub Enterprise Server host. With one GitHub remote, OpenIDEA connects to it automatically. With several, the tool window asks you to pick a **Repository**; the choice is remembered per project. To switch later, use **Change Repository or Account…** in the tool window's `⋮` menu. @@ -35,7 +35,11 @@ OpenIDEA works with GitHub through the [GitHub CLI](https://cli.github.com) (`gh -Only `github.com` is supported. GitHub Enterprise hosts, GitLab and Bitbucket are not. +### 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`. + +GitLab is covered by the community plugin `aritti.gitlab`. Bitbucket is not supported. ## Menu and shortcuts @@ -154,6 +158,7 @@ In the editor or the Project view, **Open In › GitHub** opens the file (at the ## Not supported -- GitHub Enterprise, GitLab, Bitbucket. +- Bitbucket. GitLab: see the community plugin `aritti.gitlab`. +- Cloning from, and the commit checks column for, GitHub Enterprise Server. - Issues, gists, notifications and creating or sharing repositories. - Managing GitHub Actions (re-running jobs, reading logs). diff --git a/docs/zh/guide/github.mdx b/docs/zh/guide/github.mdx index 6610beeba..7558ff49c 100644 --- a/docs/zh/guide/github.mdx +++ b/docs/zh/guide/github.mdx @@ -19,7 +19,7 @@ OpenIDEA 通过 [GitHub CLI](https://cli.github.com)(`gh`)对接 GitHub: 按钮,点击后在内置终端中执行该命令。完成后点 **重试**。 - 项目需要有一个指向 `github.com` 的 Git 远程。只有一个 GitHub 远程时自动连接;有多个时,工具窗口会让你选择 + 项目需要有一个指向 `github.com` 或 GitHub Enterprise Server 主机的 Git 远程。只有一个 GitHub 远程时自动连接;有多个时,工具窗口会让你选择 **仓库**,选择按项目记住。之后要切换,可在工具窗口的 `⋮` 菜单中选 **更改仓库或账户…**。 当 `gh` 中登录了多个 `github.com` 账户时,**自动**模式沿用 `gh` 当前的活动账户,不会在项目环境中设置 `GH_TOKEN`。在 **设置 › 版本控制 › GitHub** 和 **拉取请求** 标题栏中,OpenIDEA 会根据仓库远程提示匹配的账户(**对此项目使用 ``**),也可以手动为项目指定账户(保存在 `.openidea/settings.toml`)。显式选择账户后,OpenIDEA 会将该账户的 `GH_TOKEN` 传递给此项目中启动的进程(终端、智能体、Git、拉取请求和运行配置),而不会改动全局的 `gh auth switch` 状态。 @@ -27,7 +27,11 @@ OpenIDEA 通过 [GitHub CLI](https://cli.github.com)(`gh`)对接 GitHub: -只支持 `github.com`,不支持 GitHub Enterprise、GitLab 和 Bitbucket。 +### GitHub Enterprise Server + +先用 `gh auth login --hostname ghe.example.com` 登录服务器。gh 把项目仓库解析到该主机后,指向该主机的远程都算作 GitHub 远程,所有 API 调用都发往该主机,使用 gh 在该主机上的活动账户。上面的项目账户选择只对 `github.com` 生效;要切换 Enterprise 账户,请用 `gh auth switch --hostname ghe.example.com`。 + +GitLab 由社区插件 `aritti.gitlab` 提供。不支持 Bitbucket。 ## 菜单与快捷键 @@ -146,6 +150,7 @@ Git 日志可以显示每个提交在 GitHub 上的检查状态。在日志的 * ## 暂不支持 -- GitHub Enterprise、GitLab、Bitbucket。 +- Bitbucket。GitLab 请使用社区插件 `aritti.gitlab`。 +- 从 GitHub Enterprise Server 克隆,以及它的提交检查列。 - Issue、Gist、通知,以及创建或分享仓库。 - 管理 GitHub Actions(重新运行作业、查看日志)。 diff --git a/src/bindings.ts b/src/bindings.ts index 7bc25e388..289ec4ced 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -7958,6 +7958,11 @@ export type GhApiRequest = { body: string | null, /** Follow REST `Link` pages; the result is the array of all pages (`--slurp`). */ paginate: boolean, + /** + * The repository's GitHub host (`ghe.example.com`); none: gh's default host. `gh api` + * doesn't take the host from the remote as `gh pr` does. + */ + host?: string | null, }; /** An authenticated `github.com` account stored in GitHub CLI (`gh`). */ diff --git a/src/features/agents/SessionAssets.tsx b/src/features/agents/SessionAssets.tsx index 452263334..c9fe39daf 100644 --- a/src/features/agents/SessionAssets.tsx +++ b/src/features/agents/SessionAssets.tsx @@ -114,6 +114,7 @@ function fetchGithubMeta( endpoint: `repos/${githubRepo}/${segment}/${number}`, body: null, paginate: false, + host: null, }), ) .then((text) => parseGhItemResponse(text, kind)) diff --git a/src/features/github/api/client.ts b/src/features/github/api/client.ts index 2fdef1270..fd84fff4a 100644 --- a/src/features/github/api/client.ts +++ b/src/features/github/api/client.ts @@ -36,14 +36,20 @@ export function graphqlData(text: string): T { return json.data; } -/** Runs a document from `queries.ts` with `variables` (undefined values are dropped). */ +/** + * Runs a document from `queries.ts` with `variables` (undefined values are dropped), in `root` + * on `apiHost` (default: the connected repository's). + */ export async function graphql( doc: string, variables: Record = {}, root: string | null = current?.root ?? null, + apiHost: string | null = host, ): Promise { const body = JSON.stringify({ query: withFragments(doc), variables: definedOnly(variables) }); - const text = await call(commands.ghApi(root, { method: "POST", endpoint: "graphql", body, paginate: false })); + const text = await call( + commands.ghApi(root, { method: "POST", endpoint: "graphql", body, paginate: false, host: apiHost }), + ); return graphqlData(text); } @@ -68,6 +74,7 @@ export async function rest( endpoint, body: body === undefined ? null : JSON.stringify(body), paginate: opts.paginate ?? false, + host, }), ); return parseRest(text, opts.paginate ?? false); @@ -84,6 +91,13 @@ export function parseRest(text: string, paginated: boolean): T { // --------------------------------------------------------------------------- // The connected repository +let host: string | null = 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; +} + let current: (GHRepositoryCoordinates & { id: string | null; root?: string | null }) | null = null; /** Set by `data/repository.ts` when the tool window connects (null: disconnected); `root`: its local repository. */ diff --git a/src/features/github/data/data.test.ts b/src/features/github/data/data.test.ts index 97efc9f6a..9fd26b7c6 100644 --- a/src/features/github/data/data.test.ts +++ b/src/features/github/data/data.test.ts @@ -17,6 +17,7 @@ import { mergeCommitMessage, normalizeSearch, parseGitHubRemote, + urlHost, remoteOfRepository, pullRequestPermissions, pullRequestStateIcon, @@ -405,7 +406,7 @@ describe("pull request helpers", () => { "ssh://git@ssh.github.com:443/o/r.git", "git@ssh.github.com:o/r.git", ]) - expect(parseGitHubRemote(url), url).toEqual({ owner: "o", name: "r" }); + expect(parseGitHubRemote(url), url).toEqual({ owner: "o", name: "r", host: "github.com" }); expect(parseGitHubRemote("https://gitlab.com/o/r.git")).toBeNull(); expect(parseGitHubRemote("/local/repo")).toBeNull(); expect(parseGitHubRemote("https://ssh.github.com/o/r.git")).toBeNull(); @@ -423,6 +424,30 @@ describe("pull request helpers", () => { ]).map((r) => `${r.remote}=${r.owner}/${r.name}`), ).toEqual(["origin=me/r", "fork=dengliu/r", "upstream=org/r"]); }); + + it("recognizes remotes on a GitHub Enterprise Server host it is given", () => { + const hosts = ["ghe.example.com"]; + for (const url of [ + "https://ghe.example.com/acme/app.git", + "git@ghe.example.com:acme/app.git", + "ssh://git@GHE.example.com:2222/acme/app", + ]) + expect(parseGitHubRemote(url, hosts), url).toEqual({ owner: "acme", name: "app", host: "ghe.example.com" }); + expect(parseGitHubRemote("https://ghe.example.com/acme/app.git")).toBeNull(); + expect(parseGitHubRemote("https://gheXexample.com/acme/app.git", hosts)).toBeNull(); + expect( + githubRemotes( + [ + { name: "origin", url: "git@ghe.example.com:acme/app.git" }, + { name: "public", url: "https://github.com/acme/app-mirror" }, + ], + "/repo", + hosts, + ).map((r) => `${r.remote}=${r.host}/${r.owner}/${r.name}`), + ).toEqual(["origin=ghe.example.com/acme/app", "public=github.com/acme/app-mirror"]); + expect(urlHost("https://GHE.example.com:8443/acme/app")).toBe("ghe.example.com:8443"); + expect(urlHost("not a url")).toBeNull(); + }); }); describe("batches", () => { diff --git a/src/features/github/data/logCommitChecks.ts b/src/features/github/data/logCommitChecks.ts index 718924632..a9053278e 100644 --- a/src/features/github/data/logCommitChecks.ts +++ b/src/features/github/data/logCommitChecks.ts @@ -4,7 +4,7 @@ import { graphql, repoVariables } from "../api/client"; import type { GHCommitStatusContextState, GHRepositoryCoordinates } from "../api/types"; import { githubRemotes } from "./repository"; -type Target = GHRepositoryCoordinates & { root: string }; +type Target = GHRepositoryCoordinates & { root: string; host: string }; export interface LogCommitCheck { state: GHCommitStatusContextState; target: Target; @@ -20,7 +20,7 @@ async function targets(root: string): Promise { if (previous && previous.expires > Date.now()) return previous.targets; const remotes = githubRemotes(await call(commands.vcsRemotes(root)).catch(() => []), root); remotes.sort((a, b) => Number(b.remote === "origin") - Number(a.remote === "origin")); - const resolved = remotes.map(({ owner, name }) => ({ owner, name, root })); + const resolved = remotes.map(({ owner, name, host }) => ({ owner, name, root, host: host ?? "github.com" })); if (remoteCache.size >= 128) remoteCache.delete(remoteCache.keys().next().value!); remoteCache.set(root, { targets: resolved, expires: Date.now() + REMOTE_TTL }); return resolved; @@ -37,7 +37,7 @@ async function queryBatch(target: Target, revisions: string[]) { const variables = Object.fromEntries(revisions.map((oid, i) => [`oid${i}`, oid])); const data = await graphql<{ repository: Record | null; - }>(doc, { ...repoVariables(target), ...variables }, target.root); + }>(doc, { ...repoVariables(target), ...variables }, target.root, target.host); return revisions.map((_, i) => data.repository?.[`c${i}`]?.statusCheckRollup?.state ?? null); } diff --git a/src/features/github/data/model.ts b/src/features/github/data/model.ts index 66aae9de9..315334fbe 100644 --- a/src/features/github/data/model.ts +++ b/src/features/github/data/model.ts @@ -413,13 +413,29 @@ export function repositoryDisplayName( return showOwner ? `${repo.owner}/${repo.name}` : repo.name; } -/** `owner/name` of a github.com remote URL (https, ssh or scp-like; SSH also via ssh.github.com), else null. */ -export function parseGitHubRemote(url: string): GHRepositoryCoordinates | null { - const m = - /^(?:(?:https?:\/\/(?:[^@/]+@)?|git:\/\/)(?:www\.)?|(?:ssh:\/\/(?:[^@/]+@)?|(?:[^@/]+@)?)(?:www\.|ssh\.)?)github\.com(?::\d+(?=\/))?[:/]+([^/]+)\/([^/]+?)(?:\.git)?\/?$/i.exec( - url.trim(), - ); - return m ? { owner: m[1]!, name: m[2]! } : null; +/** + * `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. + */ +export function parseGitHubRemote( + url: string, + hosts: readonly string[] = [], +): (GHRepositoryCoordinates & { host: string }) | null { + const names = ["github\\.com", ...hosts.map((h) => 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; +} + +/** The host of a repository URL from gh (`https://ghe.example.com/o/r` → `ghe.example.com`). */ +export function urlHost(url: string): string | null { + try { + return new URL(url).host.toLowerCase() || null; + } catch { + return null; + } } /** diff --git a/src/features/github/data/repository.test.ts b/src/features/github/data/repository.test.ts index b5bed884e..3c21f8193 100644 --- a/src/features/github/data/repository.test.ts +++ b/src/features/github/data/repository.test.ts @@ -3,6 +3,12 @@ import { afterEach, describe, expect, it, vi } from "vitest"; const ghApi = vi.fn(); const ghAvailability = vi.fn(); const ok = (data: unknown) => Promise.resolve({ status: "ok", data }); +const FOLDER: Record> = { + "/w/android": [{ name: "origin", url: "git@github.com:org/android.git" }], + "/w/ios": [{ name: "origin", url: "https://github.com/org/ios.git" }], + "/w/tools": [{ name: "origin", url: "https://gitlab.com/org/tools.git" }], +}; +let layout = FOLDER; vi.mock("@/platform/ipc", () => ({ isTauri: () => true, @@ -12,17 +18,10 @@ vi.mock("@/platform/ipc", () => ({ return r.data; }, commands: { - vcsRoots: () => ok([{ root: "/w/android" }, { root: "/w/ios" }, { root: "/w/tools" }]), - vcsRemotes: (root: string | null) => - ok( - root === "/w/android" - ? [{ name: "origin", url: "git@github.com:org/android.git" }] - : root === "/w/ios" - ? [{ name: "origin", url: "https://github.com/org/ios.git" }] - : [{ name: "origin", url: "https://gitlab.com/org/tools.git" }], - ), + vcsRoots: () => ok(Object.keys(layout).map((root) => ({ root }))), + vcsRemotes: (root: string | null) => ok(layout[root ?? ""] ?? []), ghAvailability: (repo: string | null) => ghAvailability(repo), - ghApi: (repo: string | null, req: { endpoint: string }) => ghApi(repo, req), + ghApi: (repo: string | null, req: { endpoint: string; host: string | null }) => ghApi(repo, req), }, })); @@ -33,6 +32,7 @@ afterEach(() => { ghApi.mockReset(); ghAvailability.mockReset(); localStorage.clear(); + layout = FOLDER; }); describe("a folder holding several git repositories", () => { @@ -65,3 +65,38 @@ describe("a folder holding several git repositories", () => { expect(ghApi).toHaveBeenLastCalledWith("/w/ios", expect.objectContaining({ endpoint: "user" })); }); }); + +describe("a GitHub Enterprise Server repository", () => { + it("recognises the host gh resolved and sends every API call there", 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( + ok({ kind: "ready", repo: { nameWithOwner: "acme/app", url: "https://ghe.example.com/acme/app" }, login: "al" }), + ); + ghApi.mockImplementation((_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" } } }), + ), + ); + await refreshConnection(); + const s = useGhRepository.getState(); + expect(s.remotes.map((r) => `${r.host}/${r.owner}/${r.name}`)).toEqual([ + "ghe.example.com/acme/app", + "github.com/acme/app-mirror", + ]); + expect(await connect(s.remotes[0]!)).toBe(true); + expect(ghApi.mock.calls.map(([, req]) => [req.endpoint, req.host])).toEqual([ + ["graphql", "ghe.example.com"], + ["user", "ghe.example.com"], + ]); + // The github.com mirror goes back to gh's default host. + expect(await connect(s.remotes[1]!)).toBe(true); + expect(ghApi).toHaveBeenLastCalledWith("/w/app", expect.objectContaining({ host: null })); + }); +}); diff --git a/src/features/github/data/repository.ts b/src/features/github/data/repository.ts index daef6b242..773ed974a 100644 --- a/src/features/github/data/repository.ts +++ b/src/features/github/data/repository.ts @@ -17,7 +17,7 @@ import type { GhAvailability, Remote } from "@/platform/ipc"; import { call, commands, isTauri } from "@/platform/ipc"; import { useVcs, type VcsState } from "@/features/vcs/store"; import { useProject } from "@/platform/project"; -import { errorMessage, setCurrentRepository } from "../api/client"; +import { errorMessage, setApiHost, setCurrentRepository } from "../api/client"; import * as api from "../api/requests"; import type { GHCollaborator, @@ -30,7 +30,7 @@ import type { GHUser, } from "../api/types"; import { createBatchesLoader, mergeBatches, type BatchesLoader, type BatchesState } from "./batches"; -import { hasPermission, parseGitHubRemote, remoteOfRepository } from "./model"; +import { hasPermission, parseGitHubRemote, remoteOfRepository, urlHost } from "./model"; /** A GitHub remote of the project. */ export interface GHRemote extends GHRepositoryCoordinates { @@ -39,6 +39,8 @@ export interface GHRemote extends GHRepositoryCoordinates { url: string; /** Root of the project's git repository the remote belongs to (null or absent: the primary one). */ root?: string | null; + /** `github.com`, or the GitHub Enterprise Server host (absent: github.com). */ + host?: string; } export interface GHConnection { @@ -105,14 +107,18 @@ export const sameRepository = (a: GHRepositoryCoordinates | null | undefined, b: export const nameWithOwner = (r: GHRepositoryCoordinates) => `${r.owner}/${r.name}`; -/** The GitHub remotes among `remotes` of the repository at `root`, one per GitHub repository. */ +/** + * The GitHub remotes among `remotes` of the repository at `root`, one per GitHub repository; + * `hosts`: GitHub Enterprise Server hosts recognised besides github.com. + */ export function githubRemotes( remotes: ReadonlyArray<{ name: string; url: string; resolvedUrl?: string | null }>, root: string | null = null, + hosts: readonly string[] = [], ): GHRemote[] { const out: GHRemote[] = []; for (const r of remotes) { - const c = parseGitHubRemote(r.resolvedUrl ?? r.url); + const c = parseGitHubRemote(r.resolvedUrl ?? r.url, hosts); if (c && !out.some((o) => sameRepository(o, c))) out.push({ ...c, remote: r.name, url: r.url, root }); } return out; @@ -192,7 +198,12 @@ export async function refreshConnection(): Promise { availability = { kind: "error", message: errorMessage(e) }; } if (seq !== checkSeq) return; - localRemotes = found.remotes; + // An Enterprise repository gh resolved: its host's remotes are GitHub remotes too. + const host = availability.kind === "ready" ? urlHost(availability.repo.url) : null; + localRemotes = + host && host !== "github.com" + ? [...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; if (defaultRemote && !remotes.some((r) => sameRepository(r, defaultRemote))) { @@ -202,6 +213,7 @@ 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]; @@ -235,6 +247,7 @@ export async function connect( const root = repo.root !== undefined ? repo.root : (localRemotes.find((r) => sameRepository(r, repo))?.root ?? null); 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()]); if (seq !== connectSeq) return false; diff --git a/src/features/github/reviewMode/model.ts b/src/features/github/reviewMode/model.ts index 91cf4a56f..cfc08c912 100644 --- a/src/features/github/reviewMode/model.ts +++ b/src/features/github/reviewMode/model.ts @@ -46,9 +46,12 @@ export function trackedBranch( if (!remote || !merge || remote === ".") return null; const found = remotes.find((r) => r.name === remote); const url = found?.url ?? remote; - const repository = - parseGitHubRemote(found?.resolvedUrl ?? url) ?? - (connected && remoteOfRepository([{ name: remote, url }], connected) ? connected : null); + const parsed = parseGitHubRemote(found?.resolvedUrl ?? url); + const repository = parsed + ? { owner: parsed.owner, name: parsed.name } + : connected && remoteOfRepository([{ name: remote, url }], connected) + ? connected + : null; if (!repository) return null; const pr = /^refs\/pull\/(\d+)\/head$/.exec(merge); if (pr) return { repository, branch: null, pullRequest: Number(pr[1]) };