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

definition.ts

165 lines6.8 KB

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