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

gitHubRepositoryResolution.ts

163 lines6.6 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 or SSH-aliased. */
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 [remoteHost, owner, name, ...rest] = normalizeGitRemoteUrl(remote.url).split("/");
34 if (remoteHost !== host || !owner || !name || rest.length > 0) return null;
35 repositories.set(remote.name, { owner, name });
36 }
37 const marks = input.resolved
38 .split("\n")
39 .map((line) => /^remote\.(.+)\.gh-resolved\s+(\S+)$/u.exec(line.trim()))
40 .filter((match): match is RegExpExecArray => match !== null && repositories.has(match[1]!));
41 if (marks.length > 1) return null;
42 const [mark] = marks;
43 if (mark) {
44 if (mark[2] === "base") return repositories.get(mark[1]!) ?? null;
45 const [owner, name, ...rest] = mark[2]!.toLowerCase().split("/");
46 return owner && name && rest.length === 0 ? { owner, name } : null;
47 }
48 // gh ranks these names case-insensitively; a top-ranked tie has no defined winner.
49 const score = (remoteName: string) =>
50 ["origin", "github", "upstream"].indexOf(remoteName.toLowerCase()) + 1;
51 const ranked = [...repositories.entries()].toSorted(
52 ([left], [right]) => score(right) - score(left),
53 );
54 const [top, next] = ranked;
55 return top !== undefined && (next === undefined || score(top[0]) > score(next[0]))
56 ? top[1]
57 : null;
59​
60/** Check GH_REPO first; host is available even without a repository. */
61export function resolveGitHubRepository(input: {
62 readonly remotes: string;
63 readonly resolved: string;
64 readonly hostHint: string | undefined;
65 readonly defaultHost: string;
66}): { readonly host: string; readonly locator: GitHubRepositoryLocator | null } {
67 const fetchRemotes = parseFetchRemotes(input.remotes).map((remote) => ({
68 ...remote,
69 host: gitHubApiHostForRemote(remote.url),
70 }));
71 const host =
72 (input.hostHint === undefined ? undefined : apiHostForHint(input.hostHint)) ??
73 fetchRemotes.find((remote) => remote.name === "origin" && remote.host !== null)?.host ??
74 fetchRemotes.find((remote) => remote.host !== null)?.host ??
75 input.defaultHost;
76 const selected = selectGitHubBaseRepository({
77 remotes: input.remotes,
78 resolved: input.resolved,
79 host,
80 });
81 if (selected !== null) return { host, locator: { host, ...selected } };
82 // Match gh's host-filtered priority: upstream, github, origin, then the first remote.
83 const rank = (name: string) => ["upstream", "github", "origin"].indexOf(name.toLowerCase());
84 const candidates = fetchRemotes
85 .filter(
86 (remote) => remote.host === host || normalizeGitRemoteUrl(remote.url).split("/")[0] === host,
87 )
88 .toSorted((left, right) => {
89 const l = rank(left.name);
90 const r = rank(right.name);
91 return (l === -1 ? 99 : l) - (r === -1 ? 99 : r);
92 });
93 for (const remote of candidates) {
94 const [owner, name, ...rest] = normalizeGitRemoteUrl(remote.url).split("/").slice(1);
95 if (owner && name && rest.length === 0) return { host, locator: { host, owner, name } };
96 }
97 return { host, locator: null };
99​
100export function parseGitHubRepositorySelector(
101 selector: string,
102 defaultHost: string,
103): GitHubRepositoryLocator | null {
104 const trimmed = selector.trim().replace(/\.git$/i, "");
105 if (/^https?:\/\//i.test(trimmed)) {
106 try {
107 const url = new URL(trimmed);
108 const [owner, name, ...rest] = url.pathname.split("/").filter(Boolean);
109 return owner && name && rest.length === 0
110 ? { host: url.host.toLowerCase(), owner, name }
111 : null;
112 } catch {
113 return null;
114 }
115 }
116 const parts = trimmed.split("/").filter(Boolean);
117 if (parts.length === 2) return { host: defaultHost, owner: parts[0]!, name: parts[1]! };
118 const host = parts[0]?.toLowerCase();
119 if (parts.length === 3 && host !== undefined && isGitHubHost(host))
120 return { host, owner: parts[1]!, name: parts[2]! };
121 return null;
123​
124export function parsePullRequestReference(
125 reference: string,
126):
127 | { readonly kind: "number"; readonly number: number }
128 | { readonly kind: "url"; readonly locator: GitHubRepositoryLocator; readonly number: number }
129 | { readonly kind: "branch"; readonly headSelector: string } {
130 const trimmed = reference.trim();
131 const numbered = /^#?([1-9]\d*)$/.exec(trimmed);
132 if (numbered) return { kind: "number", number: Number(numbered[1]) };
133 if (/^https?:\/\//i.test(trimmed)) {
134 try {
135 const url = new URL(trimmed);
136 const match = /^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)(?:\/.*)?$/.exec(url.pathname);
137 if (match) {
138 return {
139 kind: "url",
140 locator: { host: url.host.toLowerCase(), owner: match[1]!, name: match[2]! },
141 number: Number(match[3]),
142 };
143 }
144 } catch {}
145 }
146 return { kind: "branch", headSelector: trimmed };
148​
149/** SSH aliases without a domain cannot identify an API host; default to github.com. */
150export function gitHubApiHostForRemote(remoteUrl: string): string | null {
151 const remote = parseGitRemoteHost(remoteUrl);
152 if (remote === null) return null;
153 const host = new URL(`https://${remote.host}`).host.toLowerCase();
154 if (isSshRemoteUrl(remoteUrl) && !host.includes(".")) {
155 return host.includes("github") ? "github.com" : null;
156 }
157 return definition.recognizeRemote(remote) === null ? null : host;
159​
160function apiHostForHint(host: string): string {
161 const normalized = host.toLowerCase();
162 return !normalized.includes(".") && normalized.includes("github") ? "github.com" : normalized;