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 <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-28 21:00:14 +08:00
1 джерело 16e5cb5763
коміт 2ea7d6c41b
13 files changed
+223 -40

No files matched your search

+16 -2
Переглянути файл
@@ -36,14 +36,20 @@ export function graphqlData<T>(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<T>(
doc: string,
variables: Record<string, unknown> = {},
root: string | null = current?.root ?? null,
apiHost: string | null = host,
): Promise<T> {
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<T>(text);
}
@@ -68,6 +74,7 @@ export async function rest<T>(
endpoint,
body: body === undefined ? null : JSON.stringify(body),
paginate: opts.paginate ?? false,
host,
}),
);
return parseRest<T>(text, opts.paginate ?? false);
@@ -84,6 +91,13 @@ export function parseRest<T>(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. */
+26 -1
Переглянути файл
@@ -17,6 +17,7 @@ import {
mergeCommitMessage,
normalizeSearch,
parseGitHubRemote,
urlHost,
remoteOfRepository,
pullRequestPermissions,
pullRequestStateIcon,
@@ -405,7 +406,7 @@ describe("pull request helpers", () => {
"ssh://[email protected]:443/o/r.git",
"[email protected]: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",
"[email protected]:acme/app.git",
"ssh://[email protected]: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: "[email protected]: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", () => {
+3 -3
Переглянути файл
@@ -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<Target[]> {
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<string, { statusCheckRollup: { state: GHCommitStatusContextState } | null } | null> | 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);
}
+23 -7
Переглянути файл
@@ -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;
}
}
/**
+45 -10
Переглянути файл
@@ -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<string, Array<{ name: string; url: string }>> = {
"/w/android": [{ name: "origin", url: "[email protected]: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: "[email protected]: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: "[email protected]: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 }));
});
});
+18 -5
Переглянути файл
@@ -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<void> {
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<void> {
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;
+6 -3
Переглянути файл
@@ -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]) };