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

changeRequestUrl.ts

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