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

GitHubCli.ts

1,086 lines38.3 KB

1import * as Cache from "effect/Cache";
2import * as Clock from "effect/Clock";
3import * as Duration from "effect/Duration";
4import * as Exit from "effect/Exit";
5import * as Context from "effect/Context";
6import * as DateTime from "effect/DateTime";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as PlatformError from "effect/PlatformError";
11import * as Redacted from "effect/Redacted";
12import * as Request from "effect/Request";
13import * as RequestResolver from "effect/RequestResolver";
14import * as Result from "effect/Result";
15import * as Schema from "effect/Schema";
16​
17import {
18 TrimmedNonEmptyString,
19 type SourceControlRepositoryVisibility,
20 type VcsError,
21} from "@t3tools/contracts";
22import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
23import { decodeJsonResult } from "@t3tools/shared/schemaJson";
24​
25import * as VcsProcess from "../vcs/VcsProcess.ts";
26import * as GitHubGraphQlBudget from "./githubGraphQlBudget.ts";
27import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";
28import {
29 decodeGitHubPullRequestEntries,
30 decodeGitHubPullRequestJson,
31 decodeGitHubPullRequestListJson,
32 type NormalizedGitHubPullRequestRecord,
33} from "./gitHubPullRequests.ts";
34​
35const DEFAULT_TIMEOUT_MS = 30_000;
36​
37/** Server-local credential scope; never put its value in RPC payloads or cache keys. */
38export const PinnedGitHubCredential = Context.Reference<{
39 readonly host: string;
40 readonly token: Redacted.Redacted<string>;
41 readonly credentialFingerprint: string;
42} | null>("t3/sourceControl/PinnedGitHubCredential", { defaultValue: () => null });
43​
44export const AllowGitHubReserve = Context.Reference<boolean>(
45 "t3/sourceControl/AllowGitHubReserve",
46 { defaultValue: () => false },
47);
48​
49function commandHosts(args: ReadonlyArray<string>): Array<string | null> {
50 const hosts: Array<string | null> = [];
51 const repositoryHost = (repository: string | undefined) => {
52 if (repository === undefined) return null;
53 if (/^https?:\/\//i.test(repository)) {
54 try {
55 return new URL(repository).host.toLowerCase();
56 } catch {
57 return null;
58 }
59 }
60 const parts = repository.split("/");
61 return parts.length === 3 ? parts[0]!.toLowerCase() : null;
62 };
63 if (args[0] === "repo" && args[1] === "view") hosts.push(repositoryHost(args[2]));
64 for (let index = 0; index < args.length; index++) {
65 const arg = args[index]!;
66 if (arg === "--hostname") hosts.push(args[++index]?.toLowerCase() ?? null);
67 else if (arg.startsWith("--hostname=")) hosts.push(arg.slice(11).toLowerCase());
68 else if (arg === "--repo" || arg === "-R") hosts.push(repositoryHost(args[++index]));
69 else if (arg.startsWith("--repo=")) hosts.push(repositoryHost(arg.slice(7)));
70 else if (arg.startsWith("-R")) hosts.push(repositoryHost(arg.slice(2)));
71 else if (/^https?:\/\//i.test(arg)) hosts.push(repositoryHost(arg));
72 }
73 return hosts;
75​
76function targetsVerifiedHost(args: ReadonlyArray<string>, host: string): boolean {
77 const hosts = commandHosts(args);
78 return hosts.length > 0 && hosts.every((target) => target === host);
80​
81const gitHubCliFailureFields = {
82 command: Schema.Literal("gh"),
83 cwd: Schema.String,
84 cause: Schema.Defect(),
85} as const;
86​
87export class GitHubCliUnavailableError extends Schema.TaggedError<GitHubCliUnavailableError>()(
88 "GitHubCliUnavailableError",
89 gitHubCliFailureFields,
90) {
91 get detail(): string {
92 return "GitHub CLI (`gh`) is required but not available on PATH.";
93 }
94​
95 override get message(): string {
96 return `GitHub CLI failed in execute: ${this.detail}`;
97 }
99​
100export class GitHubCliAuthenticationError extends Schema.TaggedError<GitHubCliAuthenticationError>()(
101 "GitHubCliAuthenticationError",
102 gitHubCliFailureFields,
103) {
104 get detail(): string {
105 return "GitHub CLI is not authenticated. Run `gh auth login` and retry.";
106 }
107​
108 override get message(): string {
109 return `GitHub CLI failed in execute: ${this.detail}`;
110 }
112​
113export class GitHubCliRateLimitError extends Schema.TaggedError<GitHubCliRateLimitError>()(
114 "GitHubCliRateLimitError",
115 { ...gitHubCliFailureFields, retryAt: Schema.optionalKey(Schema.Finite) },
116) {
117 get detail(): string {
118 return "GitHub API rate limit exceeded. For the GraphQL quota and reset time, run `gh api graphql -f query='{rateLimit{remaining resetAt}}'`; `gh api rate_limit` reports REST.";
119 }
120​
121 override get message(): string {
122 return `GitHub CLI failed in execute: ${this.detail}`;
123 }
125​
126export class GitHubPullRequestNotFoundError extends Schema.TaggedError<GitHubPullRequestNotFoundError>()(
127 "GitHubPullRequestNotFoundError",
128 gitHubCliFailureFields,
129) {
130 get detail(): string {
131 return "Pull request not found. Check the PR number or URL and try again.";
132 }
133​
134 override get message(): string {
135 return `GitHub CLI failed in execute: ${this.detail}`;
136 }
138​
139export class GitHubCliCommandError extends Schema.TaggedError<GitHubCliCommandError>()(
140 "GitHubCliCommandError",
141 { ...gitHubCliFailureFields, httpStatus: Schema.optional(Schema.Int) },
142) {
143 get detail(): string {
144 return "GitHub CLI command failed.";
145 }
146​
147 override get message(): string {
148 return `GitHub CLI failed in execute: ${this.detail}`;
149 }
151​
152const gitHubCliDecodeFields = {
153 command: Schema.Literal("gh"),
154 cwd: Schema.String,
155 cause: Schema.Defect(),
156} as const;
157​
158export class GitHubPullRequestListDecodeError extends Schema.TaggedError<GitHubPullRequestListDecodeError>()(
159 "GitHubPullRequestListDecodeError",
160 gitHubCliDecodeFields,
161) {
162 get detail(): string {
163 return "GitHub CLI returned invalid PR list JSON.";
164 }
165​
166 override get message(): string {
167 return `GitHub CLI failed in listOpenPullRequests: ${this.detail}`;
168 }
170​
171export class GitHubChangeRequestListDecodeError extends Schema.TaggedError<GitHubChangeRequestListDecodeError>()(
172 "GitHubChangeRequestListDecodeError",
173 gitHubCliDecodeFields,
174) {
175 get detail(): string {
176 return "GitHub CLI returned invalid change request JSON.";
177 }
178​
179 override get message(): string {
180 return `GitHub CLI failed in listChangeRequests: ${this.detail}`;
181 }
183​
184export class GitHubPullRequestDecodeError extends Schema.TaggedError<GitHubPullRequestDecodeError>()(
185 "GitHubPullRequestDecodeError",
186 gitHubCliDecodeFields,
187) {
188 get detail(): string {
189 return "GitHub CLI returned invalid pull request JSON.";
190 }
191​
192 override get message(): string {
193 return `GitHub CLI failed in getPullRequest: ${this.detail}`;
194 }
196​
197export class GitHubRepositoryDecodeError extends Schema.TaggedError<GitHubRepositoryDecodeError>()(
198 "GitHubRepositoryDecodeError",
199 gitHubCliDecodeFields,
200) {
201 get detail(): string {
202 return "GitHub CLI returned invalid repository JSON.";
203 }
204​
205 override get message(): string {
206 return `GitHub CLI failed in getRepositoryCloneUrls: ${this.detail}`;
207 }
209​
210export const GitHubCliError = Schema.Union([
211 GitHubCliUnavailableError,
212 GitHubCliAuthenticationError,
213 GitHubCliRateLimitError,
214 GitHubPullRequestNotFoundError,
215 GitHubCliCommandError,
216 GitHubPullRequestListDecodeError,
217 GitHubChangeRequestListDecodeError,
218 GitHubPullRequestDecodeError,
219 GitHubRepositoryDecodeError,
220]);
221export type GitHubCliError = typeof GitHubCliError.Type;
222​
223export const isGitHubCliError = Schema.is(GitHubCliError);
224​
225export function fromVcsError(
226 context: {
227 readonly command: "gh";
228 readonly cwd: string;
229 },
230 error: VcsError,
231): GitHubCliError {
232 if (
233 error._tag === "VcsProcessSpawnError" &&
234 error.cause instanceof PlatformError.PlatformError &&
235 error.cause.reason._tag === "NotFound" &&
236 error.cause.reason.module === "ChildProcess" &&
237 error.cause.reason.method === "spawn"
238 ) {
239 return new GitHubCliUnavailableError({ ...context, cause: error });
240 }
241​
242 if (error._tag === "VcsProcessExitError") {
243 if (error.failureKind === "authentication") {
244 return new GitHubCliAuthenticationError({ ...context, cause: error });
245 }
246 if (error.failureKind === "rate-limited") {
247 return new GitHubCliRateLimitError({ ...context, cause: error });
248 }
249 if (error.failureKind === "not-found") {
250 return new GitHubPullRequestNotFoundError({ ...context, cause: error });
251 }
252 }
253​
254 return new GitHubCliCommandError({ ...context, cause: error });
256​
257export interface GitHubPullRequestSummary {
258 readonly number: number;
259 readonly title: string;
260 readonly url: string;
261 readonly baseRefName: string;
262 readonly headRefName: string;
263 readonly state?: "open" | "closed" | "merged";
264 readonly isDraft?: boolean;
265 readonly closedAt?: string | null;
266 readonly mergedAt?: string | null;
267 readonly updatedAt?: string;
268 readonly isCrossRepository?: boolean;
269 readonly headRepositoryNameWithOwner?: string | null;
270 readonly headRepositoryOwnerLogin?: string | null;
272​
273function pullRequestSummary(input: NormalizedGitHubPullRequestRecord): GitHubPullRequestSummary {
274 const { updatedAt, ...summary } = input;
275 return {
276 ...summary,
277 ...(Option.isSome(updatedAt) ? { updatedAt: DateTime.formatIso(updatedAt.value) } : {}),
278 };
280​
281export interface GitHubRepositoryCloneUrls {
282 readonly nameWithOwner: string;
283 readonly url: string;
284 readonly sshUrl: string;
286​
287export class GitHubCli extends Context.Service<
288 GitHubCli,
289 {
290 readonly execute: (input: {
291 readonly cwd: string;
292 readonly args: ReadonlyArray<string>;
293 readonly timeoutMs?: number;
294 /** Piped to the child's stdin, for payloads that must never appear in argv. */
295 readonly stdin?: string;
296 readonly env?: NodeJS.ProcessEnv;
297 readonly maxOutputBytes?: number;
298 readonly rateLimitHost?: string;
299 readonly allowReserve?: boolean;
300 readonly acceptNotModified?: boolean;
301 }) => Effect.Effect<VcsProcess.VcsProcessOutput, GitHubCliError>;
302​
303 readonly listOpenPullRequests: (input: {
304 readonly cwd: string;
305 readonly headSelector: string;
306 readonly limit?: number;
307 readonly rateLimitHost?: string;
308 }) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
309​
310 /**
311 * Pull requests whose head is `headSelector`, in the repository `gh pr list` would read in
312 * `cwd`. Lookups on one repository that arrive together share one GraphQL document; a
313 * checkout whose repository gh could pick another way is asked through `gh pr list`.
314 */
315 readonly listPullRequestsByHead: (input: {
316 readonly cwd: string;
317 readonly headSelector: string;
318 readonly state: "open" | "closed" | "merged" | "all";
319 readonly limit: number;
320 /** The checkout's GitHub host. Without it the lookup is not batched. */
321 readonly rateLimitHost?: string;
322 }) => Effect.Effect<ReadonlyArray<NormalizedGitHubPullRequestRecord>, GitHubCliError>;
323​
324 readonly getPullRequest: (input: {
325 readonly cwd: string;
326 readonly reference: string;
327 readonly rateLimitHost?: string;
328 }) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
329​
330 readonly getRepositoryCloneUrls: (input: {
331 readonly cwd: string;
332 readonly repository: string;
333 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
334​
335 readonly createRepository: (input: {
336 readonly cwd: string;
337 readonly repository: string;
338 readonly visibility: SourceControlRepositoryVisibility;
339 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
340​
341 readonly createPullRequest: (input: {
342 readonly cwd: string;
343 readonly baseBranch: string;
344 readonly headSelector: string;
345 readonly title: string;
346 readonly bodyFile: string;
347 }) => Effect.Effect<void, GitHubCliError>;
348​
349 readonly getDefaultBranch: (input: {
350 readonly cwd: string;
351 readonly rateLimitHost?: string;
352 }) => Effect.Effect<string | null, GitHubCliError>;
353​
354 readonly checkoutPullRequest: (input: {
355 readonly cwd: string;
356 readonly reference: string;
357 readonly force?: boolean;
358 }) => Effect.Effect<void, GitHubCliError>;
359 }
360>()("t3/sourceControl/GitHubCli") {}
361​
362const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
363 nameWithOwner: TrimmedNonEmptyString,
364 url: TrimmedNonEmptyString,
365 sshUrl: TrimmedNonEmptyString,
366});
367const decodeRawGitHubRepositoryCloneUrls = Schema.decodeEffect(
368 Schema.fromJsonString(RawGitHubRepositoryCloneUrlsSchema),
369);
370​
371function normalizeRepositoryCloneUrls(
372 raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
373): GitHubRepositoryCloneUrls {
374 return {
375 nameWithOwner: raw.nameWithOwner,
376 url: raw.url,
377 sshUrl: raw.sshUrl,
378 };
380​
381/**
382 * `gh repo create` prints the canonical URL of the new repository on stdout
383 * (e.g. `https://github.com/owner/repo`). Reading it back here avoids a
384 * follow-up `gh repo view`, which can race GitHub's GraphQL eventual
385 * consistency window and falsely report the just-created repo as missing.
386 */
387function deriveRepositoryCloneUrlsFromCreateOutput(
388 stdout: string,
389 repository: string,
390): GitHubRepositoryCloneUrls {
391 const fallbackHost = "github.com";
392 const match = stdout.match(/https?:\/\/[^\s]+/);
393 if (match) {
394 const cleaned = match[0].replace(/\.git$/, "");
395 try {
396 const parsed = new URL(cleaned);
397 const pathname = parsed.pathname.replace(/^\/+|\/+$/g, "");
398 const segments = pathname.split("/").filter(Boolean);
399 if (segments.length === 2) {
400 const nameWithOwner = `${segments[0]}/${segments[1]}`;
401 return {
402 nameWithOwner,
403 url: `${parsed.origin}/${nameWithOwner}`,
404 sshUrl: `git@${parsed.host}:${nameWithOwner}.git`,
405 };
406 }
407 } catch {
408 // Fall through to the input-derived defaults below.
409 }
410 }
411 return {
412 nameWithOwner: repository,
413 url: `https://${fallbackHost}/${repository}`,
414 sshUrl: `git@${fallbackHost}:${repository}.git`,
415 };
417​
418type PullRequestListState = "open" | "closed" | "merged" | "all";
419​
420const PULL_REQUEST_LIST_JSON_FIELDS =
421 "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner";
422/** The `gh pr list --json` fields above, as GraphQL selects them. */
423const PULL_REQUEST_NODE_SELECTION =
424 "number title url baseRefName headRefName state isDraft mergedAt closedAt updatedAt isCrossRepository headRepository { name nameWithOwner } headRepositoryOwner { login }";
425const GRAPHQL_STATES: Record<PullRequestListState, ReadonlyArray<string>> = {
426 open: ["OPEN"],
427 closed: ["CLOSED"],
428 merged: ["MERGED"],
429 all: ["OPEN", "CLOSED", "MERGED"],
430};
431/**
432 * Head lookups per GraphQL document. A document of a hundred costs one point, the same as one
433 * `gh pr list`, but half that keeps each answer near half a second.
434 */
435const HEAD_LOOKUPS_PER_DOCUMENT = 50;
436/**
437 * How long a head lookup waits for company. Branch discovery reaches GitHub only after each
438 * branch's own git reads, so lookups started together arrive tens of milliseconds apart.
439 */
440const HEAD_LOOKUP_BATCH_WINDOW = "50 millis";
441/** A full document is 5,000 rows of well under 2 KB each. */
442const HEAD_LOOKUP_MAX_OUTPUT_BYTES = 16_000_000;
443const RATE_LIMIT_READING = "query { rateLimit { cost limit remaining resetAt } }";
444​
445class PullRequestsByHeadRead extends Request.Class<
446 {
447 readonly cwd: string;
448 readonly host: string;
449 readonly owner: string;
450 readonly name: string;
451 readonly headRefName: string;
452 readonly state: PullRequestListState;
453 readonly limit: number;
454 },
455 ReadonlyArray<NormalizedGitHubPullRequestRecord>,
456 GitHubCliError
457> {}
458​
459const GraphQlVariables = Schema.Record(
460 Schema.String,
461 Schema.Union([Schema.String, Schema.Array(Schema.String)]),
462);
463/** A GraphQL request body for `gh api graphql --input -`. */
464const encodeGraphQlRequest = Schema.encodeSync(
465 Schema.fromJsonString(Schema.Struct({ query: Schema.String, variables: GraphQlVariables })),
466);
467​
468/** One aliased `pullRequests` connection per lookup, each head and state passed as a variable. */
469function buildPullRequestsByHeadQuery(
470 lookups: ReadonlyArray<Pick<PullRequestsByHeadRead, "headRefName" | "state" | "limit">>,
471): { readonly document: string; readonly variables: typeof GraphQlVariables.Type } {
472 const variables: Record<string, string | ReadonlyArray<string>> = {};
473 const declarations: string[] = ["$owner: String!", "$name: String!"];
474 const selections: string[] = [];
475 for (const [index, lookup] of lookups.entries()) {
476 variables[`h${index}`] = lookup.headRefName;
477 variables[`s${index}`] = GRAPHQL_STATES[lookup.state];
478 declarations.push(`$h${index}: String!`, `$s${index}: [PullRequestState!]`);
479 // `gh pr list` orders the same way, so a head with more matches than the limit keeps the
480 // same rows.
481 selections.push(
482 ` h${index}: pullRequests(headRefName: $h${index}, states: $s${index}, first: ${lookup.limit}, orderBy: { field: CREATED_AT, direction: DESC }) { nodes { ${PULL_REQUEST_NODE_SELECTION} } }`,
483 );
484 }
485 return {
486 document: `query PullRequestsByHead(${declarations.join(", ")}) {\n repository(owner: $owner, name: $name) {\n${selections.join("\n")}\n }\n}`,
487 variables,
488 };
490​
491/** The reset time of a `rateLimit` reading, which sets when the next one is due. */
492const decodeRateLimitReading = (raw: string) =>
493 Result.map(
494 decodeJsonResult(
495 Schema.Struct({
496 data: Schema.Struct({ rateLimit: Schema.Struct({ resetAt: Schema.String }) }),
497 }),
498 )(raw),
499 (reading) => reading.data.rateLimit.resetAt,
500 );
501​
502const decodePullRequestsByHead = decodeJsonResult(
503 Schema.Struct({
504 data: Schema.Struct({
505 repository: Schema.Record(
506 Schema.String,
507 Schema.NullOr(Schema.Struct({ nodes: Schema.Array(Schema.Unknown) })),
508 ),
509 }),
510 }),
511);
512​
513/**
514 * The repository `gh pr list` reads in a checkout, picked the way gh picks one without a
515 * prompt: the remote `gh repo set-default` marked, else the first of upstream, github, origin
516 * (in any case), else the only remote. `remotes` is `git remote -v` output and `resolved` is the output of
517 * `git config --get-regexp '^remote\..*\.gh-resolved$'`.
518 *
519 * Null whenever gh might weigh the remotes differently: a remote on another host or under an
520 * SSH alias, more than one mark, or several remotes with none of those names. Callers then
521 * ask gh itself.
522 */
523export function selectGitHubBaseRepository(input: {
524 readonly remotes: string;
525 readonly resolved: string;
526 readonly host: string;
527}): { readonly owner: string; readonly name: string } | null {
528 const host = input.host.toLowerCase();
529 const repositories = new Map<string, { readonly owner: string; readonly name: string }>();
530 for (const line of input.remotes.split("\n")) {
531 const match = /^(\S+)\s+(\S+)\s+\(fetch\)$/u.exec(line.trim());
532 if (!match) continue;
533 const [remoteHost, owner, name, ...rest] = normalizeGitRemoteUrl(match[2]!).split("/");
534 if (remoteHost !== host || !owner || !name || rest.length > 0) return null;
535 repositories.set(match[1]!, { owner, name });
536 }
537 const marks = input.resolved
538 .split("\n")
539 .map((line) => /^remote\.(.+)\.gh-resolved\s+(\S+)$/u.exec(line.trim()))
540 .filter((match): match is RegExpExecArray => match !== null && repositories.has(match[1]!));
541 if (marks.length > 1) return null;
542 const [mark] = marks;
543 if (mark) {
544 if (mark[2] === "base") return repositories.get(mark[1]!) ?? null;
545 const [owner, name, ...rest] = mark[2]!.toLowerCase().split("/");
546 return owner && name && rest.length === 0 ? { owner, name } : null;
547 }
548 // gh sorts remotes by these names, case-insensitively, and takes the first. A tie for the
549 // top place has no defined winner.
550 const score = (remoteName: string) =>
551 ["origin", "github", "upstream"].indexOf(remoteName.toLowerCase()) + 1;
552 const ranked = [...repositories.entries()].toSorted(
553 ([left], [right]) => score(right) - score(left),
554 );
555 const [top, next] = ranked;
556 return top !== undefined && (next === undefined || score(top[0]) > score(next[0]))
557 ? top[1]
558 : null;
560​
561/** @public Service construction is part of the canonical Effect module API. */
562export const make = Effect.gen(function* () {
563 const process = yield* VcsProcess.VcsProcess;
564 const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;
565 const limits = yield* SourceControlRateLimit.SourceControlRateLimit;
566​
567 const executeRaw: GitHubCli["Service"]["execute"] = Effect.fn("GitHubCli.executeRaw")(
568 function* (input) {
569 const credential = yield* PinnedGitHubCredential;
570 if (credential !== null && !targetsVerifiedHost(input.args, credential.host)) {
571 return yield* new GitHubCliCommandError({
572 command: "gh",
573 cwd: input.cwd,
574 cause: new Error("The GitHub command does not target the verified credential's host."),
575 });
576 }
577 const token = credential === null ? undefined : Redacted.value(credential.token);
578 const env =
579 credential === null
580 ? input.env
581 : {
582 ...input.env,
583 GH_HOST: credential.host,
584 GH_TOKEN: token,
585 GITHUB_TOKEN: token,
586 GH_ENTERPRISE_TOKEN: token,
587 GITHUB_ENTERPRISE_TOKEN: token,
588 GH_DEBUG: "",
589 };
590 const result = yield* process
591 .run({
592 operation: "GitHubCli.execute",
593 command: "gh",
594 args: input.args,
595 cwd: input.cwd,
596 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
597 ...(input.acceptNotModified ? { allowNonZeroExit: true } : {}),
598 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
599 ...(env !== undefined ? { env } : {}),
600 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
601 })
602 .pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
603 if (result.exitCode !== 0 && input.acceptNotModified) {
604 const status = /^HTTP\/\S+ (\d+)/.exec(result.stdout)?.[1];
605 if (status !== "304" || !input.args.includes("--include")) {
606 const context = { command: "gh" as const, cwd: input.cwd, cause: undefined };
607 const headers = result.stdout.split(/\r?\n\r?\n/, 1)[0] ?? "";
608 const header = (name: string) =>
609 new RegExp(`^${name}:\\s*(.*)$`, "im").exec(headers)?.[1]?.trim();
610 if (
611 status === "429" ||
612 (status === "403" &&
613 (header("x-ratelimit-remaining") === "0" ||
614 header("retry-after") !== undefined ||
615 /rate limit/i.test(result.stderr)))
616 ) {
617 const now = DateTime.toEpochMillis(yield* DateTime.now);
618 const reset = Number(header("x-ratelimit-reset")) * 1_000;
619 const retryAt =
620 SourceControlRateLimit.retryAtFromHeader(header("retry-after"), now) ??
621 (Number.isFinite(reset) && reset > now ? reset : undefined);
622 return yield* new GitHubCliRateLimitError({
623 ...context,
624 ...(retryAt === undefined ? {} : { retryAt }),
625 });
626 }
627 if (status === "401") return yield* new GitHubCliAuthenticationError(context);
628 return yield* new GitHubCliCommandError({
629 ...context,
630 ...(status === undefined ? {} : { httpStatus: Number(status) }),
631 });
632 }
633 }
634 return result;
635 },
636 );
637​
638 /**
639 * A GraphQL `rateLimit` reading per host and credential, so the budget knows the balance
640 * before reads that cannot report their own cost (`gh pr list`). GraphQL documents keep it
641 * current in between. Each reading costs one point and is redone at the reset, or after ten
642 * minutes so a `gh auth switch` is not priced against the old account for a whole hour.
643 */
644 const budgetReading = yield* Cache.makeWith(
645 (key: string) => {
646 const host = key.split("\0")[0]!;
647 return executeRaw({
648 cwd: globalThis.process.cwd(),
649 args: ["api", "graphql", "--hostname", host, "-f", `query=${RATE_LIMIT_READING}`],
650 }).pipe(
651 Effect.tap((result) => budget.observe(host, result.stdout)),
652 Effect.flatMap((result) =>
653 Clock.currentTimeMillis.pipe(
654 Effect.map((now) => {
655 const resetAtMs = Date.parse(
656 decodeRateLimitReading(result.stdout).pipe(
657 Result.match({ onFailure: () => "", onSuccess: (reading) => reading }),
658 ),
659 );
660 // A reset that is missing or already past (a skewed clock) waits a minute, so a
661 // bad reading cannot ask again on every read.
662 return Duration.millis(
663 Number.isFinite(resetAtMs) && resetAtMs > now
664 ? Math.min(resetAtMs - now, 600_000)
665 : 60_000,
666 );
667 }),
668 ),
669 ),
670 );
671 },
672 {
673 capacity: 32,
674 timeToLive: (exit) => (Exit.isSuccess(exit) ? exit.value : Duration.minutes(1)),
675 },
676 );
677​
678 /**
679 * Runs a GraphQL-priced read under its host's pause and the GraphQL budget. `run` receives
680 * the document with `rateLimit` added, so a GraphQL read can report what it spent; a CLI read
681 * ignores it and is priced at one point.
682 */
683 const guardedRead = <A>(input: {
684 readonly cwd: string;
685 readonly host: string;
686 readonly document: string;
687 readonly allowReserve: boolean;
688 readonly run: (document: string) => Effect.Effect<A, GitHubCliError>;
689 }) =>
690 Effect.gen(function* () {
691 const credential = yield* PinnedGitHubCredential;
692 const key = { provider: "github" as const, host: input.host };
693 const guarded = Effect.gen(function* () {
694 const lease = yield* limits.check(
695 key,
696 input.allowReserve ? { allowPaused: true } : undefined,
697 );
698 // A failed reading leaves the budget unknown; it never blocks the read itself.
699 yield* Cache.get(
700 budgetReading,
701 `${input.host}\0${yield* SourceControlRateLimit.CredentialScope}`,
702 ).pipe(Effect.ignore);
703 return yield* budget
704 .query(
705 input.host,
706 input.document,
707 input.allowReserve ? { allowReserve: true } : undefined,
708 )
709 .pipe(
710 Effect.flatMap(input.run),
711 Effect.tap(() => limits.recordSuccess({ ...key, lease })),
712 Effect.tapError((error) =>
713 error._tag === "GitHubCliRateLimitError"
714 ? limits.recordRateLimit({ ...key, lease })
715 : Effect.void,
716 ),
717 );
718 });
719 return yield* guarded.pipe(
720 Effect.provideService(
721 SourceControlRateLimit.CredentialScope,
722 credential?.credentialFingerprint ?? (yield* SourceControlRateLimit.CredentialScope),
723 ),
724 Effect.catchTags({
725 SourceControlRateLimitPausedError: (cause) =>
726 Effect.fail(
727 new GitHubCliRateLimitError({
728 command: "gh",
729 cwd: input.cwd,
730 retryAt: cause.retryAt,
731 cause,
732 }),
733 ),
734 }),
735 );
736 });
737​
738 const execute: GitHubCli["Service"]["execute"] = Effect.fn("GitHubCli.execute")(
739 function* (input) {
740 const [command, action] = input.args;
741 if (
742 !(
743 (command === "pr" && (action === "list" || action === "view")) ||
744 (command === "repo" && action === "view")
745 )
746 )
747 return yield* executeRaw(input);
748 const credential = yield* PinnedGitHubCredential;
749 if (credential !== null && !targetsVerifiedHost(input.args, credential.host))
750 return yield* executeRaw(input);
751 return yield* guardedRead({
752 cwd: input.cwd,
753 host: (
754 credential?.host ??
755 commandHosts(input.args).find((host) => host !== null) ??
756 input.rateLimitHost ??
757 input.env?.GH_HOST ??
758 globalThis.process.env.GH_HOST ??
759 "github.com"
760 ).toLowerCase(),
761 document: "query {}",
762 allowReserve: input.allowReserve ?? (yield* AllowGitHubReserve),
763 run: () => executeRaw(input),
764 });
765 },
766 );
767​
768 const listPullRequestsWithCli = (input: {
769 readonly cwd: string;
770 readonly headSelector: string;
771 readonly state: PullRequestListState;
772 readonly limit: number;
773 readonly rateLimitHost?: string | undefined;
774 }) =>
775 execute({
776 cwd: input.cwd,
777 ...(input.rateLimitHost === undefined ? {} : { rateLimitHost: input.rateLimitHost }),
778 args: [
779 "pr",
780 "list",
781 "--head",
782 input.headSelector,
783 "--state",
784 input.state,
785 "--limit",
786 String(input.limit),
787 "--json",
788 PULL_REQUEST_LIST_JSON_FIELDS,
789 ],
790 }).pipe(
791 Effect.flatMap((result) => {
792 const raw = result.stdout.trim();
793 if (raw.length === 0) return Effect.succeed([]);
794 const decoded = decodeGitHubPullRequestListJson(raw);
795 return Result.isSuccess(decoded)
796 ? Effect.succeed(decoded.success)
797 : Effect.fail(
798 new GitHubChangeRequestListDecodeError({
799 command: "gh",
800 cwd: input.cwd,
801 cause: decoded.failure,
802 }),
803 );
804 }),
805 );
806​
807 const git = (cwd: string, args: ReadonlyArray<string>) =>
808 process.run({
809 operation: "GitHubCli.baseRepository",
810 command: "git",
811 args,
812 cwd,
813 allowNonZeroExit: true,
814 timeoutMs: 5_000,
815 });
816​
817 /** The repository gh reads in `cwd`, or null when gh could pick it another way. */
818 const resolveBaseRepository = (cwd: string, host: string) =>
819 globalThis.process.env.GH_REPO
820 ? Effect.succeed(null)
821 : Effect.all([
822 git(cwd, ["remote", "-v"]),
823 git(cwd, ["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"]),
824 ]).pipe(
825 Effect.map(([remotes, resolved]) =>
826 remotes.exitCode === 0
827 ? selectGitHubBaseRepository({
828 remotes: remotes.stdout,
829 resolved: resolved.exitCode === 0 ? resolved.stdout : "",
830 host,
831 })
832 : null,
833 ),
834 Effect.orElseSucceed(() => null),
835 );
836​
837 const headResolver = RequestResolver.makeGrouped<PullRequestsByHeadRead, string>({
838 key: ({ request, context }) =>
839 JSON.stringify([
840 request.host,
841 request.owner,
842 request.name,
843 Context.getOrElse(context, PinnedGitHubCredential, () => null)?.credentialFingerprint ??
844 null,
845 Context.getOrElse(context, SourceControlRateLimit.CredentialScope, () => ""),
846 ]),
847 resolver: (entries) => {
848 const [first] = entries;
849 const { cwd, host, owner, name } = first.request;
850 const query = buildPullRequestsByHeadQuery(entries.map((entry) => entry.request));
851 const readCli = (entry: (typeof entries)[number]) =>
852 listPullRequestsWithCli({
853 cwd: entry.request.cwd,
854 headSelector: entry.request.headRefName,
855 state: entry.request.state,
856 limit: entry.request.limit,
857 rateLimitHost: entry.request.host,
858 }).pipe(
859 Effect.exit,
860 Effect.map((exit) => entry.completeUnsafe(exit)),
861 );
862 return guardedRead({
863 cwd,
864 host,
865 document: query.document,
866 allowReserve: false,
867 run: (document) =>
868 executeRaw({
869 cwd,
870 args: ["api", "graphql", "--hostname", host, "--input", "-"],
871 // Up to 50 heads of 100 rows each. A default branch such as `main` can match a
872 // hundred fork pull requests, so the 1 MB default would cut the answer short.
873 maxOutputBytes: HEAD_LOOKUP_MAX_OUTPUT_BYTES,
874 stdin: encodeGraphQlRequest({
875 query: document,
876 variables: { owner, name, ...query.variables },
877 }),
878 }).pipe(Effect.tap((result) => budget.observe(host, result.stdout))),
879 }).pipe(
880 Effect.flatMap((result) => {
881 const decoded = decodePullRequestsByHead(result.stdout);
882 if (!Result.isSuccess(decoded)) {
883 return Effect.forEach(entries, readCli, { discard: true });
884 }
885 const aliases = decoded.success.data.repository;
886 return Effect.forEach(
887 entries,
888 (entry, index) => {
889 const alias = aliases[`h${index}`];
890 if (alias == null) return readCli(entry);
891 entry.completeUnsafe(Exit.succeed(decodeGitHubPullRequestEntries(alias.nodes)));
892 return Effect.void;
893 },
894 { discard: true },
895 );
896 }),
897 // A document GitHub refused as a whole (a renamed repository, a field an older
898 // Enterprise host lacks) leaves each lookup to gh. A rate limit fails them all:
899 // asking one at a time would only spend what the pause is saving.
900 Effect.catchIf(
901 (error) => error._tag !== "GitHubCliRateLimitError",
902 () => Effect.forEach(entries, readCli, { discard: true }),
903 ),
904 Effect.catchCause((cause) =>
905 Effect.sync(() => {
906 for (const entry of entries) entry.completeUnsafe(Exit.failCause(cause));
907 }),
908 ),
909 );
910 },
911 }).pipe(
912 RequestResolver.setDelay(HEAD_LOOKUP_BATCH_WINDOW),
913 RequestResolver.batchN(HEAD_LOOKUPS_PER_DOCUMENT),
914 );
915​
916 const listPullRequestsByHead: GitHubCli["Service"]["listPullRequestsByHead"] = Effect.fn(
917 "GitHubCli.listPullRequestsByHead",
918 )(function* (input) {
919 const host = input.rateLimitHost?.toLowerCase();
920 const credential = yield* PinnedGitHubCredential;
921 // `owner:branch` selectors and other hosts keep gh's own handling.
922 const repository =
923 host === undefined ||
924 input.headSelector.includes(":") ||
925 (credential !== null && credential.host !== host)
926 ? null
927 : yield* resolveBaseRepository(input.cwd, host);
928 if (host === undefined || repository === null) {
929 return yield* listPullRequestsWithCli(input);
930 }
931 return yield* Effect.request(
932 new PullRequestsByHeadRead({
933 cwd: input.cwd,
934 host,
935 owner: repository.owner,
936 name: repository.name,
937 headRefName: input.headSelector,
938 state: input.state,
939 limit: Math.min(Math.max(Math.trunc(input.limit), 1), 100),
940 }),
941 headResolver,
942 );
943 });
944​
945 return GitHubCli.of({
946 execute,
947 listPullRequestsByHead,
948 listOpenPullRequests: (input) =>
949 execute({
950 cwd: input.cwd,
951 ...(input.rateLimitHost === undefined ? {} : { rateLimitHost: input.rateLimitHost }),
952 allowReserve: true,
953 args: [
954 "pr",
955 "list",
956 "--head",
957 input.headSelector,
958 "--state",
959 "open",
960 "--limit",
961 String(input.limit ?? 1),
962 "--json",
963 "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,isCrossRepository,headRepository,headRepositoryOwner",
964 ],
965 }).pipe(
966 Effect.map((result) => result.stdout.trim()),
967 Effect.flatMap((raw) =>
968 raw.length === 0
969 ? Effect.succeed([])
970 : Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
971 Effect.flatMap((decoded) => {
972 if (!Result.isSuccess(decoded)) {
973 return Effect.fail(
974 new GitHubPullRequestListDecodeError({
975 command: "gh",
976 cwd: input.cwd,
977 cause: decoded.failure,
978 }),
979 );
980 }
981​
982 return Effect.succeed(decoded.success.map(pullRequestSummary));
983 }),
984 ),
985 ),
986 ),
987 getPullRequest: (input) =>
988 execute({
989 cwd: input.cwd,
990 ...(input.rateLimitHost === undefined ? {} : { rateLimitHost: input.rateLimitHost }),
991 allowReserve: true,
992 args: [
993 "pr",
994 "view",
995 input.reference,
996 "--json",
997 "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
998 ],
999 }).pipe(
1000 Effect.map((result) => result.stdout.trim()),
1001 Effect.flatMap((raw) =>
1002 Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
1003 Effect.flatMap((decoded) => {
1004 if (!Result.isSuccess(decoded)) {
1005 return Effect.fail(
1006 new GitHubPullRequestDecodeError({
1007 command: "gh",
1008 cwd: input.cwd,
1009 cause: decoded.failure,
1010 }),
1011 );
1013​
1014 return Effect.succeed(pullRequestSummary(decoded.success));
1015 }),
1016 ),
1017 ),
1018 ),
1019 getRepositoryCloneUrls: (input) =>
1020 execute({
1021 cwd: input.cwd,
1022 args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
1023 }).pipe(
1024 Effect.map((result) => result.stdout.trim()),
1025 Effect.flatMap((raw) =>
1026 decodeRawGitHubRepositoryCloneUrls(raw).pipe(
1027 Effect.mapError(
1028 (cause) =>
1029 new GitHubRepositoryDecodeError({
1030 command: "gh",
1031 cwd: input.cwd,
1032 cause,
1033 }),
1034 ),
1035 ),
1036 ),
1037 Effect.map(normalizeRepositoryCloneUrls),
1038 ),
1039 createRepository: (input) =>
1040 execute({
1041 cwd: input.cwd,
1042 args: ["repo", "create", input.repository, `--${input.visibility}`],
1043 }).pipe(
1044 Effect.map((result) =>
1045 deriveRepositoryCloneUrlsFromCreateOutput(result.stdout, input.repository),
1046 ),
1047 ),
1048 createPullRequest: (input) =>
1049 execute({
1050 cwd: input.cwd,
1051 args: [
1052 "pr",
1053 "create",
1054 "--base",
1055 input.baseBranch,
1056 "--head",
1057 input.headSelector,
1058 "--title",
1059 input.title,
1060 "--body-file",
1061 input.bodyFile,
1062 ],
1063 }).pipe(Effect.asVoid),
1064 getDefaultBranch: (input) =>
1065 execute({
1066 cwd: input.cwd,
1067 ...(input.rateLimitHost === undefined ? {} : { rateLimitHost: input.rateLimitHost }),
1068 args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
1069 }).pipe(
1070 Effect.map((value) => {
1071 const trimmed = value.stdout.trim();
1072 return trimmed.length > 0 ? trimmed : null;
1073 }),
1074 ),
1075 checkoutPullRequest: (input) =>
1076 execute({
1077 cwd: input.cwd,
1078 args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
1079 }).pipe(Effect.asVoid),
1080 });
1081});
1082​
1083export const layer = Layer.effect(GitHubCli, make).pipe(
1084 Layer.provideMerge(GitHubGraphQlBudget.layer),
1085 Layer.provideMerge(SourceControlRateLimit.layer),