@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 167 lines 6.88 KB
Raw
1 import { makeProviderSettingsSchema, SourceControlProviderKind } from "@t3tools/contracts";
2 import {
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
18 import { gitHubMediaUrl, gitHubRawFileUrl } from "./gitHubMedia.ts";
19 import { icon } from "./icon.ts";
20 import { gitHubReferenceAutolinks } from "./referenceAutolinks.ts";
21
22 const CHECKOUT_COMMAND = /^gh\s+pr\s+checkout\s+(.+)$/i;
23 const 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.
28 const CHANGE_REQUEST_PATH = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u;
29 const COMMIT_PATH = /^\/([^/]+\/[^/]+)\/(?:commit|pull\/\d+\/commits)\/([0-9a-f]+)\/?$/iu;
30 const ISSUE_PATH = /^\/([^/]+\/[^/]+)\/issues\/(\d+)(?:\/|$)/u;
31 const REPOSITORY_PAGE_PATH = /^\/([^/]+\/[^/]+)\/(?:tree|blob)\/[^/]/u;
32
33 const KIND = SourceControlProviderKind.make("github");
34
35 function isGitHubHost(hostname: string): boolean {
36 const host = hostname.toLowerCase();
37 return host === "github.com" || host.endsWith(".ghe.com") || host.split(".").includes("github");
38 }
39
40 function 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 );
48 }
49
50 /** Signing in through the T3 Code for GitHub app lifts the per-user API rate limit to the app's. */
51 export 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
58 export const settings = makeProviderSettingsSchema(hostCredentialSettingsFields);
59 export type GitHubSettings = typeof settings.Type;
60
61 export 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, unless a known
105 // project's host vouches for it as a GitHub Enterprise Server.
106 parseIssueUrl: (url, known) =>
107 known || isGitHubHost(url.hostname) ? parseIssuePath(url, ISSUE_PATH) : null,
108 repositoryUrlFromPage: (url) =>
109 isGitHubHost(url.hostname) ? repositoryUrlFromPagePath(url, REPOSITORY_PAGE_PATH) : null,
110 // GitHub writes every bare reference through `/issues/`, including pull requests.
111 changeRequestUrlFromReferenceAutolink: (url) => {
112 const match = isGitHubHost(url.hostname) ? ISSUE_PATH.exec(url.pathname) : null;
113 if (match?.[1] === undefined || match[2] === undefined) return null;
114 const candidate = new URL(url);
115 candidate.pathname = `/${match[1]}/pull/${match[2]}`;
116 return candidate.toString();
117 },
118 changeRequestActions: new Set([
119 "merge",
120 "ready",
121 "draft",
122 "close",
123 "reopen",
124 "delete-branch",
125 "update-branch",
126 "enable-auto-merge",
127 "disable-auto-merge",
128 "revert",
129 "approve-workflows",
130 ] as const),
131 checkoutCommand: ({ number }) => `gh pr checkout ${number}`,
132 changeRequestCloseCommand: /\bgh\s+(?:pr\s+(?:merge|close)|stack\s+merge)\b/u,
133 // `new` is gh's alias for `create`.
134 changeRequestCreateCommand: /\bgh\s+pr\s+(?:create|new)\b/u,
135 authorProfileUrl: (login, repositoryUrl) =>
136 login.endsWith("[bot]")
137 ? null
138 : new URL(`/${encodeURIComponent(login)}`, repositoryUrl).toString(),
139 referenceAutolinks: gitHubReferenceAutolinks,
140 changeRequestChecksUrl: (changeRequestUrl) => `${changeRequestUrl.replace(/\/+$/u, "")}/checks`,
141 // Before servers reported their actions, GitHub was the only host they acted on from a list.
142 changeRequestActionsWhenUnreported: new Set(["close", "merge", "ready", "reopen"] as const),
143 // One search reads every repository on the host.
144 changeRequestListScope: "host",
145 hardLineBreaks: true,
146 reviewSummaryRequired: () => false,
147 checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
148 isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
149 checkoutChangeRequestHost: (identity) => projectChangeRequestHost(identity, KIND),
150 changeRequestHeadRef: (number) => `refs/pull/${number}/head`,
151 // `*.ghe.com` is GitHub Enterprise Cloud with data residency, one subdomain per enterprise.
152 recognizeRemote: ({ host, hostname }) =>
153 isGitHubHost(hostname)
154 ? {
155 kind: KIND,
156 name: hostname === "github.com" ? "GitHub" : "GitHub Self-Hosted",
157 baseUrl: `https://${host}`,
158 }
159 : null,
160 isChangeRequestInRepository: (identity, link) =>
161 isChangeRequestInProjectRepository(projectChangeRequestHost(identity, KIND), identity, link),
162 canReadChangeRequestOnHost: (identity, link) =>
163 isChangeRequestOnProjectHost(projectChangeRequestHost(identity, KIND), identity, link),
164 mediaUrl: gitHubMediaUrl,
165 rawFileUrl: gitHubRawFileUrl,
166 settings,
167 });