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

changeRequestUrl.ts

215 lines7.5 KB

1import type { RepositoryIdentity, ThreadLinkedPullRequest } from "@t3tools/contracts";
2import { canonicalRepositoryKey } from "./sourceControl.ts";
3​
4/**
5 * The two strings are what `pullRequestHostOf` and the project's `repositoryIdentity` produce
6 * from a git remote — lower case, no port, the full path below the host — because links are
7 * matched against those. Anything else matches nothing.
8 */
9export interface ChangeRequestLink {
10 readonly host: string;
11 readonly repository: string;
12 readonly number: number;
13 readonly authority?: string;
15​
16function isHostOf(hostname: string, apex: string, label?: string): boolean {
17 if (hostname === apex || hostname.endsWith(`.${apex}`)) return true;
18 return label !== undefined && hostname.split(".").includes(label);
20​
21export function parseChangeRequestUrl(targetUrl: string): ChangeRequestLink | null {
22 let url: URL;
23 try {
24 url = new URL(targetUrl);
25 } catch {
26 return null;
27 }
28 if (url.protocol !== "https:" && url.protocol !== "http:") return null;
29 const host = url.hostname.toLowerCase();
30​
31 if (host === "git.cafe" || host === "staging.git.cafe") {
32 const match = /^\/([^/]+\/[^/]+)\/pulls\/(\d+)(?:\/|$)/u.exec(url.pathname);
33 if (match) return claim(host, match);
34 } else {
35 if (isHostOf(host, "github.com", "github")) {
36 const match = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u.exec(url.pathname);
37 if (match) return claim(host, match);
38 }
39 const forgejo = /^\/([^/]+(?:\/[^/]+)+)\/pulls\/(\d+)(?:\/|$)/u.exec(url.pathname);
40 if (forgejo) {
41 const link = claim(host, forgejo);
42 return link === null ? null : { ...link, authority: url.host.toLowerCase() };
43 }
44 const gitlab = /^\/([^/]+(?:\/[^/]+)+)\/-\/merge_requests\/(\d+)(?:\/|$)/u.exec(url.pathname);
45 if (gitlab) return claim(host, gitlab);
46 if (isHostOf(host, "bitbucket.org", "bitbucket")) {
47 const match = /^\/([^/]+\/[^/]+)\/pull-requests\/(\d+)(?:\/|$)/u.exec(url.pathname);
48 if (match) return claim(host, match);
49 }
50 }
51 // Azure DevOps Server can use any hostname; its `_git` pull request route identifies it.
52 const azure = /^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:\/|$)/u.exec(url.pathname);
53 const link = claim(host, azure);
54 return link === null || url.port === "" ? link : { ...link, authority: url.host.toLowerCase() };
56​
57function claim(host: string, match: RegExpExecArray | null): ChangeRequestLink | null {
58 const repository = match?.[1];
59 const number = Number(match?.[2]);
60 return repository && Number.isSafeInteger(number) && number > 0
61 ? { host, repository: repository.toLowerCase(), number }
62 : null;
64​
65function remoteWebOrigin(host: string, remoteUrl: string | undefined): string {
66 try {
67 const remote = new URL(remoteUrl ?? "");
68 if (
69 (remote.protocol === "http:" || remote.protocol === "https:") &&
70 (remote.hostname.toLowerCase() === host.toLowerCase() ||
71 remote.host.toLowerCase() === host.toLowerCase())
72 ) {
73 return remote.origin;
74 }
75 } catch {
76 // SSH remotes do not specify the server's web origin.
77 }
78 return `https://${host}`;
80​
81export function changeRequestUrlFor(
82 kind: string | null | undefined,
83 host: string,
84 repository: string,
85 number: number,
86 remoteUrl?: string,
87): string | null {
88 switch (kind) {
89 case "github":
90 return `https://${host}/${repository}/pull/${number}`;
91 case "gitcafe":
92 return `https://${host}/${repository}/pulls/${number}`;
93 case "forgejo":
94 return `${remoteWebOrigin(host, remoteUrl)}/${repository}/pulls/${number}`;
95 case "gitlab":
96 return `https://${host}/${repository}/-/merge_requests/${number}`;
97 case "bitbucket":
98 return `https://${host}/${repository}/pull-requests/${number}`;
99 case "azure-devops": {
100 const [canonicalHost = host, ...path] = canonicalRepositoryKey(
101 `${host}/${repository}`.toLowerCase(),
102 ).split("/");
103 return `${remoteWebOrigin(canonicalHost, remoteUrl)}/${path.join("/")}/pullrequest/${number}`;
104 }
105 default:
106 return null;
107 }
109​
110export function gitHubPullRequestBrowserUrl(
111 identity: RepositoryIdentity | null | undefined,
112 repository: string,
113 number: number,
114): string | null {
115 if (identity?.provider !== "github" || !Number.isSafeInteger(number) || number < 1) return null;
116 const repositoryPath = repository.split("/");
117 if (
118 repositoryPath.length !== 2 ||
119 repositoryPath.some((segment) => segment.length === 0 || segment === "." || segment === "..")
120 ) {
121 return null;
122 }
123​
124 let origin: string | null = null;
125 try {
126 const remoteUrl = new URL(identity.locator.remoteUrl.trim());
127 if (remoteUrl.protocol === "http:" || remoteUrl.protocol === "https:") {
128 origin = remoteUrl.origin;
129 }
130 } catch {}
131 const hostname = identity.canonicalKey.split("/")[0];
132 if (origin === null && !hostname) return null;
133​
134 try {
135 const url = new URL(origin ?? `https://${hostname}`);
136 url.pathname = `/${repositoryPath.join("/")}/pull/${number}`;
137 return url.toString();
138 } catch {
139 return null;
140 }
142​
143/**
144 * The pull-request URL a GitHub-style `#123` autolink might name. GitHub writes every bare
145 * reference through `/issues/`, including pull requests, so this only builds a candidate: the
146 * caller must successfully read it as a pull request before treating it as one.
147 */
148export function pullRequestCandidateUrlFromReferenceAutolink(targetUrl: string): string | null {
149 let url: URL;
150 try {
151 url = new URL(targetUrl);
152 } catch {
153 return null;
154 }
155 if (
156 (url.protocol !== "https:" && url.protocol !== "http:") ||
157 !(
158 url.hostname.toLowerCase() === "github.com" ||
159 url.hostname.toLowerCase().endsWith(".github.com") ||
160 url.hostname.toLowerCase().split(".").includes("github")
161 )
162 ) {
163 return null;
164 }
165 const match = /^\/([^/]+\/[^/]+)\/issues\/(\d+)(?:\/|$)/u.exec(url.pathname);
166 if (match?.[1] === undefined || match[2] === undefined) return null;
167 url.pathname = `/${match[1]}/pull/${match[2]}`;
168 return url.toString();
170​
171export function matchesLinkedPullRequestUrl(
172 linkedPullRequest: ThreadLinkedPullRequest,
173 targetUrl: string,
174): boolean {
175 const linked = parseChangeRequestUrl(linkedPullRequest.url);
176 const target = parseChangeRequestUrl(targetUrl);
177 return (
178 linked !== null &&
179 target !== null &&
180 linked.host === target.host &&
181 linked.repository === target.repository &&
182 linked.number === target.number &&
183 linked.authority === target.authority
184 );
186​
187export function changeRequestRepositoryUrl(targetUrl: string): string | null {
188 const changeRequest = parseChangeRequestUrl(targetUrl);
189 if (changeRequest === null) return null;
190 const url = new URL(targetUrl);
191 const repositoryPath =
192 /^(.*?)\/-\/merge_requests\/\d+(?:\/|$)/iu.exec(url.pathname)?.[1] ??
193 /^(.*?)(?:\/pulls?\/\d+|\/-\/merge_requests\/\d+|\/pull-requests\/\d+|\/pullrequest\/\d+)(?:\/|$)/iu.exec(
194 url.pathname,
195 )?.[1];
196 if (!repositoryPath) return null;
197 url.pathname = repositoryPath;
198 url.search = "";
199 url.hash = "";
200 return url.toString();
202​
203export function siblingPullRequestUrl(url: string, number: number): string | null {
204 const reference = parseChangeRequestUrl(url);
205 if (reference === null || !Number.isSafeInteger(number) || number < 1) return null;
206 const sibling = new URL(url);
207 const route = /^\/(-\/merge_requests|pulls?|pull-requests|pullrequest)\/\d+(?:\/|$)/u.exec(
208 sibling.pathname.slice(reference.repository.length + 1),
209 )?.[1];
210 if (route === undefined) return null;
211 sibling.pathname = `/${reference.repository}/${route}/${number}`;
212 sibling.search = "";
213 sibling.hash = "";
214 return sibling.toString();