Open History to see the last commit
1import type { RepositoryIdentity, ThreadLinkedPullRequest } from "@t3tools/contracts";
2import { canonicalRepositoryKey } from "./sourceControl.ts";
3
4/**
5 * A change request named the way a thread link names one: the host below which the repository
6 * is addressed, the repository path as that host writes it, and the number.
7 *
8 * The two strings are what `pullRequestHostOf` and the project's `repositoryIdentity` produce
9 * from a git remote — lower case, no port, the full path below the host — because links are
10 * matched against those. Anything else matches nothing.
11 */
12export interface ChangeRequestLink {
13 readonly host: string;
14 readonly repository: string;
15 readonly number: number;
16 /** Forgejo's HTTP host and port, separate from the portless repository identity. */
17 readonly authority?: string;
18}
19
20/** The host itself, one of its subdomains, or an install named after the provider. */
21function isHostOf(hostname: string, apex: string, label?: string): boolean {
22 if (hostname === apex || hostname.endsWith(`.${apex}`)) return true;
23 return label !== undefined && hostname.split(".").includes(label);
24}
25
26/**
27 * The repository and number behind a change request URL on a host this can read, or null for
28 * anything else — an issue, a commit, a repository root, a host this cannot tell apart from an
29 * ordinary link. A doubtful match is worse than no match, so nothing here guesses.
30 *
31 * Each host is recognised by the path shape it alone uses, guarded by a hostname it could
32 * plausibly be served from, since self-hosted installs are named whatever their admin chose:
33 * GitLab's `/-/` marker is unique enough to trust on any hostname, while `/pull/` is generic
34 * enough that it is only believed from a GitHub-ish host.
35 *
36 * Nothing here tries to tell a lookalike hostname from a real one — `github.com.evil.test` and
37 * the rest are an open set, and blocking spellings of it costs real hosts (`gitlab.com.br` is a
38 * registrable domain). What a claim is worth is decided where it is used.
39 */
40export function parseChangeRequestUrl(targetUrl: string): ChangeRequestLink | null {
41 let url: URL;
42 try {
43 url = new URL(targetUrl);
44 } catch {
45 return null;
46 }
47 // `javascript:`, `mailto:` and friends have no host to speak of and nothing to open.
48 if (url.protocol !== "https:" && url.protocol !== "http:") return null;
49 const host = url.hostname.toLowerCase();
50
51 // GitHub, and any Enterprise install: /{owner}/{repo}/pull/{n}
52 if (isHostOf(host, "github.com", "github")) {
53 const match = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u.exec(url.pathname);
54 if (match) return claim(host, match);
55 }
56 // Forgejo and Gitea use /pulls/ on arbitrary self-hosted domains.
57 const forgejo = /^\/([^/]+(?:\/[^/]+)+)\/pulls\/(\d+)(?:\/|$)/u.exec(url.pathname);
58 if (forgejo) {
59 const link = claim(host, forgejo);
60 return link === null ? null : { ...link, authority: url.host.toLowerCase() };
61 }
62 // GitLab, self-hosted included: /{group}/[{subgroup}/...]{repo}/-/merge_requests/{n}. The `/-/`
63 // separator is GitLab's own, so the hostname is not asked about.
64 const gitlab = /^\/([^/]+(?:\/[^/]+)+)\/-\/merge_requests\/(\d+)(?:\/|$)/u.exec(url.pathname);
65 if (gitlab) return claim(host, gitlab);
66 // Bitbucket Cloud: /{workspace}/{repo}/pull-requests/{n}
67 if (isHostOf(host, "bitbucket.org", "bitbucket")) {
68 const match = /^\/([^/]+\/[^/]+)\/pull-requests\/(\d+)(?:\/|$)/u.exec(url.pathname);
69 return claim(host, match);
70 }
71 // Azure DevOps, both the current host and the per-organisation one it replaced. `_git` is part
72 // of the repository path there, as it is in the remote URL the identity is read from.
73 if (isHostOf(host, "dev.azure.com") || host.endsWith(".visualstudio.com")) {
74 const match = /^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:\/|$)/u.exec(url.pathname);
75 return claim(host, match);
76 }
77 return null;
78}
79
80function claim(host: string, match: RegExpExecArray | null): ChangeRequestLink | null {
81 const repository = match?.[1];
82 const number = Number(match?.[2]);
83 return repository && Number.isSafeInteger(number) && number > 0
84 ? { host, repository: repository.toLowerCase(), number }
85 : null;
86}
87
88/** The web URL a host writes for a change request; null when the host shape is unknown. */
89export function changeRequestUrlFor(
90 kind: string | null | undefined,
91 host: string,
92 repository: string,
93 number: number,
94 remoteUrl?: string,
95): string | null {
96 switch (kind) {
97 case "github":
98 return `https://${host}/${repository}/pull/${number}`;
99 case "forgejo": {
100 try {
101 const remote = new URL(remoteUrl ?? "");
102 if (
103 (remote.protocol === "http:" || remote.protocol === "https:") &&
104 (remote.hostname.toLowerCase() === host.toLowerCase() ||
105 remote.host.toLowerCase() === host.toLowerCase())
106 ) {
107 return `${remote.origin}/${repository}/pulls/${number}`;
108 }
109 } catch {
110 // SSH remotes do not specify the server's web origin.
111 }
112 return `https://${host}/${repository}/pulls/${number}`;
113 }
114 case "gitlab":
115 return `https://${host}/${repository}/-/merge_requests/${number}`;
116 case "bitbucket":
117 return `https://${host}/${repository}/pull-requests/${number}`;
118 case "azure-devops":
119 return `https://${canonicalRepositoryKey(`${host}/${repository}`.toLowerCase())}/pullrequest/${number}`;
120 default:
121 return null;
122 }
123}
124
125/** Builds a GitHub URL that remains available when the pull request API cannot be read. */
126export function gitHubPullRequestBrowserUrl(
127 identity: RepositoryIdentity | null | undefined,
128 repository: string,
129 number: number,
130): string | null {
131 if (identity?.provider !== "github" || !Number.isSafeInteger(number) || number < 1) return null;
132 const repositoryPath = repository.split("/");
133 if (
134 repositoryPath.length !== 2 ||
135 repositoryPath.some((segment) => segment.length === 0 || segment === "." || segment === "..")
136 ) {
137 return null;
138 }
139
140 let origin: string | null = null;
141 try {
142 const remoteUrl = new URL(identity.locator.remoteUrl.trim());
143 if (remoteUrl.protocol === "http:" || remoteUrl.protocol === "https:") {
144 origin = remoteUrl.origin;
145 }
146 } catch {
147 // SCP-style remotes are read from their normalized identity below.
148 }
149 const hostname = identity.canonicalKey.split("/")[0];
150 if (origin === null && !hostname) return null;
151
152 try {
153 const url = new URL(origin ?? `https://${hostname}`);
154 url.pathname = `/${repositoryPath.join("/")}/pull/${number}`;
155 return url.toString();
156 } catch {
157 return null;
158 }
159}
160
161/**
162 * The pull-request URL a GitHub-style `#123` autolink might name. GitHub writes every bare
163 * reference through `/issues/`, including pull requests, so this only builds a candidate: the
164 * caller must successfully read it as a pull request before treating it as one.
165 */
166export function pullRequestCandidateUrlFromReferenceAutolink(targetUrl: string): string | null {
167 let url: URL;
168 try {
169 url = new URL(targetUrl);
170 } catch {
171 return null;
172 }
173 if (
174 (url.protocol !== "https:" && url.protocol !== "http:") ||
175 !(
176 url.hostname.toLowerCase() === "github.com" ||
177 url.hostname.toLowerCase().endsWith(".github.com") ||
178 url.hostname.toLowerCase().split(".").includes("github")
179 )
180 ) {
181 return null;
182 }
183 const match = /^\/([^/]+\/[^/]+)\/issues\/(\d+)(?:\/|$)/u.exec(url.pathname);
184 if (match?.[1] === undefined || match[2] === undefined) return null;
185 url.pathname = `/${match[1]}/pull/${match[2]}`;
186 return url.toString();
187}
188
189/** Match a stored PR without requiring its project to remain available. */
190export function matchesLinkedPullRequestUrl(
191 linkedPullRequest: ThreadLinkedPullRequest,
192 targetUrl: string,
193): boolean {
194 const linked = parseChangeRequestUrl(linkedPullRequest.url);
195 const target = parseChangeRequestUrl(targetUrl);
196 return (
197 linked !== null &&
198 target !== null &&
199 linked.host === target.host &&
200 linked.repository === target.repository &&
201 linked.number === target.number &&
202 linked.authority === target.authority
203 );
204}
205
206/** The repository root behind a recognised change-request URL, without PR-specific state. */
207export function changeRequestRepositoryUrl(targetUrl: string): string | null {
208 const changeRequest = parseChangeRequestUrl(targetUrl);
209 if (changeRequest === null) return null;
210 const url = new URL(targetUrl);
211 const repositoryPath =
212 /^(.*?)\/-\/merge_requests\/\d+(?:\/|$)/iu.exec(url.pathname)?.[1] ??
213 /^(.*?)(?:\/pulls?\/\d+|\/-\/merge_requests\/\d+|\/pull-requests\/\d+|\/pullrequest\/\d+)(?:\/|$)/iu.exec(
214 url.pathname,
215 )?.[1];
216 if (!repositoryPath) return null;
217 url.pathname = repositoryPath;
218 url.search = "";
219 url.hash = "";
220 return url.toString();
221}
222
223export function siblingPullRequestUrl(url: string, number: number): string | null {
224 const reference = parseChangeRequestUrl(url);
225 if (reference === null || !Number.isSafeInteger(number) || number < 1) return null;
226 const sibling = new URL(url);
227 const route = /^\/(-\/merge_requests|pulls?|pull-requests|pullrequest)\/\d+(?:\/|$)/u.exec(
228 sibling.pathname.slice(reference.repository.length + 1),
229 )?.[1];
230 if (route === undefined) return null;
231 sibling.pathname = `/${reference.repository}/${route}/${number}`;
232 sibling.search = "";
233 sibling.hash = "";
234 return sibling.toString();
235}