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

pullRequestAnchor.ts

237 lines8.5 KB

1import { md5, sha1 } from "@noble/hashes/legacy";
2import { sha256 } from "@noble/hashes/sha2";
3import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils";
4​
5export interface PullRequestAnchorRange {
6 readonly start: number;
7 readonly side: "left" | "right";
8 readonly end: number;
9 readonly endSide: "left" | "right";
10 /** A GitLab line code's old-side counter: the line it names when that old line was removed. */
11 readonly oldLine?: number;
13​
14export type PullRequestAnchor =
15 | { readonly kind: "code" }
16 | { readonly kind: "commits" }
17 | { readonly kind: "checks" }
18 | {
19 readonly kind: "diff";
20 readonly digest: string;
21 readonly range: PullRequestAnchorRange | null;
22 }
23 | { readonly kind: "timeline"; readonly anchor: string }
24 | { readonly kind: "summary"; readonly anchor: string };
25​
26function pullRequestUrlHash(url: string | null | undefined): string {
27 if (!url) return "";
28 try {
29 return decodeURIComponent(new URL(url).hash.slice(1));
30 } catch {
31 return "";
32 }
34​
35function normalizePullRequestCommentAnchor(anchor: string): string {
36 return anchor
37 .toLowerCase()
38 .replace(/^(?:r|discussion-diff-)(\d+)(?:[lr]\d+(?:-[lr]\d+)?)?$/, "discussion_r$1");
40​
41const COMMIT_ID = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i;
42​
43// GitHub pull request tabs and their GitLab merge request equivalents. Forgejo and Gitea spell the
44// path `/pulls/`; Bitbucket spells it `/pull-requests/` and its code tab `diff`.
45function pullRequestPathTab(pathname: string): PullRequestAnchor | null {
46 const tab = /\/(?:pulls?|pull-requests|-\/merge_requests)\/\d+\/([a-z]+)(?:\/(.*))?$/i.exec(
47 pathname,
48 );
49 const rest = tab?.[2] ?? "";
50 switch (tab?.[1]?.toLowerCase()) {
51 case "files":
52 case "changes":
53 case "diffs":
54 case "diff":
55 return { kind: "code" };
56 case "commits":
57 if (rest === "") return { kind: "commits" };
58 return COMMIT_ID.test(rest.replace(/\/$/, "")) ? { kind: "code" } : null;
59 case "checks":
60 case "pipelines":
61 return rest === "" ? { kind: "checks" } : null;
62 default:
63 return null;
64 }
66​
67// Azure DevOps names a pull request's tab in the `_a` query, not the path. Its provider states
68// no commit list, so `_a=commits` has nothing to open.
69function azureDevOpsQueryTab({ pathname, searchParams }: URL): PullRequestAnchor | null {
70 if (!/\/pullrequest\/\d+\/?$/i.test(pathname)) return null;
71 return searchParams.get("_a")?.toLowerCase() === "files" ? { kind: "code" } : null;
73​
74const isLine = (line: number) => Number.isSafeInteger(line) && line >= 1;
75​
76function gitLabLine(
77 start: number,
78 side: "left" | "right",
79 oldLine = 0,
80): PullRequestAnchorRange | null {
81 if (!isLine(start)) return null;
82 return { start, side, end: start, endSide: side, ...(isLine(oldLine) ? { oldLine } : {}) };
84​
85// GitLab names a file by its path's SHA-1 and a line by `<sha1>_<old>_<new>`, which carries both
86// sides' counters. Rapid Diffs writes `line_<sha1 prefix>_<old>` or `_A<new>`.
87function gitLabDiffAnchor(anchor: string, file: string | null): PullRequestAnchor | null {
88 const rapid = /^line_([a-f0-9]{9})_(A?)(\d+)$/i.exec(anchor);
89 if (rapid) {
90 const line = Number(rapid[3]);
91 return {
92 kind: "diff",
93 digest: (rapid[1] ?? "").toLowerCase(),
94 range: gitLabLine(line, rapid[2] ? "right" : "left"),
95 };
96 }
97 const code = /^(?:diff-content-)?([a-f0-9]{40})(?:_(\d+)_(\d+))?$/i.exec(anchor);
98 // A comment anchor beside `?file=` names the comment.
99 const digest =
100 code?.[1] ?? (!anchor && file !== null && /^[a-f0-9]{40}$/i.test(file) ? file : null);
101 if (digest === null) return null;
102 const [oldLine, newLine] = [Number(code?.[2]), Number(code?.[3])];
103 // A deleted file has no new side, so its new counter is 0.
104 const range =
105 code?.[2] === undefined
106 ? null
107 : newLine === 0
108 ? gitLabLine(oldLine, "left")
109 : gitLabLine(newLine, "right", oldLine);
110 return { kind: "diff", digest: digest.toLowerCase(), range };
112​
113/** The range to select, once the diff shows whether a GitLab line code's old line was removed. */
114export function resolvePullRequestAnchorRange(
115 range: PullRequestAnchorRange,
116 isRemovedLine: (oldLine: number) => boolean,
117): PullRequestAnchorRange {
118 return range.oldLine !== undefined && isRemovedLine(range.oldLine)
119 ? (gitLabLine(range.oldLine, "left") ?? range)
120 : range;
122​
123export function parsePullRequestAnchor(url: string | null | undefined): PullRequestAnchor | null {
124 let parsed: URL;
125 try {
126 parsed = new URL(url ?? "");
127 } catch {
128 return null;
129 }
130 const fallback = pullRequestPathTab(parsed.pathname) ?? azureDevOpsQueryTab(parsed);
131 const anchor = pullRequestUrlHash(url);
132 const isGitLabMergeRequest = /\/-\/merge_requests\/\d+(?:\/|$)/i.test(parsed.pathname);
133 const gitLab = isGitLabMergeRequest
134 ? gitLabDiffAnchor(
135 anchor,
136 /\/-\/merge_requests\/\d+\/diffs\/?$/i.test(parsed.pathname)
137 ? parsed.searchParams.get("file")
138 : null,
139 )
140 : null;
141 if (gitLab) return gitLab;
142 if (!anchor) return fallback;
143 // GitHub line ranges may cross diff sides; file digests were MD5 before SHA-256. Only digest
144 // lengths `pullRequestDiffPathMatches` can match name a file; `#diff-a` is a heading.
145 const diff =
146 /^diff-([a-f0-9]{9}|[a-f0-9]{32}|[a-f0-9]{40}|[a-f0-9]{64})(?:([LR])(\d+)(?:-([LR])(\d+))?)?$/i.exec(
147 anchor,
148 );
149 if (diff) {
150 const start = Number(diff[3]);
151 const end = Number(diff[5] ?? diff[3]);
152 if (
153 diff[2] &&
154 (!Number.isSafeInteger(start) || start < 1 || !Number.isSafeInteger(end) || end < 1)
155 )
156 return fallback;
157 return {
158 kind: "diff",
159 digest: (diff[1] ?? "").toLowerCase(),
160 range: diff[2]
161 ? {
162 start,
163 side: diff[2].toUpperCase() === "L" ? "left" : "right",
164 end,
165 endSide: (diff[4] ?? diff[2]).toUpperCase() === "L" ? "left" : "right",
166 }
167 : null,
168 };
169 }
170 if (
171 (isGitLabMergeRequest && /^note_\d+$/i.test(anchor)) ||
172 /^(?:(?:issuecomment-|pullrequestreview-|discussion_r|r|commitcomment-|event-|comment-)\d+|discussion-diff-\d+(?:[LR]\d+(?:-[LR]\d+)?)?)$/i.test(
173 anchor,
174 )
175 ) {
176 return { kind: "timeline", anchor: normalizePullRequestCommentAnchor(anchor) };
177 }
178 return fallback ?? { kind: "summary", anchor };
180​
181export function pullRequestAnchorMatchesUrl(
182 anchor: string,
183 url: string | null | undefined,
184): boolean {
185 return (
186 normalizePullRequestCommentAnchor(pullRequestUrlHash(url)) ===
187 normalizePullRequestCommentAnchor(anchor)
188 );
190​
191interface AnchoredComment {
192 readonly url: string | null;
193 readonly createdAt: string;
194 readonly reviewUrl?: string | null | undefined;
196​
197/**
198 * A review with no text of its own appears only through the line comments it posted, so its link
199 * resolves to the earliest of those. Any other anchor, or a review shown in its own right, is kept.
200 */
201export function resolvePullRequestReviewAnchor(
202 anchor: string,
203 comments: ReadonlyArray<Pick<AnchoredComment, "url">>,
204 reviewThreads: ReadonlyArray<{ readonly comments: ReadonlyArray<AnchoredComment> }>,
205): string {
206 if (!/^pullrequestreview-\d+$/i.test(anchor)) return anchor;
207 if (comments.some((comment) => pullRequestAnchorMatchesUrl(anchor, comment.url))) return anchor;
208 // The earliest comment the review posted; `toSorted` is missing from Hermes.
209 let posted: AnchoredComment | undefined;
210 for (const comment of reviewThreads.flatMap((thread) => thread.comments)) {
211 if (comment.url === null || !pullRequestAnchorMatchesUrl(anchor, comment.reviewUrl)) continue;
212 if (posted === undefined || comment.createdAt < posted.createdAt) posted = comment;
213 }
214 const own = posted ? normalizePullRequestCommentAnchor(pullRequestUrlHash(posted.url)) : "";
215 return own || anchor;
217​
218export function pullRequestDiffPathMatches(digest: string, path: string): boolean {
219 const bytes = utf8ToBytes(path);
220 // GitLab uses SHA-1, abbreviated to 9 characters in Rapid Diffs line anchors.
221 if (digest.length === 40 || digest.length === 9)
222 return bytesToHex(sha1(bytes)).startsWith(digest);
223 return digest === bytesToHex(digest.length === 32 ? md5(bytes) : sha256(bytes));
225​
226export function pullRequestLinkCommit(url: string | null | undefined): string | null {
227 if (!url) return null;
228 try {
229 const { pathname, searchParams } = new URL(url);
230 const commit = /\/-\/merge_requests\/\d+\/diffs\/?$/i.test(pathname)
231 ? searchParams.get("commit_id")
232 : /\/pulls?\/\d+\/commits\/([a-f0-9]+)\/?$/i.exec(pathname)?.[1];
233 return commit && COMMIT_ID.test(commit) ? commit.toLowerCase() : null;
234 } catch {
235 return null;
236 }