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