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 return remotes
17 .split("\n")
18 .map((line) => /^(\S+)\s+(\S+)\s+\(fetch\)$/u.exec(line.trim()))
19 .filter((match): match is RegExpExecArray => match !== null)
20 .map((match) => ({ name: match[1]!, url: match[2]! }));
21}
22
23/**
24 * The repository `gh pr list` reads in a checkout, picked the way gh picks one without a prompt: the
25 * remote `gh repo set-default` marked, else the first of upstream, github, origin (in any case), else
26 * the only remote.
27 *
28 * Null whenever gh might weigh the remotes differently: a remote on another host or under an SSH alias,
29 * more than one mark, or several remotes with none of those names.
30 */
31export function selectGitHubBaseRepository(input: {
32 readonly remotes: string;
33 readonly resolved: string;
34 readonly host: string;
35}): { readonly owner: string; readonly name: string } | null {
36 const host = input.host.toLowerCase();
37 const repositories = new Map<string, { readonly owner: string; readonly name: string }>();
38 for (const remote of parseFetchRemotes(input.remotes)) {
39 const [remoteHost, owner, name, ...rest] = normalizeGitRemoteUrl(remote.url).split("/");
40 if (remoteHost !== host || !owner || !name || rest.length > 0) return null;
41 repositories.set(remote.name, { owner, name });
42 }
43 const marks = input.resolved
44 .split("\n")
45 .map((line) => /^remote\.(.+)\.gh-resolved\s+(\S+)$/u.exec(line.trim()))
46 .filter((match): match is RegExpExecArray => match !== null && repositories.has(match[1]!));
47 if (marks.length > 1) return null;
48 const [mark] = marks;
49 if (mark) {
50 if (mark[2] === "base") return repositories.get(mark[1]!) ?? null;
51 const [owner, name, ...rest] = mark[2]!.toLowerCase().split("/");
52 return owner && name && rest.length === 0 ? { owner, name } : null;
53 }
54 // gh sorts remotes by these names, case-insensitively, and takes the first. A tie for the
55 // top place has no defined winner.
56 const score = (remoteName: string) =>
57 ["origin", "github", "upstream"].indexOf(remoteName.toLowerCase()) + 1;
58 const ranked = [...repositories.entries()].toSorted(
59 ([left], [right]) => score(right) - score(left),
60 );
61 const [top, next] = ranked;
62 return top !== undefined && (next === undefined || score(top[0]) > score(next[0]))
63 ? top[1]
64 : null;
65}
66
67/**
68 * `host` is the API host it settled on, which a caller names when no repository was
69 * found there. GH_REPO is the caller's to check first.
70 */
71export function resolveGitHubRepository(input: {
72 readonly remotes: string;
73 readonly resolved: string;
74 readonly hostHint: string | undefined;
75 readonly defaultHost: string;
76}): { readonly host: string; readonly locator: GitHubRepositoryLocator | null } {
77 const fetchRemotes = parseFetchRemotes(input.remotes).map((remote) => ({
78 ...remote,
79 host: gitHubApiHostForRemote(remote.url),
80 }));
81 const host =
82 (input.hostHint === undefined ? undefined : apiHostForHint(input.hostHint)) ??
83 fetchRemotes.find((remote) => remote.name === "origin" && remote.host !== null)?.host ??
84 fetchRemotes.find((remote) => remote.host !== null)?.host ??
85 input.defaultHost;
86 const selected = selectGitHubBaseRepository({
87 remotes: input.remotes,
88 resolved: input.resolved,
89 host,
90 });
91 if (selected !== null) return { host, locator: { host, ...selected } };
92 // gh's own order without its prompt: upstream, github, origin, then the first remote, among
93 // the ones on this host (an SSH alias counts as its API host).
94 const rank = (name: string) => ["upstream", "github", "origin"].indexOf(name.toLowerCase());
95 const candidates = fetchRemotes
96 .filter(
97 (remote) => remote.host === host || normalizeGitRemoteUrl(remote.url).split("/")[0] === host,
98 )
99 .toSorted((left, right) => {
100 const l = rank(left.name);
101 const r = rank(right.name);
102 return (l === -1 ? 99 : l) - (r === -1 ? 99 : r);
103 });
104 for (const remote of candidates) {
105 const [owner, name, ...rest] = normalizeGitRemoteUrl(remote.url).split("/").slice(1);
106 if (owner && name && rest.length === 0) return { host, locator: { host, owner, name } };
107 }
108 return { host, locator: null };
109}
110
111export function parseGitHubRepositorySelector(
112 selector: string,
113 defaultHost: string,
114): GitHubRepositoryLocator | null {
115 const trimmed = selector.trim().replace(/\.git$/i, "");
116 if (/^https?:\/\//i.test(trimmed)) {
117 try {
118 const url = new URL(trimmed);
119 const [owner, name, ...rest] = url.pathname.split("/").filter(Boolean);
120 return owner && name && rest.length === 0
121 ? { host: url.host.toLowerCase(), owner, name }
122 : null;
123 } catch {
124 return null;
125 }
126 }
127 const parts = trimmed.split("/").filter(Boolean);
128 if (parts.length === 2) return { host: defaultHost, owner: parts[0]!, name: parts[1]! };
129 if (parts.length === 3)
130 return { host: parts[0]!.toLowerCase(), owner: parts[1]!, name: parts[2]! };
131 return null;
132}
133
134export function parsePullRequestReference(
135 reference: string,
136):
137 | { readonly kind: "number"; readonly number: number }
138 | { readonly kind: "url"; readonly locator: GitHubRepositoryLocator; readonly number: number }
139 | { readonly kind: "branch"; readonly headSelector: string } {
140 const trimmed = reference.trim();
141 const numbered = /^#?([1-9]\d*)$/.exec(trimmed);
142 if (numbered) return { kind: "number", number: Number(numbered[1]) };
143 if (/^https?:\/\//i.test(trimmed)) {
144 try {
145 const url = new URL(trimmed);
146 const match = /^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)(?:\/.*)?$/.exec(url.pathname);
147 if (match) {
148 return {
149 kind: "url",
150 locator: { host: url.host.toLowerCase(), owner: match[1]!, name: match[2]! },
151 number: Number(match[3]),
152 };
153 }
154 } catch {}
155 }
156 return { kind: "branch", headSelector: trimmed };
157}
158
159/**
160 * An SSH alias (`git@github-work:owner/repo`) names no API host of its own; it is read
161 * through `github.com`, which is what such an alias almost always stands for (issue
162 * #6198).
163 */
164export function gitHubApiHostForRemote(remoteUrl: string): string | null {
165 const provider = detectSourceControlProviderFromRemoteUrl(remoteUrl);
166 if (provider === null) return null;
167 const host = new URL(provider.baseUrl).host.toLowerCase();
168 if (isSshRemoteUrl(remoteUrl) && !host.includes(".")) {
169 return host.includes("github") ? "github.com" : null;
170 }
171 return provider.kind === "github" ? host : null;
172}
173
174function apiHostForHint(host: string): string {
175 const normalized = host.toLowerCase();
176 return !normalized.includes(".") && normalized.includes("github") ? "github.com" : normalized;
177}