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

GitHubCli.ts

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