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

GitHubCli.ts

1,090 lines41.6 KB

1import * as Context from "effect/Context";
2import * as DateTime from "effect/DateTime";
3import * as Effect from "effect/Effect";
4import * as Exit from "effect/Exit";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Request from "effect/Request";
9import * as RequestResolver from "effect/RequestResolver";
10import * as Result from "effect/Result";
11import * as Schema from "effect/Schema";
12​
13import { TrimmedNonEmptyString, type SourceControlRepositoryVisibility } from "@t3tools/contracts";
14import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
15import { decodeJsonResult } from "@t3tools/shared/schemaJson";
16import {
17 detectSourceControlProviderFromRemoteUrl,
18 isSshRemoteUrl,
19} from "@t3tools/shared/sourceControl";
20​
21import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
22import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
23​
24import * as VcsProcess from "../vcs/VcsProcess.ts";
25import * as GitHubApi from "./GitHubApi.ts";
26import * as GitHubCredentials from "./GitHubCredentials.ts";
27import * as GitHubGraphQlBudget from "./githubGraphQlBudget.ts";
28import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";
29import {
30 decodeGitHubPullRequestEntries,
31 type NormalizedGitHubPullRequestRecord,
32} from "./gitHubPullRequests.ts";
33​
34export const AllowGitHubReserve = GitHubApi.AllowGitHubReserve;
35​
36const gitHubCliFailureFields = {
37 command: Schema.Literal("gh"),
38 cwd: Schema.String,
39 cause: Schema.Defect(),
40} as const;
41​
42export class GitHubCliUnavailableError extends Schema.TaggedError<GitHubCliUnavailableError>()(
43 "GitHubCliUnavailableError",
44 gitHubCliFailureFields,
45) {
46 override get message(): string {
47 return "No GitHub credential on the server. Set GH_TOKEN, or install the GitHub CLI and run `gh auth login`.";
48 }
50​
51export class GitHubCliAuthenticationError extends Schema.TaggedError<GitHubCliAuthenticationError>()(
52 "GitHubCliAuthenticationError",
53 gitHubCliFailureFields,
54) {
55 override get message(): string {
56 // A missing or turned-off credential already says what to do about it.
57 return GitHubCredentials.isGitHubCredentialUnavailableError(this.cause)
58 ? this.cause.message
59 : "GitHub is not authenticated. Run `gh auth login` (or set GH_TOKEN) and retry.";
60 }
62​
63export class GitHubCliRateLimitError extends Schema.TaggedError<GitHubCliRateLimitError>()(
64 "GitHubCliRateLimitError",
65 { ...gitHubCliFailureFields, retryAt: Schema.optionalKey(Schema.Finite) },
66) {
67 override get message(): string {
68 return "GitHub API rate limit exceeded. Requests resume when the limit resets.";
69 }
71​
72export class GitHubPullRequestNotFoundError extends Schema.TaggedError<GitHubPullRequestNotFoundError>()(
73 "GitHubPullRequestNotFoundError",
74 gitHubCliFailureFields,
75) {
76 override get message(): string {
77 return "Pull request not found. Check the PR number or URL and try again.";
78 }
80​
81export class GitHubCliCommandError extends Schema.TaggedError<GitHubCliCommandError>()(
82 "GitHubCliCommandError",
83 { ...gitHubCliFailureFields, httpStatus: Schema.optional(Schema.Int) },
84) {
85 override get message(): string {
86 // GitHub's own reason ("A pull request already exists…") or the failed step's, when known.
87 const reason =
88 this.cause instanceof Error && this.cause.message.trim() !== ""
89 ? this.cause.message.trim()
90 : null;
91 return reason === null ? "GitHub request failed." : reason;
92 }
94​
95const gitHubCliDecodeFields = {
96 command: Schema.Literal("gh"),
97 cwd: Schema.String,
98 cause: Schema.Defect(),
99} as const;
100​
101export class GitHubPullRequestListDecodeError extends Schema.TaggedError<GitHubPullRequestListDecodeError>()(
102 "GitHubPullRequestListDecodeError",
103 gitHubCliDecodeFields,
104) {
105 override get message(): string {
106 return "GitHub returned an invalid pull request list.";
107 }
109​
110export class GitHubChangeRequestListDecodeError extends Schema.TaggedError<GitHubChangeRequestListDecodeError>()(
111 "GitHubChangeRequestListDecodeError",
112 gitHubCliDecodeFields,
113) {
114 override get message(): string {
115 return "GitHub returned an invalid change request list.";
116 }
118​
119export class GitHubPullRequestDecodeError extends Schema.TaggedError<GitHubPullRequestDecodeError>()(
120 "GitHubPullRequestDecodeError",
121 gitHubCliDecodeFields,
122) {
123 override get message(): string {
124 return "GitHub returned an invalid pull request.";
125 }
127​
128export class GitHubRepositoryDecodeError extends Schema.TaggedError<GitHubRepositoryDecodeError>()(
129 "GitHubRepositoryDecodeError",
130 gitHubCliDecodeFields,
131) {
132 override get message(): string {
133 return "GitHub returned an invalid repository.";
134 }
136​
137export const GitHubCliError = Schema.Union([
138 GitHubCliUnavailableError,
139 GitHubCliAuthenticationError,
140 GitHubCliRateLimitError,
141 GitHubPullRequestNotFoundError,
142 GitHubCliCommandError,
143 GitHubPullRequestListDecodeError,
144 GitHubChangeRequestListDecodeError,
145 GitHubPullRequestDecodeError,
146 GitHubRepositoryDecodeError,
147]);
148export type GitHubCliError = typeof GitHubCliError.Type;
149​
150export const isGitHubCliError = Schema.is(GitHubCliError);
151​
152/** Maps a GitHub API failure onto the errors callers of this service already handle. */
153function fromGitHubApiError(cwd: string, error: GitHubApi.GitHubApiError): GitHubCliError {
154 const context = { command: "gh" as const, cwd, cause: error };
155 switch (error._tag) {
156 case "GitHubCliMissingError":
157 return new GitHubCliUnavailableError(context);
158 case "GitHubNotSignedInError":
159 case "GitHubHostDisabledError":
160 case "GitHubApiAuthenticationError":
161 return new GitHubCliAuthenticationError(context);
162 case "GitHubCliFailedError":
163 return new GitHubCliCommandError(context);
164 case "GitHubApiRateLimitError":
165 return new GitHubCliRateLimitError({
166 ...context,
167 ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
168 });
169 case "SourceControlRateLimitPausedError":
170 return new GitHubCliRateLimitError({ ...context, retryAt: error.retryAt });
171 case "GitHubApiNotFoundError":
172 return new GitHubPullRequestNotFoundError(context);
173 case "GitHubApiResponseError":
174 return new GitHubCliCommandError({ ...context, httpStatus: error.status });
175 case "GitHubApiRequestError":
176 return new GitHubCliCommandError(context);
177 }
179​
180export interface GitHubPullRequestSummary {
181 readonly number: number;
182 readonly title: string;
183 readonly url: string;
184 readonly baseRefName: string;
185 readonly headRefName: string;
186 readonly state?: "open" | "closed" | "merged";
187 readonly isDraft?: boolean;
188 readonly closedAt?: string | null;
189 readonly mergedAt?: string | null;
190 readonly updatedAt?: string;
191 readonly isCrossRepository?: boolean;
192 readonly headRepositoryNameWithOwner?: string | null;
193 readonly headRepositoryOwnerLogin?: string | null;
195​
196function pullRequestSummary(input: NormalizedGitHubPullRequestRecord): GitHubPullRequestSummary {
197 const { updatedAt, ...summary } = input;
198 return {
199 ...summary,
200 ...(Option.isSome(updatedAt) ? { updatedAt: DateTime.formatIso(updatedAt.value) } : {}),
201 };
203​
204export interface GitHubRepositoryCloneUrls {
205 readonly nameWithOwner: string;
206 readonly url: string;
207 readonly sshUrl: string;
209​
210export class GitHubCli extends Context.Service<
211 GitHubCli,
212 {
213 readonly listOpenPullRequests: (input: {
214 readonly cwd: string;
215 readonly headSelector: string;
216 readonly limit?: number;
217 readonly rateLimitHost?: string;
218 }) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
219​
220 /**
221 * Pull requests whose head is `headSelector` (a branch, or `owner:branch` for a fork), in the
222 * repository `gh pr list` would read in `cwd`. Lookups on one repository that arrive
223 * together share one GraphQL document.
224 */
225 readonly listPullRequestsByHead: (input: {
226 readonly cwd: string;
227 readonly headSelector: string;
228 readonly state: "open" | "closed" | "merged" | "all";
229 readonly limit: number;
230 /** The checkout's GitHub API host. Without it, the host comes from the git remotes. */
231 readonly rateLimitHost?: string;
232 }) => Effect.Effect<ReadonlyArray<NormalizedGitHubPullRequestRecord>, GitHubCliError>;
233​
234 readonly getPullRequest: (input: {
235 readonly cwd: string;
236 readonly reference: string;
237 readonly rateLimitHost?: string;
238 }) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
239​
240 readonly getRepositoryCloneUrls: (input: {
241 readonly cwd: string;
242 readonly repository: string;
243 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
244​
245 readonly createRepository: (input: {
246 readonly cwd: string;
247 readonly repository: string;
248 readonly visibility: SourceControlRepositoryVisibility;
249 }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
250​
251 readonly createPullRequest: (input: {
252 readonly cwd: string;
253 readonly baseBranch: string;
254 readonly headSelector: string;
255 readonly title: string;
256 readonly bodyFile: string;
257 }) => Effect.Effect<void, GitHubCliError>;
258​
259 readonly getDefaultBranch: (input: {
260 readonly cwd: string;
261 readonly rateLimitHost?: string;
262 }) => Effect.Effect<string | null, GitHubCliError>;
263​
264 readonly checkoutPullRequest: (input: {
265 readonly cwd: string;
266 readonly reference: string;
267 readonly force?: boolean;
268 }) => Effect.Effect<void, GitHubCliError>;
269 }
270>()("t3/sourceControl/GitHubCli") {}
271​
272/**
273 * The repository `gh pr list` reads in a checkout, picked the way gh picks one without a
274 * prompt: the remote `gh repo set-default` marked, else the first of upstream, github, origin
275 * (in any case), else the only remote. `remotes` is `git remote -v` output and `resolved` is the output of
276 * `git config --get-regexp '^remote\..*\.gh-resolved$'`.
277 *
278 * Null whenever gh might weigh the remotes differently: a remote on another host or under an
279 * SSH alias, more than one mark, or several remotes with none of those names. Callers then
280 * fall back to the provider's remote, then to the best-ranked remote on the host.
281 */
282export function selectGitHubBaseRepository(input: {
283 readonly remotes: string;
284 readonly resolved: string;
285 readonly host: string;
286}): { readonly owner: string; readonly name: string } | null {
287 const host = input.host.toLowerCase();
288 const repositories = new Map<string, { readonly owner: string; readonly name: string }>();
289 for (const line of input.remotes.split("\n")) {
290 const match = /^(\S+)\s+(\S+)\s+\(fetch\)$/u.exec(line.trim());
291 if (!match) continue;
292 const [remoteHost, owner, name, ...rest] = normalizeGitRemoteUrl(match[2]!).split("/");
293 if (remoteHost !== host || !owner || !name || rest.length > 0) return null;
294 repositories.set(match[1]!, { owner, name });
295 }
296 const marks = input.resolved
297 .split("\n")
298 .map((line) => /^remote\.(.+)\.gh-resolved\s+(\S+)$/u.exec(line.trim()))
299 .filter((match): match is RegExpExecArray => match !== null && repositories.has(match[1]!));
300 if (marks.length > 1) return null;
301 const [mark] = marks;
302 if (mark) {
303 if (mark[2] === "base") return repositories.get(mark[1]!) ?? null;
304 const [owner, name, ...rest] = mark[2]!.toLowerCase().split("/");
305 return owner && name && rest.length === 0 ? { owner, name } : null;
306 }
307 // gh sorts remotes by these names, case-insensitively, and takes the first. A tie for the
308 // top place has no defined winner.
309 const score = (remoteName: string) =>
310 ["origin", "github", "upstream"].indexOf(remoteName.toLowerCase()) + 1;
311 const ranked = [...repositories.entries()].toSorted(
312 ([left], [right]) => score(right) - score(left),
313 );
314 const [top, next] = ranked;
315 return top !== undefined && (next === undefined || score(top[0]) > score(next[0]))
316 ? top[1]
317 : null;
319​
320const RawRepositorySchema = Schema.Struct({
321 full_name: TrimmedNonEmptyString,
322 html_url: TrimmedNonEmptyString,
323 ssh_url: TrimmedNonEmptyString,
324 default_branch: Schema.optional(Schema.NullOr(Schema.String)),
325});
326const decodeRawRepository = decodeJsonResult(RawRepositorySchema);
327​
328function repositoryCloneUrls(
329 raw: Schema.Schema.Type<typeof RawRepositorySchema>,
330): GitHubRepositoryCloneUrls {
331 return { nameWithOwner: raw.full_name, url: raw.html_url, sshUrl: raw.ssh_url };
333​
334const decodeViewerLogin = decodeJsonResult(Schema.Struct({ login: TrimmedNonEmptyString }));
335​
336type PullRequestListState = "open" | "closed" | "merged" | "all";
337​
338/** The pull request fields every read selects, in GraphQL. */
339const PULL_REQUEST_NODE_SELECTION =
340 "number title url baseRefName headRefName state isDraft mergedAt closedAt updatedAt isCrossRepository headRepository { name nameWithOwner } headRepositoryOwner { login }";
341const GRAPHQL_STATES: Record<PullRequestListState, ReadonlyArray<string>> = {
342 open: ["OPEN"],
343 closed: ["CLOSED"],
344 merged: ["MERGED"],
345 all: ["OPEN", "CLOSED", "MERGED"],
346};
347/**
348 * Head lookups per GraphQL document. A document of a hundred costs one point, the same as one
349 * single lookup, but half that keeps each answer near half a second.
350 */
351const HEAD_LOOKUPS_PER_DOCUMENT = 50;
352/**
353 * How long a head lookup waits for company. Branch discovery reaches GitHub only after each
354 * branch's own git reads, so lookups started together arrive tens of milliseconds apart.
355 * A background sweep's lookups spread over up to ~300ms, and every document costs a point no
356 * matter how few heads it holds, so reads without reserve wait longer.
357 */
358const HEAD_LOOKUP_BATCH_WINDOW = "50 millis";
359const BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW = "500 millis";
360/**
361 * Background documents fill up under the longer window, and a failed document fails every head
362 * in it. Fifty `main`-like heads of a hundred pull requests each took up to ~10s, GitHub's own
363 * processing limit; twenty-five took ~7s.
364 */
365const BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT = 25;
366/** A full document is 5,000 rows of well under 2 KB each. */
367const HEAD_LOOKUP_MAX_RESPONSE_BYTES = 16_000_000;
368/**
369 * Rows read for a fork's `owner:branch` head, which GitHub cannot filter by owner. A branch
370 * named like a busy default (`main`) is the case this bounds; the owner's own row is near the
371 * top because the newest come first.
372 */
373const OWNER_HEAD_SCAN_LIMIT = 100;
374​
375class PullRequestsByHeadRead extends Request.Class<
376 {
377 readonly cwd: string;
378 readonly host: string;
379 readonly owner: string;
380 readonly name: string;
381 readonly headRefName: string;
382 readonly state: PullRequestListState;
383 readonly limit: number;
384 readonly allowReserve: boolean;
385 },
386 ReadonlyArray<NormalizedGitHubPullRequestRecord>,
387 GitHubCliError
388> {}
389​
390/** One aliased `pullRequests` connection per lookup, each head and state passed as a variable. */
391function buildPullRequestsByHeadQuery(
392 lookups: ReadonlyArray<Pick<PullRequestsByHeadRead, "headRefName" | "state" | "limit">>,
393): { readonly document: string; readonly variables: Record<string, unknown> } {
394 const variables: Record<string, unknown> = {};
395 const declarations: string[] = ["$owner: String!", "$name: String!"];
396 const selections: string[] = [];
397 for (const [index, lookup] of lookups.entries()) {
398 variables[`h${index}`] = lookup.headRefName;
399 variables[`s${index}`] = GRAPHQL_STATES[lookup.state];
400 declarations.push(`$h${index}: String!`, `$s${index}: [PullRequestState!]`);
401 // `gh pr list` orders the same way, so a head with more matches than the limit keeps the
402 // same rows.
403 selections.push(
404 ` h${index}: pullRequests(headRefName: $h${index}, states: $s${index}, first: ${lookup.limit}, orderBy: { field: CREATED_AT, direction: DESC }) { nodes { ${PULL_REQUEST_NODE_SELECTION} } }`,
405 );
406 }
407 return {
408 document: `query PullRequestsByHead(${declarations.join(", ")}) {\n repository(owner: $owner, name: $name) {\n${selections.join("\n")}\n }\n}`,
409 variables,
410 };
412​
413const PULL_REQUEST_BY_NUMBER_QUERY = `query PullRequestByNumber($owner: String!, $name: String!, $number: Int!) {
414 repository(owner: $owner, name: $name) {
415 pullRequest(number: $number) { ${PULL_REQUEST_NODE_SELECTION} }
416 }
417}`;
418​
419const decodePullRequestsByHead = decodeJsonResult(
420 Schema.Struct({
421 data: Schema.Struct({
422 repository: Schema.NullOr(
423 Schema.Record(
424 Schema.String,
425 Schema.NullOr(Schema.Struct({ nodes: Schema.Array(Schema.Unknown) })),
426 ),
427 ),
428 }),
429 }),
430);
431​
432const decodePullRequestByNumber = decodeJsonResult(
433 Schema.Struct({
434 data: Schema.Struct({
435 repository: Schema.NullOr(Schema.Struct({ pullRequest: Schema.NullOr(Schema.Unknown) })),
436 }),
437 }),
438);
439​
440/** A repository on a GitHub host: the API it is read through, and its owner and name. */
441export interface GitHubRepositoryLocator {
442 readonly host: string;
443 readonly owner: string;
444 readonly name: string;
446​
447/** `owner/name` or `host/owner/name`, as `gh --repo` and GH_REPO take them. */
448function parseGitHubRepositorySelector(
449 selector: string,
450 defaultHost: string,
451): GitHubRepositoryLocator | null {
452 const trimmed = selector.trim().replace(/\.git$/i, "");
453 if (/^https?:\/\//i.test(trimmed)) {
454 try {
455 const url = new URL(trimmed);
456 const [owner, name, ...rest] = url.pathname.split("/").filter(Boolean);
457 return owner && name && rest.length === 0
458 ? { host: url.host.toLowerCase(), owner, name }
459 : null;
460 } catch {
461 return null;
462 }
463 }
464 const parts = trimmed.split("/").filter(Boolean);
465 if (parts.length === 2) return { host: defaultHost, owner: parts[0]!, name: parts[1]! };
466 if (parts.length === 3)
467 return { host: parts[0]!.toLowerCase(), owner: parts[1]!, name: parts[2]! };
468 return null;
470​
471/**
472 * A pull request reference the way `gh pr view` takes one: a number (`#7` too), a pull request
473 * URL, or a branch name.
474 */
475function parsePullRequestReference(
476 reference: string,
477):
478 | { readonly kind: "number"; readonly number: number }
479 | { readonly kind: "url"; readonly locator: GitHubRepositoryLocator; readonly number: number }
480 | { readonly kind: "branch"; readonly headSelector: string } {
481 const trimmed = reference.trim();
482 const numbered = /^#?([1-9]\d*)$/.exec(trimmed);
483 if (numbered) return { kind: "number", number: Number(numbered[1]) };
484 if (/^https?:\/\//i.test(trimmed)) {
485 try {
486 const url = new URL(trimmed);
487 const match = /^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)(?:\/.*)?$/.exec(url.pathname);
488 if (match) {
489 return {
490 kind: "url",
491 locator: { host: url.host.toLowerCase(), owner: match[1]!, name: match[2]! },
492 number: Number(match[3]),
493 };
494 }
495 } catch {
496 // Not a URL after all; read it as a branch.
497 }
498 }
499 return { kind: "branch", headSelector: trimmed };
501​
502/**
503 * The GitHub host a remote URL is served from, or null for a remote that is not GitHub. An SSH
504 * alias (`git@github-work:owner/repo`) names no API host of its own; it is read through
505 * `github.com`, which is what such an alias almost always stands for (issue #6198).
506 */
507export function gitHubApiHostForRemote(remoteUrl: string): string | null {
508 const provider = detectSourceControlProviderFromRemoteUrl(remoteUrl);
509 if (provider === null) return null;
510 const host = new URL(provider.baseUrl).host.toLowerCase();
511 // A dotless SSH host is an alias from ~/.ssh/config, never a real API host.
512 if (isSshRemoteUrl(remoteUrl) && !host.includes(".")) {
513 return host.includes("github") ? "github.com" : null;
514 }
515 return provider.kind === "github" ? host : null;
517​
518/** A caller's host hint, read the way a remote's host is: a dotless alias is not an API host. */
519function apiHostForHint(host: string): string {
520 const normalized = host.toLowerCase();
521 return !normalized.includes(".") && normalized.includes("github") ? "github.com" : normalized;
523​
524/** The local branch a pull request checks out into, the way `gh pr checkout` names it. */
525export function pullRequestCheckoutBranchName(input: {
526 readonly headRefName: string;
527 readonly headOwner: string | null;
528 readonly isCrossRepository: boolean;
529 readonly defaultBranch: string | null;
530}): string {
531 // gh prefixes the owner only where the fork's branch would take over the default branch's
532 // name, which is the one collision every fork pull request from `main` would hit.
533 return input.isCrossRepository &&
534 input.headOwner !== null &&
535 input.defaultBranch !== null &&
536 input.headRefName === input.defaultBranch
537 ? `${input.headOwner}/${input.headRefName}`
538 : input.headRefName;
540​
541/** @public Service construction is part of the canonical Effect module API. */
542export const make = Effect.gen(function* () {
543 const process = yield* VcsProcess.VcsProcess;
544 const environment = yield* HostProcessEnvironment;
545 const api = yield* GitHubApi.GitHubApi;
546 const git = yield* GitVcsDriver.GitVcsDriver;
547 const fileSystem = yield* FileSystem.FileSystem;
548​
549 const gitRead = (cwd: string, args: ReadonlyArray<string>) =>
550 process.run({
551 operation: "GitHubCli.resolveRepository",
552 command: "git",
553 args,
554 cwd,
555 allowNonZeroExit: true,
556 timeoutMs: 5_000,
557 });
558​
559 const commandFailure = (cwd: string, detail: string) =>
560 new GitHubCliCommandError({ command: "gh", cwd, cause: new Error(detail) });
561​
562 /**
563 * The repository `gh` would act on in `cwd`: GH_REPO, else the remote `gh` would pick, else
564 * the remote the caller resolved the provider from, else the best-ranked GitHub remote.
565 */
566 const resolveRepository = Effect.fn("GitHubCli.resolveRepository")(function* (input: {
567 readonly cwd: string;
568 readonly host?: string | undefined;
569 }) {
570 const envRepository = environment.GH_REPO?.trim();
571 const defaultHost = (input.host ?? environment.GH_HOST ?? "github.com").toLowerCase();
572 if (envRepository) {
573 const locator = parseGitHubRepositorySelector(envRepository, defaultHost);
574 if (locator !== null) return locator;
575 }
576 const [remotes, resolved] = yield* Effect.all([
577 gitRead(input.cwd, ["remote", "-v"]),
578 gitRead(input.cwd, ["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"]),
579 ]).pipe(Effect.orElseSucceed(() => [null, null] as const));
580 const remoteOutput = remotes?.exitCode === 0 ? remotes.stdout : "";
581 const fetchRemotes = remoteOutput
582 .split("\n")
583 .map((line) => /^(\S+)\s+(\S+)\s+\(fetch\)$/u.exec(line.trim()))
584 .filter((match): match is RegExpExecArray => match !== null)
585 .map((match) => ({
586 name: match[1]!,
587 url: match[2]!,
588 host: gitHubApiHostForRemote(match[2]!),
589 }));
590 const host =
591 (input.host === undefined ? undefined : apiHostForHint(input.host)) ??
592 fetchRemotes.find((remote) => remote.name === "origin" && remote.host !== null)?.host ??
593 fetchRemotes.find((remote) => remote.host !== null)?.host ??
594 defaultHost;
595 const selected = selectGitHubBaseRepository({
596 remotes: remoteOutput,
597 resolved: resolved?.exitCode === 0 ? resolved.stdout : "",
598 host,
599 });
600 if (selected !== null) return { host, ...selected };
601 // gh's own order without its prompt: upstream, github, origin, then the first remote, among
602 // the ones on this host (an SSH alias counts as its API host).
603 const rank = (name: string) => ["upstream", "github", "origin"].indexOf(name.toLowerCase());
604 const candidates = fetchRemotes
605 .filter((remote) => remote.host === host)
606 .toSorted((left, right) => {
607 const l = rank(left.name);
608 const r = rank(right.name);
609 return (l === -1 ? 99 : l) - (r === -1 ? 99 : r);
610 });
611 for (const remote of candidates) {
612 const [owner, name, ...rest] = normalizeGitRemoteUrl(remote.url).split("/").slice(1);
613 if (owner && name && rest.length === 0) return { host, owner, name };
614 }
615 return yield* commandFailure(
616 input.cwd,
617 `No GitHub repository on ${host} was found among this checkout's git remotes.`,
618 );
619 });
620​
621 const graphqlJson = <A>(
622 cwd: string,
623 input: GitHubApi.GitHubGraphQlInput,
624 decode: (raw: string) => Result.Result<A, unknown>,
625 onDecodeFailure: (cause: unknown) => GitHubCliError,
626 ) =>
627 api.graphql(input).pipe(
628 Effect.mapError((error) => fromGitHubApiError(cwd, error)),
629 Effect.flatMap((raw) => {
630 const decoded = decode(raw);
631 return Result.isSuccess(decoded)
632 ? Effect.succeed(decoded.success)
633 : Effect.fail(onDecodeFailure(decoded.failure));
634 }),
635 );
636​
637 const rest = (cwd: string, input: GitHubApi.GitHubRestInput) =>
638 api.rest(input).pipe(Effect.mapError((error) => fromGitHubApiError(cwd, error)));
639​
640 /** Pull requests whose head branch is `headRefName` on one repository. */
641 const readPullRequestsByHead = (input: {
642 readonly cwd: string;
643 readonly locator: GitHubRepositoryLocator;
644 readonly lookups: ReadonlyArray<
645 Pick<PullRequestsByHeadRead, "headRefName" | "state" | "limit">
646 >;
647 readonly allowReserve: boolean;
648 readonly onDecodeFailure: (cause: unknown) => GitHubCliError;
649 }) => {
650 const query = buildPullRequestsByHeadQuery(input.lookups);
651 return graphqlJson(
652 input.cwd,
653 {
654 host: input.locator.host,
655 operation: "listPullRequestsByHead",
656 query: query.document,
657 variables: { owner: input.locator.owner, name: input.locator.name, ...query.variables },
658 allowReserve: input.allowReserve,
659 // Up to 50 heads of 100 rows each. A default branch such as `main` can match a hundred
660 // fork pull requests, so the usual cap would cut the answer short.
661 maxResponseBytes: HEAD_LOOKUP_MAX_RESPONSE_BYTES,
662 },
663 decodePullRequestsByHead,
664 input.onDecodeFailure,
665 ).pipe(
666 Effect.flatMap((decoded) =>
667 decoded.data.repository === null
668 ? Effect.fail(
669 new GitHubPullRequestNotFoundError({
670 command: "gh",
671 cwd: input.cwd,
672 cause: new Error("The repository could not be read."),
673 }),
674 )
675 : Effect.succeed(decoded.data.repository),
676 ),
677 );
678 };
679​
680 const headResolver = RequestResolver.makeGrouped<PullRequestsByHeadRead, string>({
681 key: ({ request, context }) =>
682 [
683 request.host,
684 request.owner,
685 request.name,
686 String(request.allowReserve),
687 Context.getOrElse(context, GitHubApi.PinnedGitHubCredential, () => null)
688 ?.credentialFingerprint ?? "",
689 Context.getOrElse(context, SourceControlRateLimit.CredentialScope, () => ""),
690 ].join("\0"),
691 resolver: (entries) => {
692 const [first] = entries;
693 const { cwd, host, owner, name, allowReserve } = first.request;
694 return readPullRequestsByHead({
695 cwd,
696 locator: { host, owner, name },
697 lookups: entries.map((entry) => entry.request),
698 allowReserve,
699 onDecodeFailure: (cause) =>
700 new GitHubChangeRequestListDecodeError({ command: "gh", cwd, cause }),
701 }).pipe(
702 Effect.map((aliases) => {
703 for (const [index, entry] of entries.entries()) {
704 const alias = aliases[`h${index}`];
705 entry.completeUnsafe(
706 Exit.succeed(alias == null ? [] : decodeGitHubPullRequestEntries(alias.nodes)),
707 );
708 }
709 }),
710 Effect.catchCause((cause) =>
711 Effect.sync(() => {
712 for (const entry of entries) entry.completeUnsafe(Exit.failCause(cause));
713 }),
714 ),
715 );
716 },
717 }).pipe(RequestResolver.batchN(HEAD_LOOKUPS_PER_DOCUMENT));
718 const interactiveHeadResolver = headResolver.pipe(
719 RequestResolver.setDelay(HEAD_LOOKUP_BATCH_WINDOW),
720 );
721 const backgroundHeadResolver = headResolver.pipe(
722 RequestResolver.batchN(BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT),
723 RequestResolver.setDelay(BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW),
724 );
725​
726 const listByHead = Effect.fn("GitHubCli.listByHead")(function* (input: {
727 readonly cwd: string;
728 readonly headSelector: string;
729 readonly state: PullRequestListState;
730 readonly limit: number;
731 readonly rateLimitHost?: string | undefined;
732 readonly allowReserve: boolean;
733 }) {
734 const locator = yield* resolveRepository({ cwd: input.cwd, host: input.rateLimitHost });
735 const limit = Math.min(Math.max(Math.trunc(input.limit), 1), 100);
736 // `owner:branch` names a fork's branch. GitHub filters on the branch name only, so the
737 // owner is matched on the rows it returns.
738 const ownerMatch = /^([^:/\s]+):(.+)$/u.exec(input.headSelector.trim());
739 const headRefName = ownerMatch?.[2] ?? input.headSelector.trim();
740 const rows = yield* Effect.request(
741 new PullRequestsByHeadRead({
742 cwd: input.cwd,
743 ...locator,
744 headRefName,
745 state: input.state,
746 limit: ownerMatch ? OWNER_HEAD_SCAN_LIMIT : limit,
747 allowReserve: input.allowReserve,
748 }),
749 input.allowReserve ? interactiveHeadResolver : backgroundHeadResolver,
750 );
751 if (!ownerMatch) return rows;
752 const headOwner = ownerMatch[1]!.toLowerCase();
753 return rows
754 .filter((row) => row.headRepositoryOwnerLogin?.toLowerCase() === headOwner)
755 .slice(0, limit);
756 });
757​
758 const toSummaries = (rows: ReadonlyArray<NormalizedGitHubPullRequestRecord>) =>
759 rows.map(pullRequestSummary);
760​
761 const readPullRequest = Effect.fn("GitHubCli.readPullRequest")(function* (input: {
762 readonly cwd: string;
763 readonly reference: string;
764 readonly rateLimitHost?: string | undefined;
765 }) {
766 const parsed = parsePullRequestReference(input.reference);
767 if (parsed.kind === "branch") {
768 // `gh pr view <branch>` prefers an open pull request, then the newest of any state.
769 const [open] = yield* listByHead({
770 cwd: input.cwd,
771 headSelector: parsed.headSelector,
772 state: "open",
773 limit: 1,
774 rateLimitHost: input.rateLimitHost,
775 allowReserve: true,
776 });
777 const found =
778 open ??
779 (yield* listByHead({
780 cwd: input.cwd,
781 headSelector: parsed.headSelector,
782 state: "all",
783 limit: 1,
784 rateLimitHost: input.rateLimitHost,
785 allowReserve: true,
786 }))[0];
787 if (found === undefined) {
788 return yield* new GitHubPullRequestNotFoundError({
789 command: "gh",
790 cwd: input.cwd,
791 cause: new Error("No pull request has this head branch."),
792 });
793 }
794 return found;
795 }
796 const locator =
797 parsed.kind === "url"
798 ? parsed.locator
799 : yield* resolveRepository({ cwd: input.cwd, host: input.rateLimitHost });
800 const decodeFailure = (cause: unknown) =>
801 new GitHubPullRequestDecodeError({ command: "gh", cwd: input.cwd, cause });
802 const decoded = yield* graphqlJson(
803 input.cwd,
804 {
805 host: locator.host,
806 operation: "getPullRequest",
807 query: PULL_REQUEST_BY_NUMBER_QUERY,
808 variables: { owner: locator.owner, name: locator.name, number: parsed.number },
809 allowReserve: true,
810 },
811 decodePullRequestByNumber,
812 decodeFailure,
813 );
814 const node = decoded.data.repository?.pullRequest;
815 if (node == null) {
816 return yield* new GitHubPullRequestNotFoundError({
817 command: "gh",
818 cwd: input.cwd,
819 cause: new Error("The pull request does not exist."),
820 });
821 }
822 const [record] = decodeGitHubPullRequestEntries([node]);
823 if (record === undefined) return yield* decodeFailure(new Error("Malformed pull request."));
824 return record;
825 });
826​
827 const readRepository = Effect.fn("GitHubCli.readRepository")(function* (
828 cwd: string,
829 locator: GitHubRepositoryLocator,
830 ) {
831 const response = yield* rest(cwd, {
832 host: locator.host,
833 operation: "getRepository",
834 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}`,
835 allowReserve: true,
836 });
837 const decoded = decodeRawRepository(response.body);
838 if (Result.isFailure(decoded)) {
839 return yield* new GitHubRepositoryDecodeError({
840 command: "gh",
841 cwd,
842 cause: decoded.failure,
843 });
844 }
845 return decoded.success;
846 });
847​
848 const readViewerLogin = Effect.fn("GitHubCli.readViewerLogin")(function* (
849 cwd: string,
850 host: string,
851 ) {
852 const response = yield* rest(cwd, { host, operation: "getViewer", path: "user" });
853 const decoded = decodeViewerLogin(response.body);
854 if (Result.isFailure(decoded)) {
855 return yield* new GitHubCliCommandError({ command: "gh", cwd, cause: decoded.failure });
856 }
857 return decoded.success.login;
858 });
859​
860 const gitFailure = (cwd: string) => (cause: unknown) =>
861 new GitHubCliCommandError({ command: "gh", cwd, cause });
862​
863 const runGit = (cwd: string, operation: string, args: ReadonlyArray<string>) =>
864 git.execute({ operation: `GitHubCli.checkoutPullRequest.${operation}`, cwd, args });
865​
866 /**
867 * `gh pr checkout` in plain git: the head branch is fetched from the remote that holds it (a
868 * fork gets a remote of its own), checked out under the name gh would give it, and set to
869 * track the head. A head branch that is gone is read from the base's `refs/pull/<n>/head`.
870 * An existing branch fast-forwards, or with `force` is reset to the pull request.
871 */
872 const checkoutPullRequest: GitHubCli["Service"]["checkoutPullRequest"] = Effect.fn(
873 "GitHubCli.checkoutPullRequest",
874 )(function* (input) {
875 const reference = parsePullRequestReference(input.reference);
876 const pullRequest = yield* readPullRequest({ cwd: input.cwd, reference: input.reference });
877 const base =
878 reference.kind === "url" ? reference.locator : yield* resolveRepository({ cwd: input.cwd });
879 const baseNameWithOwner = `${base.owner}/${base.name}`.toLowerCase();
880 const headNameWithOwner = pullRequest.headRepositoryNameWithOwner ?? null;
881 const isCrossRepository =
882 pullRequest.isCrossRepository ??
883 (headNameWithOwner !== null && headNameWithOwner.toLowerCase() !== baseNameWithOwner);
884 const headOwner =
885 pullRequest.headRepositoryOwnerLogin ?? headNameWithOwner?.split("/")[0] ?? null;
886​
887 const remotes = yield* gitRead(input.cwd, ["remote", "-v"]).pipe(
888 Effect.map((result) => (result.exitCode === 0 ? result.stdout : "")),
889 Effect.mapError(gitFailure(input.cwd)),
890 );
891 const remoteFor = (nameWithOwner: string) =>
892 remotes
893 .split("\n")
894 .map((line) => /^(\S+)\s+(\S+)\s+\(fetch\)$/u.exec(line.trim()))
895 .find(
896 (match) =>
897 match !== null &&
898 normalizeGitRemoteUrl(match[2]!).split("/").slice(1).join("/") ===
899 nameWithOwner.toLowerCase(),
900 )?.[1] ?? null;
901 const baseRemote = Effect.suspend(() => {
902 const known = remoteFor(baseNameWithOwner);
903 return known === null ? git.resolvePrimaryRemoteName(input.cwd) : Effect.succeed(known);
904 });
905 // A fork's branch named like the base's default branch is checked out under the owner's
906 // prefix. Without the default branch that collision cannot be ruled out, and the checkout
907 // would reset the local default branch to the fork's commit, so it fails instead.
908 const defaultBranch = isCrossRepository
909 ? yield* readRepository(input.cwd, base).pipe(
910 Effect.map((repository) => repository.default_branch ?? null),
911 )
912 : null;
913 const localBranch = pullRequestCheckoutBranchName({
914 headRefName: pullRequest.headRefName,
915 headOwner,
916 isCrossRepository,
917 defaultBranch,
918 });
919​
920 /** The remote the head branch lives on; a fork the checkout does not know yet is added. */
921 const headRemote = Effect.gen(function* () {
922 if (!isCrossRepository) return yield* baseRemote;
923 if (headNameWithOwner === null) return yield* commandFailure(input.cwd, "The fork is gone.");
924 const known = remoteFor(headNameWithOwner);
925 if (known !== null) return known;
926 const [owner, name] = headNameWithOwner.split("/");
927 const fork = yield* readRepository(input.cwd, {
928 host: base.host,
929 owner: owner!,
930 name: name!,
931 });
932 const originUrl = yield* git.readConfigValue(input.cwd, "remote.origin.url");
933 return yield* git.ensureRemote({
934 cwd: input.cwd,
935 preferredName: headOwner ?? "fork",
936 url: originUrl !== null && isSshRemoteUrl(originUrl) ? fork.ssh_url : fork.html_url,
937 });
938 });
939​
940 const exists = (yield* git
941 .listLocalBranchNames(input.cwd)
942 .pipe(Effect.mapError(gitFailure(input.cwd)))).includes(localBranch);
943​
944 // The commit to check out, fetched from the head branch where it still exists.
945 const target = yield* Effect.gen(function* () {
946 const remoteName = yield* headRemote;
947 yield* git.fetchRemoteTrackingBranch({
948 cwd: input.cwd,
949 remoteName,
950 remoteBranch: pullRequest.headRefName,
951 });
952 return {
953 ref: `refs/remotes/${remoteName}/${pullRequest.headRefName}`,
954 upstream: { remoteName, remoteBranch: pullRequest.headRefName },
955 };
956 }).pipe(
957 Effect.catch(() =>
958 Effect.gen(function* () {
959 yield* runGit(input.cwd, "fetchPullRef", [
960 "fetch",
961 "--quiet",
962 "--no-tags",
963 yield* baseRemote,
964 `refs/pull/${pullRequest.number}/head`,
965 ]);
966 const { commitSha } = yield* git.resolveCommit({
967 cwd: input.cwd,
968 revision: "FETCH_HEAD",
969 });
970 return { ref: commitSha, upstream: null };
971 }),
972 ),
973 Effect.mapError(gitFailure(input.cwd)),
974 );
975​
976 yield* Effect.gen(function* () {
977 if (!exists) yield* runGit(input.cwd, "branch", ["branch", localBranch, target.ref]);
978 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
979 if (exists) {
980 yield* runGit(
981 input.cwd,
982 "sync",
983 input.force === true
984 ? ["reset", "--hard", "--quiet", target.ref]
985 : ["merge", "--ff-only", "--quiet", target.ref],
986 );
987 }
988 // Tracking is set once the branch is the pull request's, so a sync that fails leaves an
989 // existing branch's upstream as it was.
990 if (target.upstream !== null) {
991 yield* git.setBranchUpstream({ cwd: input.cwd, branch: localBranch, ...target.upstream });
992 }
993 }).pipe(Effect.mapError(gitFailure(input.cwd)));
994 });
995​
996 return GitHubCli.of({
997 listPullRequestsByHead: (input) =>
998 AllowGitHubReserve.pipe(
999 Effect.flatMap((allowReserve) => listByHead({ ...input, allowReserve })),
1000 ),
1001 listOpenPullRequests: (input) =>
1002 listByHead({
1003 cwd: input.cwd,
1004 headSelector: input.headSelector,
1005 state: "open",
1006 limit: input.limit ?? 1,
1007 rateLimitHost: input.rateLimitHost,
1008 allowReserve: true,
1009 }).pipe(Effect.map(toSummaries)),
1010 getPullRequest: (input) => readPullRequest(input).pipe(Effect.map(pullRequestSummary)),
1011 getRepositoryCloneUrls: (input) =>
1012 Effect.gen(function* () {
1013 const fallbackHost = (yield* resolveRepository({ cwd: input.cwd }).pipe(
1014 Effect.map((locator) => locator.host),
1015 Effect.orElseSucceed(() => environment.GH_HOST ?? "github.com"),
1016 )).toLowerCase();
1017 const locator = parseGitHubRepositorySelector(input.repository, fallbackHost);
1018 if (locator === null) {
1019 return yield* commandFailure(input.cwd, "Repositories are named owner/name.");
1021 return repositoryCloneUrls(yield* readRepository(input.cwd, locator));
1022 }),
1023 createRepository: (input) =>
1024 Effect.gen(function* () {
1025 const locator = parseGitHubRepositorySelector(
1026 input.repository,
1027 (environment.GH_HOST ?? "github.com").toLowerCase(),
1028 );
1029 const viewer = locator === null ? null : yield* readViewerLogin(input.cwd, locator.host);
1030 const owner = locator?.owner ?? viewer;
1031 const name = locator?.name ?? input.repository.trim();
1032 const host = locator?.host ?? (environment.GH_HOST?.trim().toLowerCase() || "github.com");
1033 const isViewer = viewer !== null && owner?.toLowerCase() === viewer.toLowerCase();
1034 const response = yield* rest(input.cwd, {
1035 host,
1036 operation: "createRepository",
1037 method: "POST",
1038 path:
1039 isViewer || owner === null ? "user/repos" : `orgs/${encodeURIComponent(owner)}/repos`,
1040 body: { name, private: input.visibility === "private" },
1041 });
1042 const decoded = decodeRawRepository(response.body);
1043 if (Result.isFailure(decoded)) {
1044 return yield* new GitHubRepositoryDecodeError({
1045 command: "gh",
1046 cwd: input.cwd,
1047 cause: decoded.failure,
1048 });
1050 return repositoryCloneUrls(decoded.success);
1051 }),
1052 createPullRequest: (input) =>
1053 Effect.gen(function* () {
1054 const locator = yield* resolveRepository({ cwd: input.cwd });
1055 const body = yield* fileSystem
1056 .readFileString(input.bodyFile)
1057 .pipe(Effect.mapError(gitFailure(input.cwd)));
1058 yield* rest(input.cwd, {
1059 host: locator.host,
1060 operation: "createPullRequest",
1061 method: "POST",
1062 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}/pulls`,
1063 // `owner:branch` is how the REST API takes a fork's head, the same as `gh --head`.
1064 // gh allows maintainer edits unless told otherwise; the API's default is not documented.
1065 body: {
1066 base: input.baseBranch,
1067 head: input.headSelector,
1068 title: input.title,
1069 body,
1070 maintainer_can_modify: true,
1071 },
1072 });
1073 }),
1074 getDefaultBranch: (input) =>
1075 Effect.gen(function* () {
1076 const locator = yield* resolveRepository({ cwd: input.cwd, host: input.rateLimitHost });
1077 const repository = yield* readRepository(input.cwd, locator);
1078 const branch = repository.default_branch?.trim() ?? "";
1079 return branch.length > 0 ? branch : null;
1080 }),
1081 checkoutPullRequest,
1082 });
1083});
1084​
1085export const layer = Layer.effect(GitHubCli, make).pipe(
1086 Layer.provideMerge(GitHubApi.layer),
1087 Layer.provideMerge(GitHubCredentials.layer),
1088 Layer.provideMerge(GitHubGraphQlBudget.layer),
1089 Layer.provideMerge(SourceControlRateLimit.layer),