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

GitHubCli.ts

666 lines21.6 KB

1import * as Cache from "effect/Cache";
2import * as Duration from "effect/Duration";
3import * as Exit from "effect/Exit";
4import * as Context from "effect/Context";
5import * as DateTime from "effect/DateTime";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as PlatformError from "effect/PlatformError";
10import * as Redacted from "effect/Redacted";
11import * as Result from "effect/Result";
12import * as Schema from "effect/Schema";
13​
14import {
15 TrimmedNonEmptyString,
16 type SourceControlRepositoryVisibility,
17 type VcsError,
18 VcsProcessExitError,
19} from "@t3tools/contracts";
20​
21import * as VcsProcess from "../vcs/VcsProcess.ts";
22import * as GitHubGraphQlBudget from "./githubGraphQlBudget.ts";
23import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";
24import {
25 decodeGitHubPullRequestJson,
26 decodeGitHubPullRequestListJson,
27 type NormalizedGitHubPullRequestRecord,
28} from "./gitHubPullRequests.ts";
29​
30const DEFAULT_TIMEOUT_MS = 30_000;
31​
32/** Server-local credential scope; never put its value in RPC payloads or cache keys. */
33export const PinnedGitHubCredential = Context.Reference<{
34 readonly host: string;
35 readonly token: Redacted.Redacted<string>;
36 readonly credentialFingerprint: string;
37} | null>("t3/sourceControl/PinnedGitHubCredential", { defaultValue: () => null });
38​
39export const AllowGitHubReserve = Context.Reference<boolean>(
40 "t3/sourceControl/AllowGitHubReserve",
41 { defaultValue: () => false },
42);
43​
44function commandHosts(args: ReadonlyArray<string>): Array<string | null> {
45 const hosts: Array<string | null> = [];
46 const repositoryHost = (repository: string | undefined) => {
47 if (repository === undefined) return null;
48 if (/^https?:\/\//i.test(repository)) {
49 try {
50 return new URL(repository).host.toLowerCase();
51 } catch {
52 return null;
53 }
54 }
55 const parts = repository.split("/");
56 return parts.length === 3 ? parts[0]!.toLowerCase() : null;
57 };
58 if (args[0] === "repo" && args[1] === "view") hosts.push(repositoryHost(args[2]));
59 for (let index = 0; index < args.length; index++) {
60 const arg = args[index]!;
61 if (arg === "--hostname") hosts.push(args[++index]?.toLowerCase() ?? null);
62 else if (arg.startsWith("--hostname=")) hosts.push(arg.slice(11).toLowerCase());
63 else if (arg === "--repo" || arg === "-R") hosts.push(repositoryHost(args[++index]));
64 else if (arg.startsWith("--repo=")) hosts.push(repositoryHost(arg.slice(7)));
65 else if (arg.startsWith("-R")) hosts.push(repositoryHost(arg.slice(2)));
66 else if (/^https?:\/\//i.test(arg)) hosts.push(repositoryHost(arg));
67 }
68 return hosts;
70​
71function targetsVerifiedHost(args: ReadonlyArray<string>, host: string): boolean {
72 const hosts = commandHosts(args);
73 return hosts.length > 0 && hosts.every((target) => target === host);
75​
76const gitHubCliFailureFields = {
77 command: Schema.Literal("gh"),
78 cwd: Schema.String,
79 cause: Schema.Defect(),
80} as const;
81​
82export class GitHubCliUnavailableError extends Schema.TaggedError<GitHubCliUnavailableError>()(
83 "GitHubCliUnavailableError",
84 gitHubCliFailureFields,
85) {
86 get detail(): string {
87 return "GitHub CLI (`gh`) is required but not available on PATH.";
88 }
89​
90 override get message(): string {
91 return `GitHub CLI failed in execute: ${this.detail}`;
92 }
94​
95export class GitHubCliAuthenticationError extends Schema.TaggedError<GitHubCliAuthenticationError>()(
96 "GitHubCliAuthenticationError",
97 gitHubCliFailureFields,
98) {
99 get detail(): string {
100 return "GitHub CLI is not authenticated. Run `gh auth login` and retry.";
101 }
102​
103 override get message(): string {
104 return `GitHub CLI failed in execute: ${this.detail}`;
105 }
107​
108export class GitHubCliRateLimitError extends Schema.TaggedError<GitHubCliRateLimitError>()(
109 "GitHubCliRateLimitError",
110 { ...gitHubCliFailureFields, retryAt: Schema.optionalKey(Schema.Finite) },
111) {
112 get detail(): string {
113 return "GitHub API rate limit exceeded. Run `gh api rate_limit` to inspect the quota and reset time.";
114 }
115​
116 override get message(): string {
117 return `GitHub CLI failed in execute: ${this.detail}`;
118 }
120​
121export class GitHubPullRequestNotFoundError extends Schema.TaggedError<GitHubPullRequestNotFoundError>()(
122 "GitHubPullRequestNotFoundError",
123 gitHubCliFailureFields,
124) {
125 get detail(): string {
126 return "Pull request not found. Check the PR number or URL and try again.";
127 }
128​
129 override get message(): string {
130 return `GitHub CLI failed in execute: ${this.detail}`;
131 }
133​
134export class GitHubCliCommandError extends Schema.TaggedError<GitHubCliCommandError>()(
135 "GitHubCliCommandError",
136 gitHubCliFailureFields,
137) {
138 get detail(): string {
139 return (
140 (this.cause instanceof VcsProcessExitError ? this.cause.hostMessage : undefined) ??
141 "GitHub CLI command failed."
142 );
143 }
144​
145 override get message(): string {
146 return `GitHub CLI failed in execute: ${this.detail}`;
147 }
149​
150const gitHubCliDecodeFields = {
151 command: Schema.Literal("gh"),
152 cwd: Schema.String,
153 cause: Schema.Defect(),
154} as const;
155​
156export class GitHubPullRequestListDecodeError extends Schema.TaggedError<GitHubPullRequestListDecodeError>()(
157 "GitHubPullRequestListDecodeError",
158 gitHubCliDecodeFields,
159) {
160 get detail(): string {
161 return "GitHub CLI returned invalid PR list JSON.";
162 }
163​
164 override get message(): string {
165 return `GitHub CLI failed in listOpenPullRequests: ${this.detail}`;
166 }
168​
169export class GitHubChangeRequestListDecodeError extends Schema.TaggedError<GitHubChangeRequestListDecodeError>()(
170 "GitHubChangeRequestListDecodeError",
171 gitHubCliDecodeFields,
172) {
173 get detail(): string {
174 return "GitHub CLI returned invalid change request JSON.";
175 }
176​
177 override get message(): string {
178 return `GitHub CLI failed in listChangeRequests: ${this.detail}`;
179 }
181​
182export class GitHubPullRequestDecodeError extends Schema.TaggedError<GitHubPullRequestDecodeError>()(
183 "GitHubPullRequestDecodeError",
184 gitHubCliDecodeFields,
185) {
186 get detail(): string {
187 return "GitHub CLI returned invalid pull request JSON.";
188 }
189​
190 override get message(): string {
191 return `GitHub CLI failed in getPullRequest: ${this.detail}`;
192 }
194​
195export class GitHubRepositoryDecodeError extends Schema.TaggedError<GitHubRepositoryDecodeError>()(
196 "GitHubRepositoryDecodeError",
197 gitHubCliDecodeFields,
198) {
199 get detail(): string {
200 return "GitHub CLI returned invalid repository JSON.";
201 }
202​
203 override get message(): string {
204 return `GitHub CLI failed in getRepositoryCloneUrls: ${this.detail}`;
205 }
207​
208export const GitHubCliError = Schema.Union([
209 GitHubCliUnavailableError,
210 GitHubCliAuthenticationError,
211 GitHubCliRateLimitError,
212 GitHubPullRequestNotFoundError,
213 GitHubCliCommandError,
214 GitHubPullRequestListDecodeError,
215 GitHubChangeRequestListDecodeError,
216 GitHubPullRequestDecodeError,
217 GitHubRepositoryDecodeError,
218]);
219export type GitHubCliError = typeof GitHubCliError.Type;
220​
221export const isGitHubCliError = Schema.is(GitHubCliError);
222​
223export function fromVcsError(
224 context: {
225 readonly command: "gh";
226 readonly cwd: string;
227 },
228 error: VcsError,
229): GitHubCliError {
230 if (
231 error._tag === "VcsProcessSpawnError" &&
232 error.cause instanceof PlatformError.PlatformError &&
233 error.cause.reason._tag === "NotFound" &&
234 error.cause.reason.module === "ChildProcess" &&
235 error.cause.reason.method === "spawn"
236 ) {
237 return new GitHubCliUnavailableError({ ...context, cause: error });
238 }
239​
240 if (error._tag === "VcsProcessExitError") {
241 if (error.failureKind === "authentication") {
242 return new GitHubCliAuthenticationError({ ...context, cause: error });
243 }
244 if (error.failureKind === "rate-limited") {
245 return new GitHubCliRateLimitError({ ...context, cause: error });
246 }
247 if (error.failureKind === "not-found") {
248 return new GitHubPullRequestNotFoundError({ ...context, cause: error });
249 }
250 }
251​
252 return new GitHubCliCommandError({ ...context, cause: error });
254​
255export interface GitHubPullRequestSummary {
256 readonly number: number;
257 readonly title: string;
258 readonly url: string;
259 readonly baseRefName: string;
260 readonly headRefName: string;
261 readonly state?: "open" | "closed" | "merged";
262 readonly isDraft?: boolean;
263 readonly closedAt?: string | null;
264 readonly mergedAt?: string | null;
265 readonly updatedAt?: string;
266 readonly isCrossRepository?: boolean;
267 readonly headRepositoryNameWithOwner?: string | null;
268 readonly headRepositoryOwnerLogin?: string | null;
270​
271function pullRequestSummary(input: NormalizedGitHubPullRequestRecord): GitHubPullRequestSummary {
272 const { updatedAt, ...summary } = input;
273 return {
274 ...summary,
275 ...(Option.isSome(updatedAt) ? { updatedAt: DateTime.formatIso(updatedAt.value) } : {}),
276 };
278​
279export interface GitHubRepositoryCloneUrls {
280 readonly nameWithOwner: string;
281 readonly url: string;
282 readonly sshUrl: string;
284​
285export class GitHubCli extends Context.Service<
286 GitHubCli,
287 {
288 readonly execute: (input: {
289 readonly cwd: string;
290 readonly args: ReadonlyArray<string>;
291 readonly timeoutMs?: number;
292 /** Piped to the child's stdin, for payloads that must never appear in argv. */
293 readonly stdin?: string;
294 readonly env?: NodeJS.ProcessEnv;
295 readonly maxOutputBytes?: number;
296 readonly rateLimitHost?: string;
297 readonly allowReserve?: boolean;
298 }) => Effect.Effect<VcsProcess.VcsProcessOutput, GitHubCliError>;
299​
300 readonly listOpenPullRequests: (input: {
301 readonly cwd: string;
302 readonly headSelector: string;
303 readonly limit?: number;
304 readonly rateLimitHost?: string;
305 }) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
306​
307 readonly getPullRequest: (input: {
308 readonly cwd: string;
309 readonly reference: string;
310 readonly rateLimitHost?: string;
311 }) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
312​
313 readonly getRepositoryCloneUrls: (input: {
314 readonly cwd: string;
315 readonly repository: string;
316 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
317​
318 readonly createRepository: (input: {
319 readonly cwd: string;
320 readonly repository: string;
321 readonly visibility: SourceControlRepositoryVisibility;
322 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
323​
324 readonly createPullRequest: (input: {
325 readonly cwd: string;
326 readonly baseBranch: string;
327 readonly headSelector: string;
328 readonly title: string;
329 readonly bodyFile: string;
330 }) => Effect.Effect<void, GitHubCliError>;
331​
332 readonly getDefaultBranch: (input: {
333 readonly cwd: string;
334 readonly rateLimitHost?: string;
335 }) => Effect.Effect<string | null, GitHubCliError>;
336​
337 readonly checkoutPullRequest: (input: {
338 readonly cwd: string;
339 readonly reference: string;
340 readonly force?: boolean;
341 }) => Effect.Effect<void, GitHubCliError>;
342 }
343>()("t3/sourceControl/GitHubCli") {}
344​
345const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
346 nameWithOwner: TrimmedNonEmptyString,
347 url: TrimmedNonEmptyString,
348 sshUrl: TrimmedNonEmptyString,
349});
350const decodeRawGitHubRepositoryCloneUrls = Schema.decodeEffect(
351 Schema.fromJsonString(RawGitHubRepositoryCloneUrlsSchema),
352);
353​
354function normalizeRepositoryCloneUrls(
355 raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
356): GitHubRepositoryCloneUrls {
357 return {
358 nameWithOwner: raw.nameWithOwner,
359 url: raw.url,
360 sshUrl: raw.sshUrl,
361 };
363​
364/**
365 * `gh repo create` prints the canonical URL of the new repository on stdout
366 * (e.g. `https://github.com/owner/repo`). Reading it back here avoids a
367 * follow-up `gh repo view`, which can race GitHub's GraphQL eventual
368 * consistency window and falsely report the just-created repo as missing.
369 */
370function deriveRepositoryCloneUrlsFromCreateOutput(
371 stdout: string,
372 repository: string,
373): GitHubRepositoryCloneUrls {
374 const fallbackHost = "github.com";
375 const match = stdout.match(/https?:\/\/[^\s]+/);
376 if (match) {
377 const cleaned = match[0].replace(/\.git$/, "");
378 try {
379 const parsed = new URL(cleaned);
380 const pathname = parsed.pathname.replace(/^\/+|\/+$/g, "");
381 const segments = pathname.split("/").filter(Boolean);
382 if (segments.length === 2) {
383 const nameWithOwner = `${segments[0]}/${segments[1]}`;
384 return {
385 nameWithOwner,
386 url: `${parsed.origin}/${nameWithOwner}`,
387 sshUrl: `git@${parsed.host}:${nameWithOwner}.git`,
388 };
389 }
390 } catch {
391 // Fall through to the input-derived defaults below.
392 }
393 }
394 return {
395 nameWithOwner: repository,
396 url: `https://${fallbackHost}/${repository}`,
397 sshUrl: `git@${fallbackHost}:${repository}.git`,
398 };
400​
401/** @public Service construction is part of the canonical Effect module API. */
402export const make = Effect.gen(function* () {
403 const process = yield* VcsProcess.VcsProcess;
404 const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;
405 const limits = yield* SourceControlRateLimit.SourceControlRateLimit;
406​
407 const executeRaw: GitHubCli["Service"]["execute"] = Effect.fn("GitHubCli.executeRaw")(
408 function* (input) {
409 const credential = yield* PinnedGitHubCredential;
410 if (credential !== null && !targetsVerifiedHost(input.args, credential.host)) {
411 return yield* new GitHubCliCommandError({
412 command: "gh",
413 cwd: input.cwd,
414 cause: new Error("The GitHub command does not target the verified credential's host."),
415 });
416 }
417 const token = credential === null ? undefined : Redacted.value(credential.token);
418 const env =
419 credential === null
420 ? input.env
421 : {
422 ...input.env,
423 GH_HOST: credential.host,
424 GH_TOKEN: token,
425 GITHUB_TOKEN: token,
426 GH_ENTERPRISE_TOKEN: token,
427 GITHUB_ENTERPRISE_TOKEN: token,
428 GH_DEBUG: "",
429 };
430 return yield* process
431 .run({
432 operation: "GitHubCli.execute",
433 command: "gh",
434 args: input.args,
435 cwd: input.cwd,
436 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
437 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
438 ...(env !== undefined ? { env } : {}),
439 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
440 })
441 .pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
442 },
443 );
444​
445 const quota = yield* Cache.makeWith(
446 (key: string) => {
447 const host = key.split("\0")[0]!;
448 return executeRaw({
449 cwd: globalThis.process.cwd(),
450 args: [
451 "api",
452 "rate_limit",
453 "--hostname",
454 host,
455 "--jq",
456 ".resources.graphql | {data:{rateLimit:{cost:1,limit:.limit,remaining:.remaining,resetAt:(.reset|todateiso8601)}}}",
457 ],
458 }).pipe(
459 Effect.tap((result) => budget.observe(host, result.stdout)),
460 Effect.asVoid,
461 );
462 },
463 {
464 capacity: 32,
465 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.seconds(30) : Duration.zero),
466 },
467 );
468 const execute: GitHubCli["Service"]["execute"] = Effect.fn("GitHubCli.execute")(
469 function* (input) {
470 const [command, action] = input.args;
471 if (
472 !(
473 (command === "pr" && (action === "list" || action === "view")) ||
474 (command === "repo" && action === "view")
475 )
476 )
477 return yield* executeRaw(input);
478 const credential = yield* PinnedGitHubCredential;
479 if (credential !== null && !targetsVerifiedHost(input.args, credential.host))
480 return yield* executeRaw(input);
481 const allowReserve = input.allowReserve ?? (yield* AllowGitHubReserve);
482 const host = (
483 credential?.host ??
484 commandHosts(input.args).find((host) => host !== null) ??
485 input.rateLimitHost ??
486 input.env?.GH_HOST ??
487 globalThis.process.env.GH_HOST ??
488 "github.com"
489 ).toLowerCase();
490 const key = { provider: "github" as const, host };
491 const guarded = Effect.gen(function* () {
492 const lease = yield* limits.check(key, allowReserve ? { allowPaused: true } : undefined);
493 return yield* Effect.gen(function* () {
494 yield* Cache.get(quota, `${host}\0${credential?.credentialFingerprint ?? ""}`);
495 yield* budget.query(host, "query {}", allowReserve ? { allowReserve: true } : undefined);
496 return yield* executeRaw(input);
497 }).pipe(
498 Effect.tap(() => limits.recordSuccess({ ...key, lease })),
499 Effect.tapError((error) =>
500 error._tag === "GitHubCliRateLimitError"
501 ? limits.recordRateLimit({ ...key, lease })
502 : Effect.void,
503 ),
504 );
505 });
506 return yield* guarded.pipe(
507 Effect.provideService(
508 SourceControlRateLimit.CredentialScope,
509 credential?.credentialFingerprint ?? (yield* SourceControlRateLimit.CredentialScope),
510 ),
511 Effect.catchTags({
512 SourceControlRateLimitPausedError: (cause) =>
513 Effect.fail(
514 new GitHubCliRateLimitError({
515 command: "gh",
516 cwd: input.cwd,
517 retryAt: cause.retryAt,
518 cause,
519 }),
520 ),
521 }),
522 );
523 },
524 );
525​
526 return GitHubCli.of({
527 execute,
528 listOpenPullRequests: (input) =>
529 execute({
530 cwd: input.cwd,
531 ...(input.rateLimitHost === undefined ? {} : { rateLimitHost: input.rateLimitHost }),
532 allowReserve: true,
533 args: [
534 "pr",
535 "list",
536 "--head",
537 input.headSelector,
538 "--state",
539 "open",
540 "--limit",
541 String(input.limit ?? 1),
542 "--json",
543 "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,isCrossRepository,headRepository,headRepositoryOwner",
544 ],
545 }).pipe(
546 Effect.map((result) => result.stdout.trim()),
547 Effect.flatMap((raw) =>
548 raw.length === 0
549 ? Effect.succeed([])
550 : Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
551 Effect.flatMap((decoded) => {
552 if (!Result.isSuccess(decoded)) {
553 return Effect.fail(
554 new GitHubPullRequestListDecodeError({
555 command: "gh",
556 cwd: input.cwd,
557 cause: decoded.failure,
558 }),
559 );
560 }
561​
562 return Effect.succeed(decoded.success.map(pullRequestSummary));
563 }),
564 ),
565 ),
566 ),
567 getPullRequest: (input) =>
568 execute({
569 cwd: input.cwd,
570 ...(input.rateLimitHost === undefined ? {} : { rateLimitHost: input.rateLimitHost }),
571 allowReserve: true,
572 args: [
573 "pr",
574 "view",
575 input.reference,
576 "--json",
577 "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
578 ],
579 }).pipe(
580 Effect.map((result) => result.stdout.trim()),
581 Effect.flatMap((raw) =>
582 Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
583 Effect.flatMap((decoded) => {
584 if (!Result.isSuccess(decoded)) {
585 return Effect.fail(
586 new GitHubPullRequestDecodeError({
587 command: "gh",
588 cwd: input.cwd,
589 cause: decoded.failure,
590 }),
591 );
592 }
593​
594 return Effect.succeed(pullRequestSummary(decoded.success));
595 }),
596 ),
597 ),
598 ),
599 getRepositoryCloneUrls: (input) =>
600 execute({
601 cwd: input.cwd,
602 args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
603 }).pipe(
604 Effect.map((result) => result.stdout.trim()),
605 Effect.flatMap((raw) =>
606 decodeRawGitHubRepositoryCloneUrls(raw).pipe(
607 Effect.mapError(
608 (cause) =>
609 new GitHubRepositoryDecodeError({
610 command: "gh",
611 cwd: input.cwd,
612 cause,
613 }),
614 ),
615 ),
616 ),
617 Effect.map(normalizeRepositoryCloneUrls),
618 ),
619 createRepository: (input) =>
620 execute({
621 cwd: input.cwd,
622 args: ["repo", "create", input.repository, `--${input.visibility}`],
623 }).pipe(
624 Effect.map((result) =>
625 deriveRepositoryCloneUrlsFromCreateOutput(result.stdout, input.repository),
626 ),
627 ),
628 createPullRequest: (input) =>
629 execute({
630 cwd: input.cwd,
631 args: [
632 "pr",
633 "create",
634 "--base",
635 input.baseBranch,
636 "--head",
637 input.headSelector,
638 "--title",
639 input.title,
640 "--body-file",
641 input.bodyFile,
642 ],
643 }).pipe(Effect.asVoid),
644 getDefaultBranch: (input) =>
645 execute({
646 cwd: input.cwd,
647 ...(input.rateLimitHost === undefined ? {} : { rateLimitHost: input.rateLimitHost }),
648 args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
649 }).pipe(
650 Effect.map((value) => {
651 const trimmed = value.stdout.trim();
652 return trimmed.length > 0 ? trimmed : null;
653 }),
654 ),
655 checkoutPullRequest: (input) =>
656 execute({
657 cwd: input.cwd,
658 args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
659 }).pipe(Effect.asVoid),
660 });
661});
662​
663export const layer = Layer.effect(GitHubCli, make).pipe(
664 Layer.provideMerge(GitHubGraphQlBudget.layer),
665 Layer.provideMerge(SourceControlRateLimit.layer),
666);