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