Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

gitHubRepositoryResolution.ts

178 lines7.0 KB

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