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
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 }
65}
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;
72}
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 } : {}) };
83}
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 };
111}
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;
121}
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 gitLab = /\/-\/merge_requests\/\d+(?:\/|$)/i.test(parsed.pathname)
133 ? gitLabDiffAnchor(
134 anchor,
135 /\/-\/merge_requests\/\d+\/diffs\/?$/i.test(parsed.pathname)
136 ? parsed.searchParams.get("file")
137 : null,
138 )
139 : null;
140 if (gitLab) return gitLab;
141 if (!anchor) return fallback;
142 // GitHub line ranges may cross diff sides; file digests were MD5 before SHA-256.
143 const diff = /^diff-([a-f0-9]+)(?:([LR])(\d+)(?:-([LR])(\d+))?)?$/i.exec(anchor);
144 if (diff) {
145 const start = Number(diff[3]);
146 const end = Number(diff[5] ?? diff[3]);
147 if (
148 diff[2] &&
149 (!Number.isSafeInteger(start) || start < 1 || !Number.isSafeInteger(end) || end < 1)
150 )
151 return fallback;
152 return {
153 kind: "diff",
154 digest: (diff[1] ?? "").toLowerCase(),
155 range: diff[2]
156 ? {
157 start,
158 side: diff[2].toUpperCase() === "L" ? "left" : "right",
159 end,
160 endSide: (diff[4] ?? diff[2]).toUpperCase() === "L" ? "left" : "right",
161 }
162 : null,
163 };
164 }
165 if (
166 /^(?:(?:issuecomment-|pullrequestreview-|discussion_r|r|commitcomment-|event-|note_|comment-)\d+|discussion-diff-\d+(?:[LR]\d+(?:-[LR]\d+)?)?)$/i.test(
167 anchor,
168 )
169 ) {
170 return { kind: "timeline", anchor: normalizePullRequestCommentAnchor(anchor) };
171 }
172 return fallback ?? { kind: "summary", anchor };
173}
174
175export function pullRequestAnchorMatchesUrl(
176 anchor: string,
177 url: string | null | undefined,
178): boolean {
179 return (
180 normalizePullRequestCommentAnchor(pullRequestUrlHash(url)) ===
181 normalizePullRequestCommentAnchor(anchor)
182 );
183}
184
185interface AnchoredComment {
186 readonly url: string | null;
187 readonly createdAt: string;
188 readonly reviewUrl?: string | null | undefined;
189}
190
191/**
192 * A review with no text of its own appears only through the line comments it posted, so its link
193 * resolves to the earliest of those. Any other anchor, or a review shown in its own right, is kept.
194 */
195export function resolvePullRequestReviewAnchor(
196 anchor: string,
197 comments: ReadonlyArray<Pick<AnchoredComment, "url">>,
198 reviewThreads: ReadonlyArray<{ readonly comments: ReadonlyArray<AnchoredComment> }>,
199): string {
200 if (!/^pullrequestreview-\d+$/i.test(anchor)) return anchor;
201 if (comments.some((comment) => pullRequestAnchorMatchesUrl(anchor, comment.url))) return anchor;
202 // The earliest comment the review posted; `toSorted` is missing from Hermes.
203 let posted: AnchoredComment | undefined;
204 for (const comment of reviewThreads.flatMap((thread) => thread.comments)) {
205 if (comment.url === null || !pullRequestAnchorMatchesUrl(anchor, comment.reviewUrl)) continue;
206 if (posted === undefined || comment.createdAt < posted.createdAt) posted = comment;
207 }
208 const own = posted ? normalizePullRequestCommentAnchor(pullRequestUrlHash(posted.url)) : "";
209 return own || anchor;
210}
211
212export function pullRequestDiffPathMatches(digest: string, path: string): boolean {
213 const bytes = utf8ToBytes(path);
214 // GitLab uses SHA-1, abbreviated to 9 characters in Rapid Diffs line anchors.
215 if (digest.length === 40 || digest.length === 9)
216 return bytesToHex(sha1(bytes)).startsWith(digest);
217 return digest === bytesToHex(digest.length === 32 ? md5(bytes) : sha256(bytes));
218}
219
220export function pullRequestLinkCommit(url: string | null | undefined): string | null {
221 if (!url) return null;
222 try {
223 const { pathname, searchParams } = new URL(url);
224 const commit = /\/-\/merge_requests\/\d+\/diffs\/?$/i.test(pathname)
225 ? searchParams.get("commit_id")
226 : /\/pulls?\/\d+\/commits\/([a-f0-9]+)\/?$/i.exec(pathname)?.[1];
227 return commit && COMMIT_ID.test(commit) ? commit.toLowerCase() : null;
228 } catch {
229 return null;
230 }
231}