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

definition.ts

156 lines6.3 KB

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