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

definition.ts

151 lines5.9 KB

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