Open History to see the last commit
1import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
2import {
3 detectSourceControlProviderFromRemoteUrl,
4 isSshRemoteUrl,
5} from "@t3tools/shared/sourceControl";
6
7export interface GitHubRepositoryLocator {
8 readonly host: string;
9 readonly owner: string;
10 readonly name: string;
11}
12
13export function parseFetchRemotes(
14 remotes: string,
15): ReadonlyArray<{ readonly name: string; readonly url: string }> {
16 // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`.
17 return remotes
18 .split("\n")
19 .map((line) => /^(\S+)\s+(\S+)\s+\(fetch\)(?:\s+\[[^\]]+\])?$/u.exec(line.trim()))
20 .filter((match): match is RegExpExecArray => match !== null)
21 .map((match) => ({ name: match[1]!, url: match[2]! }));
22}
23
24/**
25 * The repository `gh pr list` reads in a checkout, picked the way gh picks one without a prompt: the
26 * remote `gh repo set-default` marked, else the first of upstream, github, origin (in any case), else
27 * the only remote.
28 *
29 * Null whenever gh might weigh the remotes differently: a remote on another host or under an unrecognized SSH alias,
30 * more than one mark, or several remotes with none of those names.
31 */
32export function selectGitHubBaseRepository(input: {
33 readonly remotes: string;
34 readonly resolved: string;
35 readonly host: string;
36}): { readonly owner: string; readonly name: string } | null {
37 const host = input.host.toLowerCase();
38 const repositories = new Map<string, { readonly owner: string; readonly name: string }>();
39 for (const remote of parseFetchRemotes(input.remotes)) {
40 const [normalizedHost, owner, name, ...rest] = normalizeGitRemoteUrl(remote.url).split("/");
41 const remoteHost =
42 normalizedHost && isSshRemoteUrl(remote.url)
43 ? (apiHostForSshAlias(normalizedHost) ?? normalizedHost)
44 : normalizedHost;
45 if (remoteHost !== host || !owner || !name || rest.length > 0) return null;
46 repositories.set(remote.name, { owner, name });
47 }
48 const marks = input.resolved
49 .split("\n")
50 .map((line) => /^remote\.(.+)\.gh-resolved\s+(\S+)$/u.exec(line.trim()))
51 .filter((match): match is RegExpExecArray => match !== null && repositories.has(match[1]!));
52 if (marks.length > 1) return null;
53 const [mark] = marks;
54 if (mark) {
55 if (mark[2] === "base") return repositories.get(mark[1]!) ?? null;
56 const [owner, name, ...rest] = mark[2]!.toLowerCase().split("/");
57 return owner && name && rest.length === 0 ? { owner, name } : null;
58 }
59 // gh sorts remotes by these names, case-insensitively, and takes the first. A tie for the
60 // top place has no defined winner.
61 const score = (remoteName: string) =>
62 ["origin", "github", "upstream"].indexOf(remoteName.toLowerCase()) + 1;
63 const ranked = [...repositories.entries()].toSorted(
64 ([left], [right]) => score(right) - score(left),
65 );
66 const [top, next] = ranked;
67 return top !== undefined && (next === undefined || score(top[0]) > score(next[0]))
68 ? top[1]
69 : null;
70}
71
72/**
73 * `host` is the API host it settled on, which a caller names when no repository was
74 * found there. GH_REPO is the caller's to check first.
75 */
76export function resolveGitHubRepository(input: {
77 readonly remotes: string;
78 readonly resolved: string;
79 readonly hostHint: string | undefined;
80 readonly defaultHost: string;
81}): { readonly host: string; readonly locator: GitHubRepositoryLocator | null } {
82 const fetchRemotes = parseFetchRemotes(input.remotes).map((remote) => ({
83 ...remote,
84 host: gitHubApiHostForRemote(remote.url),
85 }));
86 const host =
87 (input.hostHint === undefined ? undefined : apiHostForHint(input.hostHint, fetchRemotes)) ??
88 fetchRemotes.find((remote) => remote.name === "origin" && remote.host !== null)?.host ??
89 fetchRemotes.find((remote) => remote.host !== null)?.host ??
90 input.defaultHost;
91 const selected = selectGitHubBaseRepository({
92 remotes: input.remotes,
93 resolved: input.resolved,
94 host,
95 });
96 if (selected !== null) return { host, locator: { host, ...selected } };
97 // gh's own order without its prompt: upstream, github, origin, then the first remote, among
98 // the ones on this host (an SSH alias counts as its API host).
99 const rank = (name: string) => ["upstream", "github", "origin"].indexOf(name.toLowerCase());
100 const candidates = fetchRemotes
101 .filter(
102 (remote) => remote.host === host || normalizeGitRemoteUrl(remote.url).split("/")[0] === host,
103 )
104 .toSorted((left, right) => {
105 const l = rank(left.name);
106 const r = rank(right.name);
107 return (l === -1 ? 99 : l) - (r === -1 ? 99 : r);
108 });
109 for (const remote of candidates) {
110 const [owner, name, ...rest] = normalizeGitRemoteUrl(remote.url).split("/").slice(1);
111 if (owner && name && rest.length === 0) return { host, locator: { host, owner, name } };
112 }
113 return { host, locator: null };
114}
115
116export function parseGitHubRepositorySelector(
117 selector: string,
118 defaultHost: string,
119): GitHubRepositoryLocator | null {
120 const trimmed = selector.trim().replace(/\.git$/i, "");
121 if (/^https?:\/\//i.test(trimmed)) {
122 try {
123 const url = new URL(trimmed);
124 const [owner, name, ...rest] = url.pathname.split("/").filter(Boolean);
125 return owner && name && rest.length === 0
126 ? { host: url.host.toLowerCase(), owner, name }
127 : null;
128 } catch {
129 return null;
130 }
131 }
132 const parts = trimmed.split("/").filter(Boolean);
133 if (parts.length === 2) return { host: defaultHost, owner: parts[0]!, name: parts[1]! };
134 if (parts.length === 3)
135 return { host: parts[0]!.toLowerCase(), owner: parts[1]!, name: parts[2]! };
136 return null;
137}
138
139export function parsePullRequestReference(
140 reference: string,
141):
142 | { readonly kind: "number"; readonly number: number }
143 | { readonly kind: "url"; readonly locator: GitHubRepositoryLocator; readonly number: number }
144 | { readonly kind: "branch"; readonly headSelector: string } {
145 const trimmed = reference.trim();
146 const numbered = /^#?([1-9]\d*)$/.exec(trimmed);
147 if (numbered) return { kind: "number", number: Number(numbered[1]) };
148 if (/^https?:\/\//i.test(trimmed)) {
149 try {
150 const url = new URL(trimmed);
151 const match = /^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)(?:\/.*)?$/.exec(url.pathname);
152 if (match) {
153 return {
154 kind: "url",
155 locator: { host: url.host.toLowerCase(), owner: match[1]!, name: match[2]! },
156 number: Number(match[3]),
157 };
158 }
159 } catch {}
160 }
161 return { kind: "branch", headSelector: trimmed };
162}
163
164/**
165 * `github.com-<name>` is the usual per-account SSH alias (`Host github.com-work` with `HostName
166 * github.com`). Only that exact shape counts: one more dot makes a real DNS name, such as
167 * `github.com-evil.example`, which is read as itself and never handed github.com credentials.
168 */
169const GITHUB_DOT_COM_SSH_ALIAS = /^github\.com-[a-z0-9_-]+$/u;
170
171/** The API host an SSH alias stands for: null for a dotless non-GitHub alias, undefined for none. */
172function apiHostForSshAlias(host: string): string | null | undefined {
173 if (!host.includes(".")) return host.includes("github") ? "github.com" : null;
174 return GITHUB_DOT_COM_SSH_ALIAS.test(host) ? "github.com" : undefined;
175}
176
177/**
178 * An SSH alias (`git@github-work:owner/repo`, `git@github.com-work:owner/repo`) names no API
179 * host of its own; it is read through `github.com`, which is what such an alias almost always
180 * stands for (issue #6198).
181 */
182export function gitHubApiHostForRemote(remoteUrl: string): string | null {
183 const provider = detectSourceControlProviderFromRemoteUrl(remoteUrl);
184 if (provider === null) return null;
185 const host = new URL(provider.baseUrl).host.toLowerCase();
186 if (isSshRemoteUrl(remoteUrl)) {
187 const aliased = apiHostForSshAlias(host);
188 if (aliased !== undefined) return aliased;
189 }
190 return provider.kind === "github" ? host : null;
191}
192
193function apiHostForHint(host: string, remotes: ReadonlyArray<{ readonly url: string }>): string {
194 const normalized = host.toLowerCase();
195 if (GITHUB_DOT_COM_SSH_ALIAS.test(normalized)) {
196 const matching = remotes.filter(
197 (remote) => normalizeGitRemoteUrl(remote.url).split("/")[0] === normalized,
198 );
199 // A hint carries no transport; an HTTPS remote or missing evidence must not select
200 // the github.com endpoint and credentials for a dotted host.
201 if (matching.length === 0 || matching.some((remote) => !isSshRemoteUrl(remote.url)))
202 return normalized;
203 }
204 return apiHostForSshAlias(normalized) ?? normalized;
205}