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

changeRequestUrl.ts

208 lines7.2 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 return claim(host, match);
34 }
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 return claim(host, match);
49 }
50 if (isHostOf(host, "dev.azure.com") || host.endsWith(".visualstudio.com")) {
51 const match = /^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:\/|$)/u.exec(url.pathname);
52 return claim(host, match);
53 }
54 return null;
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​
65export function changeRequestUrlFor(
66 kind: string | null | undefined,
67 host: string,
68 repository: string,
69 number: number,
70 remoteUrl?: string,
71): string | null {
72 switch (kind) {
73 case "github":
74 return `https://${host}/${repository}/pull/${number}`;
75 case "gitcafe":
76 return `https://${host}/${repository}/pulls/${number}`;
77 case "forgejo": {
78 try {
79 const remote = new URL(remoteUrl ?? "");
80 if (
81 (remote.protocol === "http:" || remote.protocol === "https:") &&
82 (remote.hostname.toLowerCase() === host.toLowerCase() ||
83 remote.host.toLowerCase() === host.toLowerCase())
84 ) {
85 return `${remote.origin}/${repository}/pulls/${number}`;
86 }
87 } catch {
88 // SSH remotes do not specify the server's web origin.
89 }
90 return `https://${host}/${repository}/pulls/${number}`;
91 }
92 case "gitlab":
93 return `https://${host}/${repository}/-/merge_requests/${number}`;
94 case "bitbucket":
95 return `https://${host}/${repository}/pull-requests/${number}`;
96 case "azure-devops":
97 return `https://${canonicalRepositoryKey(`${host}/${repository}`.toLowerCase())}/pullrequest/${number}`;
98 default:
99 return null;
100 }
102​
103export function gitHubPullRequestBrowserUrl(
104 identity: RepositoryIdentity | null | undefined,
105 repository: string,
106 number: number,
107): string | null {
108 if (identity?.provider !== "github" || !Number.isSafeInteger(number) || number < 1) return null;
109 const repositoryPath = repository.split("/");
110 if (
111 repositoryPath.length !== 2 ||
112 repositoryPath.some((segment) => segment.length === 0 || segment === "." || segment === "..")
113 ) {
114 return null;
115 }
116​
117 let origin: string | null = null;
118 try {
119 const remoteUrl = new URL(identity.locator.remoteUrl.trim());
120 if (remoteUrl.protocol === "http:" || remoteUrl.protocol === "https:") {
121 origin = remoteUrl.origin;
122 }
123 } catch {}
124 const hostname = identity.canonicalKey.split("/")[0];
125 if (origin === null && !hostname) return null;
126​
127 try {
128 const url = new URL(origin ?? `https://${hostname}`);
129 url.pathname = `/${repositoryPath.join("/")}/pull/${number}`;
130 return url.toString();
131 } catch {
132 return null;
133 }
135​
136/**
137 * The pull-request URL a GitHub-style `#123` autolink might name. GitHub writes every bare
138 * reference through `/issues/`, including pull requests, so this only builds a candidate: the
139 * caller must successfully read it as a pull request before treating it as one.
140 */
141export function pullRequestCandidateUrlFromReferenceAutolink(targetUrl: string): string | null {
142 let url: URL;
143 try {
144 url = new URL(targetUrl);
145 } catch {
146 return null;
147 }
148 if (
149 (url.protocol !== "https:" && url.protocol !== "http:") ||
150 !(
151 url.hostname.toLowerCase() === "github.com" ||
152 url.hostname.toLowerCase().endsWith(".github.com") ||
153 url.hostname.toLowerCase().split(".").includes("github")
154 )
155 ) {
156 return null;
157 }
158 const match = /^\/([^/]+\/[^/]+)\/issues\/(\d+)(?:\/|$)/u.exec(url.pathname);
159 if (match?.[1] === undefined || match[2] === undefined) return null;
160 url.pathname = `/${match[1]}/pull/${match[2]}`;
161 return url.toString();
163​
164export function matchesLinkedPullRequestUrl(
165 linkedPullRequest: ThreadLinkedPullRequest,
166 targetUrl: string,
167): boolean {
168 const linked = parseChangeRequestUrl(linkedPullRequest.url);
169 const target = parseChangeRequestUrl(targetUrl);
170 return (
171 linked !== null &&
172 target !== null &&
173 linked.host === target.host &&
174 linked.repository === target.repository &&
175 linked.number === target.number &&
176 linked.authority === target.authority
177 );
179​
180export function changeRequestRepositoryUrl(targetUrl: string): string | null {
181 const changeRequest = parseChangeRequestUrl(targetUrl);
182 if (changeRequest === null) return null;
183 const url = new URL(targetUrl);
184 const repositoryPath =
185 /^(.*?)\/-\/merge_requests\/\d+(?:\/|$)/iu.exec(url.pathname)?.[1] ??
186 /^(.*?)(?:\/pulls?\/\d+|\/-\/merge_requests\/\d+|\/pull-requests\/\d+|\/pullrequest\/\d+)(?:\/|$)/iu.exec(
187 url.pathname,
188 )?.[1];
189 if (!repositoryPath) return null;
190 url.pathname = repositoryPath;
191 url.search = "";
192 url.hash = "";
193 return url.toString();
195​
196export function siblingPullRequestUrl(url: string, number: number): string | null {
197 const reference = parseChangeRequestUrl(url);
198 if (reference === null || !Number.isSafeInteger(number) || number < 1) return null;
199 const sibling = new URL(url);
200 const route = /^\/(-\/merge_requests|pulls?|pull-requests|pullrequest)\/\d+(?:\/|$)/u.exec(
201 sibling.pathname.slice(reference.repository.length + 1),
202 )?.[1];
203 if (route === undefined) return null;
204 sibling.pathname = `/${reference.repository}/${route}/${number}`;
205 sibling.search = "";
206 sibling.hash = "";
207 return sibling.toString();