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