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