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