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

changeRequestUrl.ts

210 lines8.2 KB

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