Open History to see the last commit
1import { makeProviderSettingsSchema, SourceControlProviderKind } from "@t3tools/contracts";
2import {
3 changeRequestUrlBelow,
4 defineSourceControl,
5 hostCredentialSettingsFields,
6 isChangeRequestInProjectRepository,
7 isChangeRequestOnProjectHost,
8 parseChangeRequestPath,
9 projectChangeRequestHost,
10 remoteWebOrigin,
11} from "@t3tools/source-control-core/shared/definition";
12
13import { gitHubMediaUrl } from "./gitHubMedia.ts";
14import { icon } from "./icon.ts";
15import { gitHubReferenceAutolinks } from "./referenceAutolinks.ts";
16
17const CHECKOUT_COMMAND = /^gh\s+pr\s+checkout\s+(.+)$/i;
18const CHANGE_REQUEST_REFERENCE =
19 /^https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/(\d+)(?:[/?#].*)?$/i;
20
21// GitHub Enterprise Server runs on any hostname, so the `<owner>/<repo>/pull/<n>` route alone
22// identifies a GitHub pull request.
23const CHANGE_REQUEST_PATH = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u;
24const ISSUE_PATH = /^\/([^/]+\/[^/]+)\/issues\/(\d+)(?:\/|$)/u;
25
26const KIND = SourceControlProviderKind.make("github");
27
28function isGitHubHost(hostname: string): boolean {
29 const host = hostname.toLowerCase();
30 return (
31 host === "github.com" || host.endsWith(".github.com") || host.split(".").includes("github")
32 );
33}
34
35function isRepositoryPath(repository: string): boolean {
36 const segments = repository.split("/");
37 return (
38 segments.length === 2 &&
39 // GitHub owner and repository names are only these characters, so nothing here can
40 // be an encoded dot segment, query or fragment that `new URL` would reinterpret.
41 segments.every((segment) => /^[\w.-]+$/u.test(segment) && segment !== "." && segment !== "..")
42 );
43}
44
45export const settings = makeProviderSettingsSchema(hostCredentialSettingsFields);
46export type GitHubSettings = typeof settings.Type;
47
48export const definition = defineSourceControl({
49 kind: KIND,
50 label: "GitHub",
51 pickerLabel: "GitHub",
52 icon,
53 searchKeywords: ["ghes", "enterprise"],
54 credentials: {
55 cliName: "gh",
56 cliLabel: "GitHub CLI",
57 loginCommand: "gh auth login",
58 tokenEnvVar: "GH_TOKEN",
59 tokenAccess: "read and write access to pull requests and contents",
60 newTokenUrl: (host) => `https://${host}/settings/personal-access-tokens/new`,
61 },
62 changeRequest: {
63 shortLabel: "PR",
64 shortLabelWithArticle: "a PR",
65 singular: "pull request",
66 plural: "pull requests",
67 },
68 repositoryPathHint: "owner/repo",
69 publicHost: "github.com",
70 publishDescription: "github.com",
71 publishHost: () => "github.com",
72 newRepositoryOwner: (account) => ({ owner: account }),
73 defaultCloneTransport: "https",
74 changeRequestUrl: ({ host, repository, number, remoteUrl, webUrl }) => {
75 if (!Number.isSafeInteger(number) || number < 1) return null;
76 if (webUrl) return changeRequestUrlBelow(webUrl, `pull/${number}`);
77 if (!isRepositoryPath(repository)) return null;
78 try {
79 return new URL(`/${repository}/pull/${number}`, remoteWebOrigin(host, remoteUrl)).toString();
80 } catch {
81 return null;
82 }
83 },
84 parseChangeRequestUrl: (url) => parseChangeRequestPath(url, CHANGE_REQUEST_PATH),
85 // GitHub writes every bare reference through `/issues/`, including pull requests.
86 changeRequestUrlFromReferenceAutolink: (url) => {
87 const match = isGitHubHost(url.hostname) ? ISSUE_PATH.exec(url.pathname) : null;
88 if (match?.[1] === undefined || match[2] === undefined) return null;
89 const candidate = new URL(url);
90 candidate.pathname = `/${match[1]}/pull/${match[2]}`;
91 return candidate.toString();
92 },
93 changeRequestActions: new Set([
94 "merge",
95 "ready",
96 "draft",
97 "close",
98 "reopen",
99 "delete-branch",
100 "update-branch",
101 "enable-auto-merge",
102 "disable-auto-merge",
103 "revert",
104 "approve-workflows",
105 ] as const),
106 checkoutCommand: ({ number }) => `gh pr checkout ${number}`,
107 changeRequestCloseCommand: /\bgh\s+(?:pr\s+(?:merge|close)|stack\s+merge)\b/u,
108 changeRequestCreateCommand: /\bgh\s+pr\s+create\b/u,
109 authorProfileUrl: (login, repositoryUrl) =>
110 login.endsWith("[bot]")
111 ? null
112 : new URL(`/${encodeURIComponent(login)}`, repositoryUrl).toString(),
113 referenceAutolinks: gitHubReferenceAutolinks,
114 changeRequestChecksUrl: (changeRequestUrl) => `${changeRequestUrl.replace(/\/+$/u, "")}/checks`,
115 // Before servers reported their actions, GitHub was the only host they acted on from a list.
116 changeRequestActionsWhenUnreported: new Set(["close", "merge", "ready", "reopen"] as const),
117 // One search reads every repository on the host.
118 changeRequestListScope: "host",
119 reviewSummaryRequired: () => false,
120 checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
121 isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
122 checkoutChangeRequestHost: (identity) => projectChangeRequestHost(identity, KIND),
123 changeRequestHeadRef: (number) => `refs/pull/${number}/head`,
124 // `*.ghe.com` is GitHub Enterprise Cloud with data residency, one subdomain per enterprise.
125 recognizeRemote: ({ host, hostname }) =>
126 hostname === "github.com" ||
127 hostname.endsWith(".ghe.com") ||
128 hostname.split(".").includes("github")
129 ? {
130 kind: KIND,
131 name: hostname === "github.com" ? "GitHub" : "GitHub Self-Hosted",
132 baseUrl: `https://${host}`,
133 }
134 : null,
135 isChangeRequestInRepository: (identity, link) =>
136 isChangeRequestInProjectRepository(projectChangeRequestHost(identity, KIND), identity, link),
137 canReadChangeRequestOnHost: (identity, link) =>
138 isChangeRequestOnProjectHost(projectChangeRequestHost(identity, KIND), identity, link),
139 mediaUrl: gitHubMediaUrl,
140 settings,
141});