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

definition.ts

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