Open History to see the last commit
1import type { ReferenceAutolink } from "@t3tools/source-control-core/shared/definition";
2
3// GitLab's autolinked references: `#12` issues and `!12` merge requests, qualified by
4// `project` (same namespace) or a full `group/sub/project` path; `GL-12` and `[issue:12]`
5// (or `[issue:project/12]`) issues; a SHA of 7 to 40 characters,
6// optionally qualified the same way with `@`; `@user` and `@group/subgroup`.
7const PROJECT = String.raw`[\w.-]+(?:\/[\w.-]+)*`;
8const REFERENCE = new RegExp(
9 String.raw`(?<![\w./\\-])(?:(${PROJECT})?([#!])([1-9]\d*)|(?:(${PROJECT})@)?([a-f\d]{7,40})(?![\w])|@([\w](?:[\w.-]*[\w])?(?:\/[\w](?:[\w.-]*[\w])?)*)|GL-([1-9]\d*)|\[issue:(?:(${PROJECT})\/)?([1-9]\d*)\])(?![\w])`,
10 "giu",
11);
12const CANDIDATE = /[#!@]|\bGL-\d|\[issue:|\b[a-f\d]{7,40}\b/iu;
13const SHORT_SHA_LENGTH = 7;
14const ROUTE = { "#": "issues", "!": "merge_requests" } as const;
15
16export function gitLabReferenceAutolinks(
17 text: string,
18 repositoryUrl: string,
19): ReadonlyArray<ReferenceAutolink> {
20 if (!CANDIDATE.test(text)) return [];
21 let url: URL;
22 try {
23 url = new URL(repositoryUrl);
24 } catch {
25 return [];
26 }
27 const path = url.pathname.split("/").filter(Boolean);
28 if (path.length < 2 || !/^https?:$/u.test(url.protocol)) return [];
29 const namespace = path.slice(0, -1).join("/");
30 const project = (qualifier: string | undefined) =>
31 qualifier?.includes("/") ? qualifier : qualifier ? `${namespace}/${qualifier}` : path.join("/");
32 const links: ReferenceAutolink[] = [];
33 for (const match of text.matchAll(REFERENCE)) {
34 const [
35 matched,
36 referenceProject,
37 sigil,
38 number,
39 commitProject,
40 sha,
41 mention,
42 prefixedIssue,
43 bracketProject,
44 bracketIssue,
45 ] = match;
46 if (number && (sigil === "#" || sigil === "!")) {
47 links.push({
48 index: match.index,
49 text: matched,
50 label: matched,
51 url: `${url.origin}/${project(referenceProject)}/-/${ROUTE[sigil]}/${number}`,
52 kind: "reference",
53 });
54 } else if (bracketIssue || (prefixedIssue && matched.startsWith("GL-"))) {
55 links.push({
56 index: match.index,
57 text: matched,
58 label: matched,
59 url: `${url.origin}/${project(bracketProject)}/-/issues/${bracketIssue ?? prefixedIssue}`,
60 kind: "reference",
61 });
62 } else if (sha) {
63 // A run of digits is a number far more often than a SHA.
64 if (!/[a-f]/iu.test(sha)) continue;
65 links.push({
66 index: match.index,
67 text: matched,
68 label: `${commitProject ? `${commitProject}@` : ""}${sha.slice(0, SHORT_SHA_LENGTH)}`,
69 url: `${url.origin}/${project(commitProject)}/-/commit/${sha}`,
70 kind: "commit",
71 });
72 } else if (mention && mention.toLowerCase() !== "all") {
73 links.push({
74 index: match.index,
75 text: matched,
76 label: matched,
77 url: `${url.origin}/${mention}`,
78 kind: "mention",
79 });
80 }
81 }
82 return links;
83}