дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +02:00
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]>
Цей коміт міститься в:
1 джерело
952bd0b24b
коміт
836a4405d6
10 files changed
+146
-31
No files matched your search
@@ -66,15 +66,15 @@ export async function rest<T>(
|
||||
method: GHApiMethod,
|
||||
endpoint: string,
|
||||
body?: unknown,
|
||||
opts: { paginate?: boolean } = {},
|
||||
opts: { paginate?: boolean; host?: string | null; root?: string | null } = {},
|
||||
): Promise<T> {
|
||||
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<T>(text, opts.paginate ?? false);
|
||||
@@ -93,9 +93,13 @@ export function parseRest<T>(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;
|
||||
|
||||
@@ -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<T>(page: (cursor: string | null) => Promise<GHCon
|
||||
// ---------------------------------------------------------------------------
|
||||
// Repository and users
|
||||
|
||||
export async function findRepository(repo: GHRepositoryCoordinates): Promise<GHRepository | null> {
|
||||
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<GHRepository | null> {
|
||||
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<GHUser> {
|
||||
return restUser(await rest<RestUser>("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<GHUser> {
|
||||
return restUser(await rest<RestUser>("GET", "user", undefined, { host, root }));
|
||||
}
|
||||
|
||||
/** Page `page` (1-based) of a REST list; `next` is null on the last page. */
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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`). */
|
||||
|
||||
@@ -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"]);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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: "[email protected]: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: "[email protected]:o/r.git" }])).toBeNull();
|
||||
});
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
connect,
|
||||
disconnect,
|
||||
nameWithOwner,
|
||||
repositoryKey,
|
||||
refreshConnection,
|
||||
sameRepository,
|
||||
useGhRepository,
|
||||
@@ -179,8 +180,10 @@ function RepositorySelector() {
|
||||
const [chosen, setChosen] = useState<string | null>(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 (
|
||||
<div className={styles.selector}>
|
||||
{status && status.accounts.length > 0 && (
|
||||
@@ -217,9 +220,9 @@ function RepositorySelector() {
|
||||
<Select
|
||||
value={value}
|
||||
options={remotes.map((r) => ({
|
||||
value: nameWithOwner(r),
|
||||
value: repositoryKey(r),
|
||||
verbatim: true,
|
||||
label: repositoryDisplayName(remotes, r, true),
|
||||
label: `${repositoryDisplayName(remotes, r, true)}${hosts ? ` · ${r.host ?? "github.com"}` : ""}`,
|
||||
}))}
|
||||
onChange={setChosen}
|
||||
aria-label="Repository"
|
||||
|
||||
Reference in new issue
Заблокувати користувача