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

pullRequestMarkdown.logic.ts

52 lines1.7 KB

1import {
2 findAndReplaceText,
3 type MarkdownNode,
4 type TextMatch,
5} from "~/vendor/mdast-find-and-replace";
6​
7export {
8 splitPullRequestBody,
9 type PullRequestBodySegment,
10} from "@t3tools/client-runtime/pull-request-markdown";
11​
12const AUTOLINK_CANDIDATE_PATTERN = /#[1-9]\d*|[0-9a-f]{40}/giu;
13const AUTOLINK_WORD_CHARACTER_PATTERN = /[A-Za-z0-9_]/u;
14const AUTOLINK_COMMIT_PREFIX_PATTERN = /[\s([{]/u;
15const AUTOLINK_IGNORED_TYPES = new Set(["link", "linkReference"]);
16​
17export function remarkPullRequestAutolinks(options: { readonly repositoryUrl: string }) {
18 const repositoryUrl = options.repositoryUrl.replace(/\/+$/u, "");
19 return (tree: MarkdownNode) => {
20 findAndReplaceText(
21 tree,
22 AUTOLINK_CANDIDATE_PATTERN,
23 (matched: string, match: TextMatch) => {
24 const reference = matched.startsWith("#");
25 const before = match.input[match.index - 1];
26 const after = match.input[match.index + matched.length];
27 if (
28 (before !== undefined &&
29 (reference
30 ? AUTOLINK_WORD_CHARACTER_PATTERN.test(before)
31 : !AUTOLINK_COMMIT_PREFIX_PATTERN.test(before))) ||
32 (after !== undefined && AUTOLINK_WORD_CHARACTER_PATTERN.test(after))
33 ) {
34 return false;
35 }
36 return {
37 type: "link",
38 url: reference
39 ? `${repositoryUrl}/issues/${matched.slice(1)}`
40 : `${repositoryUrl}/commit/${matched}`,
41 data: {
42 hProperties: {
43 dataPullRequestAutolink: reference ? "reference" : "commit",
44 },
45 },
46 children: [{ type: "text", value: reference ? matched : matched.slice(0, 7) }],
47 };
48 },
49 AUTOLINK_IGNORED_TYPES,
50 );
51 };