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

GitHubSourceControlProvider.ts

513 lines17.8 KB

1import * as Schema from "effect/Schema";
2import * as DateTime from "effect/DateTime";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import * as Result from "effect/Result";
6import {
7 DEFAULT_SERVER_SETTINGS,
8 SourceControlProviderError,
9 type ChangeRequest,
10 type GitHubSettings,
11 type SourceControlProviderDiscoveryItem,
12} from "@t3tools/contracts";
13​
14import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
15​
16import * as ServerSettings from "../serverSettings.ts";
17import * as GitHubApi from "./GitHubApi.ts";
18import * as GitHubCli from "./GitHubCli.ts";
19import {
20 effectiveGitHubAccount,
21 findAuthenticatedGitHubAccount,
22 parseGitHubAuthStatus,
23 type GitHubAuthStatusAccount,
24} from "./gitHubAuthStatus.ts";
25import * as SourceControlProvider from "./SourceControlProvider.ts";
26import {
27 combinedAuthOutput,
28 firstSafeAuthLine,
29 probeSourceControlProvider,
30 providerAuth,
31 type SourceControlAuthProbeInput,
32 type SourceControlCliDiscoverySpec,
33 type SourceControlManagedCliDiscoverySpec,
34} from "./SourceControlProviderDiscovery.ts";
35import * as VcsProcess from "../vcs/VcsProcess.ts";
36​
37const decodeLinkSubject = Schema.decodeUnknownEffect(
38 Schema.fromJsonString(
39 Schema.Struct({ title: Schema.String, body: Schema.optional(Schema.NullOr(Schema.String)) }),
40 ),
41);
42​
43function toChangeRequest(summary: GitHubCli.GitHubPullRequestSummary): ChangeRequest {
44 return {
45 provider: "github",
46 number: summary.number,
47 title: summary.title,
48 url: summary.url,
49 baseRefName: summary.baseRefName,
50 headRefName: summary.headRefName,
51 state: summary.state ?? "open",
52 ...(summary.isDraft === true ? { isDraft: true } : {}),
53 closedAt: summary.closedAt ?? null,
54 mergedAt: summary.mergedAt ?? null,
55 updatedAt:
56 summary.updatedAt === undefined
57 ? Option.none()
58 : Option.some(DateTime.makeUnsafe(summary.updatedAt)),
59 ...(summary.isCrossRepository !== undefined
60 ? { isCrossRepository: summary.isCrossRepository }
61 : {}),
62 ...(summary.headRepositoryNameWithOwner !== undefined
63 ? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
64 : {}),
65 ...(summary.headRepositoryOwnerLogin !== undefined
66 ? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
67 : {}),
68 };
70​
71function authAccounts(accounts: ReadonlyArray<GitHubAuthStatusAccount>) {
72 return accounts.map((entry) => ({
73 host: entry.host,
74 account: entry.account,
75 active: entry.active,
76 authenticated: entry.authenticated,
77 ...(entry.error === null ? {} : { error: entry.error }),
78 ...(entry.environmentVariable === null
79 ? {}
80 : { environmentVariable: entry.environmentVariable }),
81 }));
83​
84/**
85 * Reads `gh auth status --json hosts`. The headline account is the one GitHub requests will
86 * use: Settings can pin a login per host or turn a host off, and an environment token beats both.
87 */
88export function parseGitHubAuth(
89 input: SourceControlAuthProbeInput,
90 settings: GitHubSettings = DEFAULT_SERVER_SETTINGS.github,
91) {
92 const output = combinedAuthOutput(input);
93 const authStatus = parseGitHubAuthStatus(input.stdout);
94 const hosts = [...new Set(authStatus.accounts.map((entry) => entry.host))];
95 const fallback = findAuthenticatedGitHubAccount(authStatus.accounts);
96 // Lead with the host gh would pick, unless Settings turned it off.
97 const orderedHosts = fallback
98 ? [fallback.host, ...hosts.filter((host) => host !== fallback.host)]
99 : hosts;
100 const chosen = orderedHosts
101 .map((host) => effectiveGitHubAccount(host, authStatus.accounts, settings))
102 .find((entry) => entry !== undefined);
103 const accounts = authStatus.parsed ? { accounts: authAccounts(authStatus.accounts) } : {};
104​
105 if (chosen) {
106 return {
107 ...providerAuth({
108 status: "authenticated",
109 account: chosen.account,
110 host: chosen.host,
111 detail:
112 chosen.environmentVariable === null
113 ? undefined
114 : `Using ${chosen.environmentVariable} from the server environment; it overrides the account chosen in Settings.`,
115 }),
116 ...accounts,
117 };
118 }
119​
120 if (fallback) {
121 return {
122 ...providerAuth({
123 status: "unauthenticated",
124 host: fallback.host,
125 detail: "Every GitHub host gh is signed in to is turned off in Settings → Source Control.",
126 }),
127 ...accounts,
128 };
129 }
130​
131 const failedAccount = authStatus.accounts.find((entry) => entry.active) ?? authStatus.accounts[0];
132 if (authStatus.parsed) {
133 return {
134 ...providerAuth({
135 status: "unauthenticated",
136 host: failedAccount?.host,
137 detail:
138 failedAccount?.error ??
139 "Run `gh auth login` to authenticate GitHub CLI with an active account.",
140 }),
141 ...accounts,
142 };
143 }
144​
145 // gh gained `auth status --json` in 2.81.0. Older versions reject the flag and exit
146 // non-zero, which reads exactly like a signed-out CLI. Name the real problem instead.
147 if (input.exitCode !== 0 && output.includes("unknown flag: --json")) {
148 return providerAuth({
149 status: "unknown",
150 detail:
151 "GitHub CLI is too old to report sign-in status. Update `gh` to 2.81.0 or newer (for example `brew upgrade gh`) and rescan.",
152 });
153 }
154​
155 if (input.exitCode !== 0) {
156 return providerAuth({
157 status: "unauthenticated",
158 detail: firstSafeAuthLine(output) ?? "Run `gh auth login` to authenticate GitHub CLI.",
159 });
160 }
161​
162 return providerAuth({
163 status: "unknown",
164 detail: firstSafeAuthLine(output) ?? "GitHub CLI auth status could not be parsed.",
165 });
167​
168export const discovery = {
169 type: "cli",
170 kind: "github",
171 label: "GitHub",
172 executable: "gh",
173 versionArgs: ["--version"],
174 authArgs: ["auth", "status", "--json", "hosts"],
175 parseAuth: parseGitHubAuth,
176 installHint:
177 "Install the GitHub command-line tool (`gh`) via https://cli.github.com/ or your package manager (for example `brew install gh`).",
178} satisfies SourceControlCliDiscoverySpec;
179​
180const decodeViewer = Schema.decodeUnknownOption(
181 Schema.fromJsonString(Schema.Struct({ login: Schema.String })),
182);
183​
184/** The environment variable gh would take a github.com token from, if one is set. */
185function environmentTokenVariable(environment: NodeJS.ProcessEnv): string | null {
186 return ["GH_TOKEN", "GITHUB_TOKEN"].find((name) => environment[name]?.trim()) ?? null;
188​
189/**
190 * GitHub is usable with a token saved in Settings, one from the environment, or `gh` to hand one
191 * over. Reads the
192 * GitHub settings on every probe, so a saved account choice shows on rescan. An environment
193 * token is checked against the API, since `gh auth status` may not know it.
194 */
195export const makeDiscovery = Effect.gen(function* () {
196 const api = yield* GitHubApi.GitHubApi;
197 const process = yield* VcsProcess.VcsProcess;
198 const environment = yield* HostProcessEnvironment;
199 const serverSettings = yield* ServerSettings.ServerSettingsService;
200​
201 return {
202 type: "managed-cli",
203 kind: discovery.kind,
204 label: discovery.label,
205 installHint: discovery.installHint,
206 probe: Effect.fn("GitHubSourceControlProvider.discovery")(function* (cwd: string) {
207 const settings = yield* serverSettings.getSettings.pipe(
208 Effect.map((current) => current.github),
209 Effect.orElseSucceed(() => DEFAULT_SERVER_SETTINGS.github),
210 );
211 const cli = yield* probeSourceControlProvider({
212 cwd,
213 process,
214 spec: { ...discovery, parseAuth: (input) => parseGitHubAuth(input, settings) },
215 });
216 // A token saved in Settings wins over the environment, which wins over gh.
217 const savedToken = (settings.tokens["github.com"] ?? "").trim() !== "";
218 const variable = environmentTokenVariable(environment);
219 const tokenSource = savedToken ? "the token saved in Settings" : variable;
220 // A host turned off in Settings stays off even with a token.
221 if (tokenSource === null || settings.hosts["github.com"]?.enabled === false) return cli;
222 const viewer = yield* api
223 .rest({ host: "github.com", operation: "discovery", path: "user" })
224 .pipe(Effect.result);
225 const login = Result.isSuccess(viewer)
226 ? Option.getOrUndefined(decodeViewer(viewer.success.body))?.login
227 : undefined;
228 // The per-host logins stay, so the account picker still lists every host gh knows.
229 const accounts = cli.auth.accounts === undefined ? {} : { accounts: cli.auth.accounts };
230 return {
231 ...cli,
232 status: "available" as const,
233 auth: {
234 ...(login !== undefined
235 ? providerAuth({
236 status: "authenticated",
237 account: login,
238 host: "github.com",
239 detail: savedToken
240 ? "Using the token saved in Settings; it overrides GH_TOKEN and the gh login."
241 : `Using ${variable} from the server environment; it overrides the account chosen in Settings.`,
242 })
243 : Result.isFailure(viewer) && viewer.failure._tag !== "GitHubApiAuthenticationError"
244 ? // Only a refusal says the token is bad; a network error or a pause says nothing.
245 providerAuth({
246 status: "unknown",
247 host: "github.com",
248 detail: `Could not check ${savedToken ? tokenSource : `the token in ${tokenSource}`}: ${viewer.failure.message}`,
249 })
250 : providerAuth({
251 status: "unauthenticated",
252 host: "github.com",
253 detail: savedToken
254 ? "GitHub refused the token saved in Settings. Replace or remove it in Settings → Source Control."
255 : `GitHub refused the token in ${tokenSource}. Replace it, or unset it to use \`gh auth login\`.`,
256 })),
257 ...accounts,
258 },
259 } satisfies SourceControlProviderDiscoveryItem;
260 }),
261 refineUnknownRemote: () => Effect.succeed(null),
262 } satisfies SourceControlManagedCliDiscoverySpec;
263});
264​
265export const make = Effect.gen(function* () {
266 const github = yield* GitHubCli.GitHubCli;
267 const api = yield* GitHubApi.GitHubApi;
268​
269 const listChangeRequests: SourceControlProvider.SourceControlProvider["Service"]["listChangeRequests"] =
270 (input) => {
271 if (input.state === "open") {
272 return github
273 .listOpenPullRequests({
274 cwd: input.cwd,
275 headSelector: input.headSelector,
276 ...(input.context === undefined
277 ? {}
278 : { rateLimitHost: new URL(input.context.provider.baseUrl).host }),
279 ...(input.limit !== undefined ? { limit: input.limit } : {}),
280 })
281 .pipe(
282 Effect.map((items) => items.map(toChangeRequest)),
283 Effect.mapError(
284 (error) =>
285 new SourceControlProviderError({
286 provider: "github",
287 operation: "listChangeRequests",
288 command: error.command,
289 cwd: input.cwd,
290 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
291 input.headSelector,
292 ),
293 detail: error.message,
294 cause: error,
295 }),
296 ),
297 );
298 }
299​
300 return github
301 .listPullRequestsByHead({
302 cwd: input.cwd,
303 headSelector: input.headSelector,
304 state: input.state,
305 limit: input.limit ?? 20,
306 ...(input.context === undefined
307 ? {}
308 : { rateLimitHost: new URL(input.context.provider.baseUrl).host }),
309 })
310 .pipe(
311 Effect.map((items) =>
312 items.map(({ updatedAt, ...summary }) => ({
313 ...toChangeRequest({
314 ...summary,
315 ...(Option.isSome(updatedAt)
316 ? { updatedAt: DateTime.formatIso(updatedAt.value) }
317 : {}),
318 }),
319 updatedAt,
320 })),
321 ),
322 Effect.mapError(
323 (error) =>
324 new SourceControlProviderError({
325 provider: "github",
326 operation: "listChangeRequests",
327 command: error.command,
328 cwd: input.cwd,
329 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
330 input.headSelector,
331 ),
332 detail: error.message,
333 cause: error,
334 }),
335 ),
336 );
337 };
338​
339 const readLinkSubject = Effect.fn("GitHubSourceControlProvider.readLinkSubject")(function* (
340 input: { readonly cwd: string; readonly url: URL },
341 endpoint: string,
342 ) {
343 const result = yield* api
344 .rest({
345 host: input.url.host,
346 operation: "resolveLink",
347 path: endpoint,
348 maxResponseBytes: 1_000_000,
349 })
350 .pipe(
351 Effect.timeout("3 seconds"),
352 Effect.mapError(
353 (cause) =>
354 new SourceControlProviderError({
355 provider: "github",
356 operation: "resolveLink",
357 cwd: input.cwd,
358 detail: "The linked subject could not be read.",
359 cause,
360 }),
361 ),
362 );
363 const subject = yield* decodeLinkSubject(result.body).pipe(
364 Effect.mapError(
365 (cause) =>
366 new SourceControlProviderError({
367 provider: "github",
368 operation: "resolveLink.decode",
369 cwd: input.cwd,
370 detail: "The linked subject could not be read.",
371 cause,
372 }),
373 ),
374 );
375 return { title: subject.title, body: subject.body ?? null };
376 });
377​
378 return SourceControlProvider.SourceControlProvider.of({
379 kind: "github",
380 resolveLink: (input) => {
381 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
382 if (input.url.host !== "github.com") return undefined;
383 const match = /^\/([\w.-]+)\/([\w.-]+)\/(?:pull|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
384 input.url.pathname,
385 );
386 if (!match) return undefined;
387 return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);
388 },
389 listChangeRequests,
390 getChangeRequest: (input) =>
391 github
392 .getPullRequest({
393 ...input,
394 ...(input.context === undefined
395 ? {}
396 : { rateLimitHost: new URL(input.context.provider.baseUrl).host }),
397 })
398 .pipe(
399 Effect.map(toChangeRequest),
400 Effect.mapError(
401 (error) =>
402 new SourceControlProviderError({
403 provider: "github",
404 operation: "getChangeRequest",
405 command: error.command,
406 cwd: input.cwd,
407 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
408 input.reference,
409 ),
410 detail: error.message,
411 cause: error,
412 }),
413 ),
414 ),
415 createChangeRequest: (input) =>
416 github
417 .createPullRequest({
418 cwd: input.cwd,
419 baseBranch: input.baseRefName,
420 headSelector: input.headSelector,
421 title: input.title,
422 bodyFile: input.bodyFile,
423 })
424 .pipe(
425 Effect.mapError(
426 (error) =>
427 new SourceControlProviderError({
428 provider: "github",
429 operation: "createChangeRequest",
430 command: error.command,
431 cwd: input.cwd,
432 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
433 input.headSelector,
434 ),
435 detail: error.message,
436 cause: error,
437 }),
438 ),
439 ),
440 getRepositoryCloneUrls: (input) =>
441 github.getRepositoryCloneUrls(input).pipe(
442 Effect.mapError(
443 (error) =>
444 new SourceControlProviderError({
445 provider: "github",
446 operation: "getRepositoryCloneUrls",
447 command: error.command,
448 cwd: input.cwd,
449 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
450 input.repository,
451 ),
452 detail: error.message,
453 cause: error,
454 }),
455 ),
456 ),
457 createRepository: (input) =>
458 github.createRepository(input).pipe(
459 Effect.mapError(
460 (error) =>
461 new SourceControlProviderError({
462 provider: "github",
463 operation: "createRepository",
464 command: error.command,
465 cwd: input.cwd,
466 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
467 input.repository,
468 ),
469 detail: error.message,
470 cause: error,
471 }),
472 ),
473 ),
474 getDefaultBranch: (input) =>
475 github
476 .getDefaultBranch({
477 ...input,
478 ...(input.context === undefined
479 ? {}
480 : { rateLimitHost: new URL(input.context.provider.baseUrl).host }),
481 })
482 .pipe(
483 Effect.mapError(
484 (error) =>
485 new SourceControlProviderError({
486 provider: "github",
487 operation: "getDefaultBranch",
488 command: error.command,
489 cwd: input.cwd,
490 detail: error.message,
491 cause: error,
492 }),
493 ),
494 ),
495 checkoutChangeRequest: (input) =>
496 github.checkoutPullRequest(input).pipe(
497 Effect.mapError(
498 (error) =>
499 new SourceControlProviderError({
500 provider: "github",
501 operation: "checkoutChangeRequest",
502 command: error.command,
503 cwd: input.cwd,
504 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
505 input.reference,
506 ),
507 detail: error.message,
508 cause: error,
509 }),
510 ),
511 ),
512 });
513});