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, httpStatus: Schema.optional(Schema.Int) },
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 readonly acceptNotModified?: boolean;
295 }) => Effect.Effect<VcsProcess.VcsProcessOutput, GitHubCliError>;
296
297 readonly listOpenPullRequests: (input: {
298 readonly cwd: string;
299 readonly headSelector: string;
300 readonly limit?: number;
301 readonly rateLimitHost?: string;
302 }) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
303
304 readonly getPullRequest: (input: {
305 readonly cwd: string;
306 readonly reference: string;
307 readonly rateLimitHost?: string;
308 }) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
309
310 readonly getRepositoryCloneUrls: (input: {
311 readonly cwd: string;
312 readonly repository: string;
313 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
314
315 readonly createRepository: (input: {
316 readonly cwd: string;
317 readonly repository: string;
318 readonly visibility: SourceControlRepositoryVisibility;
319 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
320
321 readonly createPullRequest: (input: {
322 readonly cwd: string;
323 readonly baseBranch: string;
324 readonly headSelector: string;
325 readonly title: string;
326 readonly bodyFile: string;
327 }) => Effect.Effect<void, GitHubCliError>;
328
329 readonly getDefaultBranch: (input: {
330 readonly cwd: string;
331 readonly rateLimitHost?: string;
332 }) => Effect.Effect<string | null, GitHubCliError>;
333
334 readonly checkoutPullRequest: (input: {
335 readonly cwd: string;
336 readonly reference: string;
337 readonly force?: boolean;
338 }) => Effect.Effect<void, GitHubCliError>;
339 }
340>()("t3/sourceControl/GitHubCli") {}
341
342const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
343 nameWithOwner: TrimmedNonEmptyString,
344 url: TrimmedNonEmptyString,
345 sshUrl: TrimmedNonEmptyString,
346});
347const decodeRawGitHubRepositoryCloneUrls = Schema.decodeEffect(
348 Schema.fromJsonString(RawGitHubRepositoryCloneUrlsSchema),
349);
350
351function normalizeRepositoryCloneUrls(
352 raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
353): GitHubRepositoryCloneUrls {
354 return {
355 nameWithOwner: raw.nameWithOwner,
356 url: raw.url,
357 sshUrl: raw.sshUrl,
358 };
359}
360
361/**
362 * `gh repo create` prints the canonical URL of the new repository on stdout
363 * (e.g. `https://github.com/owner/repo`). Reading it back here avoids a
364 * follow-up `gh repo view`, which can race GitHub's GraphQL eventual
365 * consistency window and falsely report the just-created repo as missing.
366 */
367function deriveRepositoryCloneUrlsFromCreateOutput(
368 stdout: string,
369 repository: string,
370): GitHubRepositoryCloneUrls {
371 const fallbackHost = "github.com";
372 const match = stdout.match(/https?:\/\/[^\s]+/);
373 if (match) {
374 const cleaned = match[0].replace(/\.git$/, "");
375 try {
376 const parsed = new URL(cleaned);
377 const pathname = parsed.pathname.replace(/^\/+|\/+$/g, "");
378 const segments = pathname.split("/").filter(Boolean);
379 if (segments.length === 2) {
380 const nameWithOwner = `${segments[0]}/${segments[1]}`;
381 return {
382 nameWithOwner,
383 url: `${parsed.origin}/${nameWithOwner}`,
384 sshUrl: `git@${parsed.host}:${nameWithOwner}.git`,
385 };
386 }
387 } catch {
388 // Fall through to the input-derived defaults below.
389 }
390 }
391 return {
392 nameWithOwner: repository,
393 url: `https://${fallbackHost}/${repository}`,
394 sshUrl: `git@${fallbackHost}:${repository}.git`,
395 };
396}
397
398/** @public Service construction is part of the canonical Effect module API. */
399export const make = Effect.gen(function* () {
400 const process = yield* VcsProcess.VcsProcess;
401 const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;
402 const limits = yield* SourceControlRateLimit.SourceControlRateLimit;
403
404 const executeRaw: GitHubCli["Service"]["execute"] = Effect.fn("GitHubCli.executeRaw")(
405 function* (input) {
406 const credential = yield* PinnedGitHubCredential;
407 if (credential !== null && !targetsVerifiedHost(input.args, credential.host)) {
408 return yield* new GitHubCliCommandError({
409 command: "gh",
410 cwd: input.cwd,
411 cause: new Error("The GitHub command does not target the verified credential's host."),
412 });
413 }
414 const token = credential === null ? undefined : Redacted.value(credential.token);
415 const env =
416 credential === null
417 ? input.env
418 : {
419 ...input.env,
420 GH_HOST: credential.host,
421 GH_TOKEN: token,
422 GITHUB_TOKEN: token,
423 GH_ENTERPRISE_TOKEN: token,
424 GITHUB_ENTERPRISE_TOKEN: token,
425 GH_DEBUG: "",
426 };
427 const result = yield* process
428 .run({
429 operation: "GitHubCli.execute",
430 command: "gh",
431 args: input.args,
432 cwd: input.cwd,
433 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
434 ...(input.acceptNotModified ? { allowNonZeroExit: true } : {}),
435 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
436 ...(env !== undefined ? { env } : {}),
437 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
438 })
439 .pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
440 if (result.exitCode !== 0 && input.acceptNotModified) {
441 const status = /^HTTP\/\S+ (\d+)/.exec(result.stdout)?.[1];
442 if (status !== "304" || !input.args.includes("--include")) {
443 const context = { command: "gh" as const, cwd: input.cwd, cause: undefined };
444 const headers = result.stdout.split(/\r?\n\r?\n/, 1)[0] ?? "";
445 const header = (name: string) =>
446 new RegExp(`^${name}:\\s*(.*)$`, "im").exec(headers)?.[1]?.trim();
447 if (
448 status === "429" ||
449 (status === "403" &&
450 (header("x-ratelimit-remaining") === "0" ||
451 header("retry-after") !== undefined ||
452 /rate limit/i.test(result.stderr)))
453 ) {
454 const now = DateTime.toEpochMillis(yield* DateTime.now);
455 const reset = Number(header("x-ratelimit-reset")) * 1_000;
456 const retryAt =
457 SourceControlRateLimit.retryAtFromHeader(header("retry-after"), now) ??
458 (Number.isFinite(reset) && reset > now ? reset : undefined);
459 return yield* new GitHubCliRateLimitError({
460 ...context,
461 ...(retryAt === undefined ? {} : { retryAt }),
462 });
463 }
464 if (status === "401") return yield* new GitHubCliAuthenticationError(context);
465 return yield* new GitHubCliCommandError({
466 ...context,
467 ...(status === undefined ? {} : { httpStatus: Number(status) }),
468 });
469 }
470 }
471 return result;
472 },
473 );
474
475 const quota = yield* Cache.makeWith(
476 (key: string) => {
477 const host = key.split("\0")[0]!;
478 return executeRaw({
479 cwd: globalThis.process.cwd(),
480 args: [
481 "api",
482 "rate_limit",
483 "--hostname",
484 host,
485 "--jq",
486 ".resources.graphql | {data:{rateLimit:{cost:1,limit:.limit,remaining:.remaining,resetAt:(.reset|todateiso8601)}}}",
487 ],
488 }).pipe(
489 Effect.tap((result) => budget.observe(host, result.stdout)),
490 Effect.asVoid,
491 );
492 },
493 {
494 capacity: 32,
495 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.seconds(30) : Duration.zero),
496 },
497 );
498 const execute: GitHubCli["Service"]["execute"] = Effect.fn("GitHubCli.execute")(
499 function* (input) {
500 const [command, action] = input.args;
501 if (
502 !(
503 (command === "pr" && (action === "list" || action === "view")) ||
504 (command === "repo" && action === "view")
505 )
506 )
507 return yield* executeRaw(input);
508 const credential = yield* PinnedGitHubCredential;
509 if (credential !== null && !targetsVerifiedHost(input.args, credential.host))
510 return yield* executeRaw(input);
511 const allowReserve = input.allowReserve ?? (yield* AllowGitHubReserve);
512 const host = (
513 credential?.host ??
514 commandHosts(input.args).find((host) => host !== null) ??
515 input.rateLimitHost ??
516 input.env?.GH_HOST ??
517 globalThis.process.env.GH_HOST ??
518 "github.com"
519 ).toLowerCase();
520 const key = { provider: "github" as const, host };
521 const guarded = Effect.gen(function* () {
522 const lease = yield* limits.check(key, allowReserve ? { allowPaused: true } : undefined);
523 return yield* Effect.gen(function* () {
524 yield* Cache.get(quota, `${host}\0${credential?.credentialFingerprint ?? ""}`);
525 yield* budget.query(host, "query {}", allowReserve ? { allowReserve: true } : undefined);
526 return yield* executeRaw(input);
527 }).pipe(
528 Effect.tap(() => limits.recordSuccess({ ...key, lease })),
529 Effect.tapError((error) =>
530 error._tag === "GitHubCliRateLimitError"
531 ? limits.recordRateLimit({ ...key, lease })
532 : Effect.void,
533 ),
534 );
535 });
536 return yield* guarded.pipe(
537 Effect.provideService(
538 SourceControlRateLimit.CredentialScope,
539 credential?.credentialFingerprint ?? (yield* SourceControlRateLimit.CredentialScope),
540 ),
541 Effect.catchTags({
542 SourceControlRateLimitPausedError: (cause) =>
543 Effect.fail(
544 new GitHubCliRateLimitError({
545 command: "gh",
546 cwd: input.cwd,
547 retryAt: cause.retryAt,
548 cause,
549 }),
550 ),
551 }),
552 );
553 },
554 );
555
556 return GitHubCli.of({
557 execute,
558 listOpenPullRequests: (input) =>
559 execute({
560 cwd: input.cwd,
561 ...(input.rateLimitHost === undefined ? {} : { rateLimitHost: input.rateLimitHost }),
562 allowReserve: true,
563 args: [
564 "pr",
565 "list",
566 "--head",
567 input.headSelector,
568 "--state",
569 "open",
570 "--limit",
571 String(input.limit ?? 1),
572 "--json",
573 "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,isCrossRepository,headRepository,headRepositoryOwner",
574 ],
575 }).pipe(
576 Effect.map((result) => result.stdout.trim()),
577 Effect.flatMap((raw) =>
578 raw.length === 0
579 ? Effect.succeed([])
580 : Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
581 Effect.flatMap((decoded) => {
582 if (!Result.isSuccess(decoded)) {
583 return Effect.fail(
584 new GitHubPullRequestListDecodeError({
585 command: "gh",
586 cwd: input.cwd,
587 cause: decoded.failure,
588 }),
589 );
590 }
591
592 return Effect.succeed(decoded.success.map(pullRequestSummary));
593 }),
594 ),
595 ),
596 ),
597 getPullRequest: (input) =>
598 execute({
599 cwd: input.cwd,
600 ...(input.rateLimitHost === undefined ? {} : { rateLimitHost: input.rateLimitHost }),
601 allowReserve: true,
602 args: [
603 "pr",
604 "view",
605 input.reference,
606 "--json",
607 "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
608 ],
609 }).pipe(
610 Effect.map((result) => result.stdout.trim()),
611 Effect.flatMap((raw) =>
612 Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
613 Effect.flatMap((decoded) => {
614 if (!Result.isSuccess(decoded)) {
615 return Effect.fail(
616 new GitHubPullRequestDecodeError({
617 command: "gh",
618 cwd: input.cwd,
619 cause: decoded.failure,
620 }),
621 );
622 }
623
624 return Effect.succeed(pullRequestSummary(decoded.success));
625 }),
626 ),
627 ),
628 ),
629 getRepositoryCloneUrls: (input) =>
630 execute({
631 cwd: input.cwd,
632 args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
633 }).pipe(
634 Effect.map((result) => result.stdout.trim()),
635 Effect.flatMap((raw) =>
636 decodeRawGitHubRepositoryCloneUrls(raw).pipe(
637 Effect.mapError(
638 (cause) =>
639 new GitHubRepositoryDecodeError({
640 command: "gh",
641 cwd: input.cwd,
642 cause,
643 }),
644 ),
645 ),
646 ),
647 Effect.map(normalizeRepositoryCloneUrls),
648 ),
649 createRepository: (input) =>
650 execute({
651 cwd: input.cwd,
652 args: ["repo", "create", input.repository, `--${input.visibility}`],
653 }).pipe(
654 Effect.map((result) =>
655 deriveRepositoryCloneUrlsFromCreateOutput(result.stdout, input.repository),
656 ),
657 ),
658 createPullRequest: (input) =>
659 execute({
660 cwd: input.cwd,
661 args: [
662 "pr",
663 "create",
664 "--base",
665 input.baseBranch,
666 "--head",
667 input.headSelector,
668 "--title",
669 input.title,
670 "--body-file",
671 input.bodyFile,
672 ],
673 }).pipe(Effect.asVoid),
674 getDefaultBranch: (input) =>
675 execute({
676 cwd: input.cwd,
677 ...(input.rateLimitHost === undefined ? {} : { rateLimitHost: input.rateLimitHost }),
678 args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
679 }).pipe(
680 Effect.map((value) => {
681 const trimmed = value.stdout.trim();
682 return trimmed.length > 0 ? trimmed : null;
683 }),
684 ),
685 checkoutPullRequest: (input) =>
686 execute({
687 cwd: input.cwd,
688 args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
689 }).pipe(Effect.asVoid),
690 });
691});
692
693export const layer = Layer.effect(GitHubCli, make).pipe(
694 Layer.provideMerge(GitHubGraphQlBudget.layer),
695 Layer.provideMerge(SourceControlRateLimit.layer),
696);