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

gitHubRepositoryResolution.ts

189 lines7.8 KB

1import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
2import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
3import { parseGitRemoteHost } from "@t3tools/source-control-core/shared/definition";
4import { definition } from "../shared/definition.ts";
5import { isGitHubHost } from "./GitHubCredentials.ts";
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/** gh priority: marked default, upstream/github/origin, sole remote. Null if ambiguous. */
25export function selectGitHubBaseRepository(input: {
26 readonly remotes: string;
27 readonly resolved: string;
28 readonly host: string;
29}): { readonly owner: string; readonly name: string } | null {
30 const host = input.host.toLowerCase();
31 const repositories = new Map<string, { readonly owner: string; readonly name: string }>();
32 for (const remote of parseFetchRemotes(input.remotes)) {
33 const [normalizedHost, owner, name, ...rest] = normalizeGitRemoteUrl(remote.url).split("/");
34 const remoteHost =
35 normalizedHost && isSshRemoteUrl(remote.url)
36 ? (apiHostForSshAlias(normalizedHost) ?? normalizedHost)
37 : normalizedHost;
38 if (remoteHost !== host || !owner || !name || rest.length > 0) return null;
39 repositories.set(remote.name, { owner, name });
40 }
41 const marks = input.resolved
42 .split("\n")
43 .map((line) => /^remote\.(.+)\.gh-resolved\s+(\S+)$/u.exec(line.trim()))
44 .filter((match): match is RegExpExecArray => match !== null && repositories.has(match[1]!));
45 if (marks.length > 1) return null;
46 const [mark] = marks;
47 if (mark) {
48 if (mark[2] === "base") return repositories.get(mark[1]!) ?? null;
49 const [owner, name, ...rest] = mark[2]!.toLowerCase().split("/");
50 return owner && name && rest.length === 0 ? { owner, name } : null;
51 }
52 // gh ranks these names case-insensitively; a top-ranked tie has no defined winner.
53 const score = (remoteName: string) =>
54 ["origin", "github", "upstream"].indexOf(remoteName.toLowerCase()) + 1;
55 const ranked = [...repositories.entries()].toSorted(
56 ([left], [right]) => score(right) - score(left),
57 );
58 const [top, next] = ranked;
59 return top !== undefined && (next === undefined || score(top[0]) > score(next[0]))
60 ? top[1]
61 : null;
63​
64/** Check GH_REPO first; host is available even without a repository. */
65export function resolveGitHubRepository(input: {
66 readonly remotes: string;
67 readonly resolved: string;
68 readonly hostHint: string | undefined;
69 readonly defaultHost: string;
70}): { readonly host: string; readonly locator: GitHubRepositoryLocator | null } {
71 const fetchRemotes = parseFetchRemotes(input.remotes).map((remote) => ({
72 ...remote,
73 host: gitHubApiHostForRemote(remote.url),
74 }));
75 const host =
76 (input.hostHint === undefined ? undefined : apiHostForHint(input.hostHint, fetchRemotes)) ??
77 fetchRemotes.find((remote) => remote.name === "origin" && remote.host !== null)?.host ??
78 fetchRemotes.find((remote) => remote.host !== null)?.host ??
79 input.defaultHost;
80 const selected = selectGitHubBaseRepository({
81 remotes: input.remotes,
82 resolved: input.resolved,
83 host,
84 });
85 if (selected !== null) return { host, locator: { host, ...selected } };
86 // Match gh's host-filtered priority: upstream, github, origin, then the first remote.
87 const rank = (name: string) => ["upstream", "github", "origin"].indexOf(name.toLowerCase());
88 const candidates = fetchRemotes
89 .filter(
90 (remote) =>
91 remote.host === host ||
92 (remote.host === null && normalizeGitRemoteUrl(remote.url).split("/")[0] === host),
93 )
94 .toSorted((left, right) => {
95 const l = rank(left.name);
96 const r = rank(right.name);
97 return (l === -1 ? 99 : l) - (r === -1 ? 99 : r);
98 });
99 for (const remote of candidates) {
100 const [owner, name, ...rest] = normalizeGitRemoteUrl(remote.url).split("/").slice(1);
101 if (owner && name && rest.length === 0) return { host, locator: { host, owner, name } };
102 }
103 return { host, locator: null };
105​
106export function parseGitHubRepositorySelector(
107 selector: string,
108 defaultHost: string,
109): GitHubRepositoryLocator | null {
110 // Like gh, a clone URL's `.git` comes off the path, before any trailing slash, query or fragment.
111 const withoutGitSuffix = (path: string) => path.replace(/\.git\/*$/i, "");
112 const trimmed = selector.trim();
113 if (/^https?:\/\//i.test(trimmed)) {
114 try {
115 const url = new URL(trimmed);
116 const [owner, name, ...rest] = withoutGitSuffix(url.pathname).split("/").filter(Boolean);
117 return owner && name && rest.length === 0
118 ? { host: url.host.toLowerCase(), owner, name }
119 : null;
120 } catch {
121 return null;
122 }
123 }
124 const parts = withoutGitSuffix(trimmed).split("/").filter(Boolean);
125 if (parts.length === 2) return { host: defaultHost, owner: parts[0]!, name: parts[1]! };
126 const host = parts[0]?.toLowerCase();
127 if (parts.length === 3 && host !== undefined && isGitHubHost(host))
128 return { host, owner: parts[1]!, name: parts[2]! };
129 return null;
131​
132export function parsePullRequestReference(
133 reference: string,
134):
135 | { readonly kind: "number"; readonly number: number }
136 | { readonly kind: "url"; readonly locator: GitHubRepositoryLocator; readonly number: number }
137 | { readonly kind: "branch"; readonly headSelector: string } {
138 const trimmed = reference.trim();
139 const numbered = /^#?([1-9]\d*)$/.exec(trimmed);
140 if (numbered) return { kind: "number", number: Number(numbered[1]) };
141 if (/^https?:\/\//i.test(trimmed)) {
142 try {
143 const url = new URL(trimmed);
144 const match = /^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)(?:\/.*)?$/.exec(url.pathname);
145 if (match) {
146 return {
147 kind: "url",
148 locator: { host: url.host.toLowerCase(), owner: match[1]!, name: match[2]! },
149 number: Number(match[3]),
150 };
151 }
152 } catch {}
153 }
154 return { kind: "branch", headSelector: trimmed };
156​
157// An additional dot is a real DNS host, never a github.com SSH alias.
158const GITHUB_DOT_COM_SSH_ALIAS = /^github\.com-[a-z0-9_-]+$/u;
159​
160function apiHostForSshAlias(host: string): string | null | undefined {
161 if (!host.includes(".")) return host.includes("github") ? "github.com" : null;
162 return GITHUB_DOT_COM_SSH_ALIAS.test(host) ? "github.com" : undefined;
164​
165/** Recognized GitHub SSH aliases use github.com for API requests. */
166export function gitHubApiHostForRemote(remoteUrl: string): string | null {
167 const remote = parseGitRemoteHost(remoteUrl);
168 if (remote === null) return null;
169 const host = new URL(`https://${remote.host}`).host.toLowerCase();
170 if (isSshRemoteUrl(remoteUrl)) {
171 const aliased = apiHostForSshAlias(host);
172 if (aliased !== undefined) return aliased;
173 }
174 return definition.recognizeRemote(remote) === null ? null : host;
176​
177function apiHostForHint(host: string, remotes: ReadonlyArray<{ readonly url: string }>): string {
178 const normalized = host.toLowerCase();
179 if (GITHUB_DOT_COM_SSH_ALIAS.test(normalized)) {
180 const matching = remotes.filter(
181 (remote) => normalizeGitRemoteUrl(remote.url).split("/")[0] === normalized,
182 );
183 // A hint carries no transport; an HTTPS remote or missing evidence must not select
184 // the github.com endpoint and credentials for a dotted host.
185 if (matching.length === 0 || matching.some((remote) => !isSshRemoteUrl(remote.url)))
186 return normalized;
187 }
188 return apiHostForSshAlias(normalized) ?? normalized;