fix(github): keep GitHub Enterprise and github.com repositories apart (#6742)

Follow-up to #6729. Repositories now compare by host as well, so acme/app on an Enterprise server and on github.com stay two remotes; the selector shows the host when remotes span hosts, and the saved choice is host/owner/name (an older owner/name still loads). connect passes the target's host and root to its own requests and switches the shared API host only after they succeed, so a failed switch no longer redirects the existing connection's requests. Remotes match an Enterprise host whatever its port, keeping gh's host:port for --hostname. Docs note that gh checks the server certificate against the system trust store.

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-28 21:48:48 +08:00
1 джерело 952bd0b24b
коміт 836a4405d6
10 files changed
+146 -31

No files matched your search

+9 -3
Переглянути файл
@@ -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`). */
+72 -1
Переглянути файл
@@ -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: "[email protected]: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: "[email protected]: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: "[email protected]:acme/app.git" },
{ name: "fork", url: "ssh://[email protected]/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"]);
});
});
+25 -9
Переглянути файл
@@ -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<void> {
? [...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<void> {
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<boolean> {
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;