The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import type { ReferenceAutolink } from "@t3tools/source-control-core/shared/definition"; |
| 2 | |
| 3 | // GitHub's autolinked references: `#12`, `repo#12` and `owner/repo#12`; a SHA of 7 to 40 |
| 4 | // characters, optionally `repo@` or `owner/repo@` qualified; `@user` and `@org/team`. |
| 5 | const REFERENCE = |
| 6 | /(?<![\w./\\-])(?:([\w.-]+\/[\w.-]+|[\w-]+)?#([1-9]\d*)|(?:([\w.-]+\/[\w.-]+|[\w-]+)@)?([a-f\d]{7,40})(?![\w])|@([a-z\d](?:[a-z\d-]*[a-z\d])?(?:\/[a-z\d][a-z\d-]*)?))(?![\w])/giu; |
| 7 | const CANDIDATE = /[#@]|\b[a-f\d]{7,40}\b/iu; |
| 8 | const SHORT_SHA_LENGTH = 7; |
| 9 | |
| 10 | export function gitHubReferenceAutolinks( |
| 11 | text: string, |
| 12 | repositoryUrl: string, |
| 13 | ): ReadonlyArray<ReferenceAutolink> { |
| 14 | if (!CANDIDATE.test(text)) return []; |
| 15 | let url: URL; |
| 16 | try { |
| 17 | url = new URL(repositoryUrl); |
| 18 | } catch { |
| 19 | return []; |
| 20 | } |
| 21 | const [owner, repo] = url.pathname.split("/").filter(Boolean); |
| 22 | if (!owner || !repo || !/^https?:$/u.test(url.protocol)) return []; |
| 23 | const repository = (qualifier: string | undefined) => |
| 24 | qualifier?.includes("/") ? qualifier : qualifier ? `${qualifier}/${repo}` : `${owner}/${repo}`; |
| 25 | const links: ReferenceAutolink[] = []; |
| 26 | for (const match of text.matchAll(REFERENCE)) { |
| 27 | const [matched, issueRepo, number, commitRepo, sha, mention] = match; |
| 28 | if (number) { |
| 29 | links.push({ |
| 30 | index: match.index, |
| 31 | text: matched, |
| 32 | label: matched, |
| 33 | url: `${url.origin}/${repository(issueRepo)}/issues/${number}`, |
| 34 | kind: "reference", |
| 35 | }); |
| 36 | } else if (sha) { |
| 37 | // A run of digits is a number far more often than a SHA. |
| 38 | if (!/[a-f]/iu.test(sha)) continue; |
| 39 | links.push({ |
| 40 | index: match.index, |
| 41 | text: matched, |
| 42 | label: `${commitRepo ? `${commitRepo}@` : ""}${sha.slice(0, SHORT_SHA_LENGTH)}`, |
| 43 | url: `${url.origin}/${repository(commitRepo)}/commit/${sha}`, |
| 44 | kind: "commit", |
| 45 | }); |
| 46 | } else if (mention) { |
| 47 | const [organization, team] = mention.split("/"); |
| 48 | links.push({ |
| 49 | index: match.index, |
| 50 | text: matched, |
| 51 | label: matched, |
| 52 | url: `${url.origin}/${team ? `orgs/${organization}/teams/${team}` : mention}`, |
| 53 | kind: "mention", |
| 54 | }); |
| 55 | } |
| 56 | } |
| 57 | return links; |
| 58 | } |