Open History to see the last commit
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 }
49}
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 }
61}
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 }
70}
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 }
79}
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 }
93}
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 }
108}
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 }
117}
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 }
126}
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 }
135}
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 }
178}
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;
194}
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 };
202}
203
204export interface GitHubRepositoryCloneUrls {
205 readonly nameWithOwner: string;
206 readonly url: string;
207 readonly sshUrl: string;
208}
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;
318}
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 };
332}
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 */
356const HEAD_LOOKUP_BATCH_WINDOW = "50 millis";
357/** A full document is 5,000 rows of well under 2 KB each. */
358const HEAD_LOOKUP_MAX_RESPONSE_BYTES = 16_000_000;
359/**
360 * Rows read for a fork's `owner:branch` head, which GitHub cannot filter by owner. A branch
361 * named like a busy default (`main`) is the case this bounds; the owner's own row is near the
362 * top because the newest come first.
363 */
364const OWNER_HEAD_SCAN_LIMIT = 100;
365
366class PullRequestsByHeadRead extends Request.Class<
367 {
368 readonly cwd: string;
369 readonly host: string;
370 readonly owner: string;
371 readonly name: string;
372 readonly headRefName: string;
373 readonly state: PullRequestListState;
374 readonly limit: number;
375 readonly allowReserve: boolean;
376 },
377 ReadonlyArray<NormalizedGitHubPullRequestRecord>,
378 GitHubCliError
379> {}
380
381/** One aliased `pullRequests` connection per lookup, each head and state passed as a variable. */
382function buildPullRequestsByHeadQuery(
383 lookups: ReadonlyArray<Pick<PullRequestsByHeadRead, "headRefName" | "state" | "limit">>,
384): { readonly document: string; readonly variables: Record<string, unknown> } {
385 const variables: Record<string, unknown> = {};
386 const declarations: string[] = ["$owner: String!", "$name: String!"];
387 const selections: string[] = [];
388 for (const [index, lookup] of lookups.entries()) {
389 variables[`h${index}`] = lookup.headRefName;
390 variables[`s${index}`] = GRAPHQL_STATES[lookup.state];
391 declarations.push(`$h${index}: String!`, `$s${index}: [PullRequestState!]`);
392 // `gh pr list` orders the same way, so a head with more matches than the limit keeps the
393 // same rows.
394 selections.push(
395 ` h${index}: pullRequests(headRefName: $h${index}, states: $s${index}, first: ${lookup.limit}, orderBy: { field: CREATED_AT, direction: DESC }) { nodes { ${PULL_REQUEST_NODE_SELECTION} } }`,
396 );
397 }
398 return {
399 document: `query PullRequestsByHead(${declarations.join(", ")}) {\n repository(owner: $owner, name: $name) {\n${selections.join("\n")}\n }\n}`,
400 variables,
401 };
402}
403
404const PULL_REQUEST_BY_NUMBER_QUERY = `query PullRequestByNumber($owner: String!, $name: String!, $number: Int!) {
405 repository(owner: $owner, name: $name) {
406 pullRequest(number: $number) { ${PULL_REQUEST_NODE_SELECTION} }
407 }
408}`;
409
410const decodePullRequestsByHead = decodeJsonResult(
411 Schema.Struct({
412 data: Schema.Struct({
413 repository: Schema.NullOr(
414 Schema.Record(
415 Schema.String,
416 Schema.NullOr(Schema.Struct({ nodes: Schema.Array(Schema.Unknown) })),
417 ),
418 ),
419 }),
420 }),
421);
422
423const decodePullRequestByNumber = decodeJsonResult(
424 Schema.Struct({
425 data: Schema.Struct({
426 repository: Schema.NullOr(Schema.Struct({ pullRequest: Schema.NullOr(Schema.Unknown) })),
427 }),
428 }),
429);
430
431/** A repository on a GitHub host: the API it is read through, and its owner and name. */
432export interface GitHubRepositoryLocator {
433 readonly host: string;
434 readonly owner: string;
435 readonly name: string;
436}
437
438/** `owner/name` or `host/owner/name`, as `gh --repo` and GH_REPO take them. */
439function parseGitHubRepositorySelector(
440 selector: string,
441 defaultHost: string,
442): GitHubRepositoryLocator | null {
443 const trimmed = selector.trim().replace(/\.git$/i, "");
444 if (/^https?:\/\//i.test(trimmed)) {
445 try {
446 const url = new URL(trimmed);
447 const [owner, name, ...rest] = url.pathname.split("/").filter(Boolean);
448 return owner && name && rest.length === 0
449 ? { host: url.host.toLowerCase(), owner, name }
450 : null;
451 } catch {
452 return null;
453 }
454 }
455 const parts = trimmed.split("/").filter(Boolean);
456 if (parts.length === 2) return { host: defaultHost, owner: parts[0]!, name: parts[1]! };
457 if (parts.length === 3)
458 return { host: parts[0]!.toLowerCase(), owner: parts[1]!, name: parts[2]! };
459 return null;
460}
461
462/**
463 * A pull request reference the way `gh pr view` takes one: a number (`#7` too), a pull request
464 * URL, or a branch name.
465 */
466function parsePullRequestReference(
467 reference: string,
468):
469 | { readonly kind: "number"; readonly number: number }
470 | { readonly kind: "url"; readonly locator: GitHubRepositoryLocator; readonly number: number }
471 | { readonly kind: "branch"; readonly headSelector: string } {
472 const trimmed = reference.trim();
473 const numbered = /^#?([1-9]\d*)$/.exec(trimmed);
474 if (numbered) return { kind: "number", number: Number(numbered[1]) };
475 if (/^https?:\/\//i.test(trimmed)) {
476 try {
477 const url = new URL(trimmed);
478 const match = /^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)(?:\/.*)?$/.exec(url.pathname);
479 if (match) {
480 return {
481 kind: "url",
482 locator: { host: url.host.toLowerCase(), owner: match[1]!, name: match[2]! },
483 number: Number(match[3]),
484 };
485 }
486 } catch {
487 // Not a URL after all; read it as a branch.
488 }
489 }
490 return { kind: "branch", headSelector: trimmed };
491}
492
493/**
494 * The GitHub host a remote URL is served from, or null for a remote that is not GitHub. An SSH
495 * alias (`git@github-work:owner/repo`) names no API host of its own; it is read through
496 * `github.com`, which is what such an alias almost always stands for (issue #6198).
497 */
498export function gitHubApiHostForRemote(remoteUrl: string): string | null {
499 const provider = detectSourceControlProviderFromRemoteUrl(remoteUrl);
500 if (provider === null) return null;
501 const host = new URL(provider.baseUrl).host.toLowerCase();
502 // A dotless SSH host is an alias from ~/.ssh/config, never a real API host.
503 if (isSshRemoteUrl(remoteUrl) && !host.includes(".")) {
504 return host.includes("github") ? "github.com" : null;
505 }
506 return provider.kind === "github" ? host : null;
507}
508
509/** A caller's host hint, read the way a remote's host is: a dotless alias is not an API host. */
510function apiHostForHint(host: string): string {
511 const normalized = host.toLowerCase();
512 return !normalized.includes(".") && normalized.includes("github") ? "github.com" : normalized;
513}
514
515/** The local branch a pull request checks out into, the way `gh pr checkout` names it. */
516export function pullRequestCheckoutBranchName(input: {
517 readonly headRefName: string;
518 readonly headOwner: string | null;
519 readonly isCrossRepository: boolean;
520 readonly defaultBranch: string | null;
521}): string {
522 // gh prefixes the owner only where the fork's branch would take over the default branch's
523 // name, which is the one collision every fork pull request from `main` would hit.
524 return input.isCrossRepository &&
525 input.headOwner !== null &&
526 input.defaultBranch !== null &&
527 input.headRefName === input.defaultBranch
528 ? `${input.headOwner}/${input.headRefName}`
529 : input.headRefName;
530}
531
532/** @public Service construction is part of the canonical Effect module API. */
533export const make = Effect.gen(function* () {
534 const process = yield* VcsProcess.VcsProcess;
535 const environment = yield* HostProcessEnvironment;
536 const api = yield* GitHubApi.GitHubApi;
537 const git = yield* GitVcsDriver.GitVcsDriver;
538 const fileSystem = yield* FileSystem.FileSystem;
539
540 const gitRead = (cwd: string, args: ReadonlyArray<string>) =>
541 process.run({
542 operation: "GitHubCli.resolveRepository",
543 command: "git",
544 args,
545 cwd,
546 allowNonZeroExit: true,
547 timeoutMs: 5_000,
548 });
549
550 const commandFailure = (cwd: string, detail: string) =>
551 new GitHubCliCommandError({ command: "gh", cwd, cause: new Error(detail) });
552
553 /**
554 * The repository `gh` would act on in `cwd`: GH_REPO, else the remote `gh` would pick, else
555 * the remote the caller resolved the provider from, else the best-ranked GitHub remote.
556 */
557 const resolveRepository = Effect.fn("GitHubCli.resolveRepository")(function* (input: {
558 readonly cwd: string;
559 readonly host?: string | undefined;
560 }) {
561 const envRepository = environment.GH_REPO?.trim();
562 const defaultHost = (input.host ?? environment.GH_HOST ?? "github.com").toLowerCase();
563 if (envRepository) {
564 const locator = parseGitHubRepositorySelector(envRepository, defaultHost);
565 if (locator !== null) return locator;
566 }
567 const [remotes, resolved] = yield* Effect.all([
568 gitRead(input.cwd, ["remote", "-v"]),
569 gitRead(input.cwd, ["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"]),
570 ]).pipe(Effect.orElseSucceed(() => [null, null] as const));
571 const remoteOutput = remotes?.exitCode === 0 ? remotes.stdout : "";
572 const fetchRemotes = remoteOutput
573 .split("\n")
574 .map((line) => /^(\S+)\s+(\S+)\s+\(fetch\)$/u.exec(line.trim()))
575 .filter((match): match is RegExpExecArray => match !== null)
576 .map((match) => ({
577 name: match[1]!,
578 url: match[2]!,
579 host: gitHubApiHostForRemote(match[2]!),
580 }));
581 const host =
582 (input.host === undefined ? undefined : apiHostForHint(input.host)) ??
583 fetchRemotes.find((remote) => remote.name === "origin" && remote.host !== null)?.host ??
584 fetchRemotes.find((remote) => remote.host !== null)?.host ??
585 defaultHost;
586 const selected = selectGitHubBaseRepository({
587 remotes: remoteOutput,
588 resolved: resolved?.exitCode === 0 ? resolved.stdout : "",
589 host,
590 });
591 if (selected !== null) return { host, ...selected };
592 // gh's own order without its prompt: upstream, github, origin, then the first remote, among
593 // the ones on this host (an SSH alias counts as its API host).
594 const rank = (name: string) => ["upstream", "github", "origin"].indexOf(name.toLowerCase());
595 const candidates = fetchRemotes
596 .filter((remote) => remote.host === host)
597 .toSorted((left, right) => {
598 const l = rank(left.name);
599 const r = rank(right.name);
600 return (l === -1 ? 99 : l) - (r === -1 ? 99 : r);
601 });
602 for (const remote of candidates) {
603 const [owner, name, ...rest] = normalizeGitRemoteUrl(remote.url).split("/").slice(1);
604 if (owner && name && rest.length === 0) return { host, owner, name };
605 }
606 return yield* commandFailure(
607 input.cwd,
608 `No GitHub repository on ${host} was found among this checkout's git remotes.`,
609 );
610 });
611
612 const graphqlJson = <A>(
613 cwd: string,
614 input: GitHubApi.GitHubGraphQlInput,
615 decode: (raw: string) => Result.Result<A, unknown>,
616 onDecodeFailure: (cause: unknown) => GitHubCliError,
617 ) =>
618 api.graphql(input).pipe(
619 Effect.mapError((error) => fromGitHubApiError(cwd, error)),
620 Effect.flatMap((raw) => {
621 const decoded = decode(raw);
622 return Result.isSuccess(decoded)
623 ? Effect.succeed(decoded.success)
624 : Effect.fail(onDecodeFailure(decoded.failure));
625 }),
626 );
627
628 const rest = (cwd: string, input: GitHubApi.GitHubRestInput) =>
629 api.rest(input).pipe(Effect.mapError((error) => fromGitHubApiError(cwd, error)));
630
631 /** Pull requests whose head branch is `headRefName` on one repository. */
632 const readPullRequestsByHead = (input: {
633 readonly cwd: string;
634 readonly locator: GitHubRepositoryLocator;
635 readonly lookups: ReadonlyArray<
636 Pick<PullRequestsByHeadRead, "headRefName" | "state" | "limit">
637 >;
638 readonly allowReserve: boolean;
639 readonly onDecodeFailure: (cause: unknown) => GitHubCliError;
640 }) => {
641 const query = buildPullRequestsByHeadQuery(input.lookups);
642 return graphqlJson(
643 input.cwd,
644 {
645 host: input.locator.host,
646 operation: "listPullRequestsByHead",
647 query: query.document,
648 variables: { owner: input.locator.owner, name: input.locator.name, ...query.variables },
649 allowReserve: input.allowReserve,
650 // Up to 50 heads of 100 rows each. A default branch such as `main` can match a hundred
651 // fork pull requests, so the usual cap would cut the answer short.
652 maxResponseBytes: HEAD_LOOKUP_MAX_RESPONSE_BYTES,
653 },
654 decodePullRequestsByHead,
655 input.onDecodeFailure,
656 ).pipe(
657 Effect.flatMap((decoded) =>
658 decoded.data.repository === null
659 ? Effect.fail(
660 new GitHubPullRequestNotFoundError({
661 command: "gh",
662 cwd: input.cwd,
663 cause: new Error("The repository could not be read."),
664 }),
665 )
666 : Effect.succeed(decoded.data.repository),
667 ),
668 );
669 };
670
671 const headResolver = RequestResolver.makeGrouped<PullRequestsByHeadRead, string>({
672 key: ({ request, context }) =>
673 [
674 request.host,
675 request.owner,
676 request.name,
677 String(request.allowReserve),
678 Context.getOrElse(context, GitHubApi.PinnedGitHubCredential, () => null)
679 ?.credentialFingerprint ?? "",
680 Context.getOrElse(context, SourceControlRateLimit.CredentialScope, () => ""),
681 ].join("\0"),
682 resolver: (entries) => {
683 const [first] = entries;
684 const { cwd, host, owner, name, allowReserve } = first.request;
685 return readPullRequestsByHead({
686 cwd,
687 locator: { host, owner, name },
688 lookups: entries.map((entry) => entry.request),
689 allowReserve,
690 onDecodeFailure: (cause) =>
691 new GitHubChangeRequestListDecodeError({ command: "gh", cwd, cause }),
692 }).pipe(
693 Effect.map((aliases) => {
694 for (const [index, entry] of entries.entries()) {
695 const alias = aliases[`h${index}`];
696 entry.completeUnsafe(
697 Exit.succeed(alias == null ? [] : decodeGitHubPullRequestEntries(alias.nodes)),
698 );
699 }
700 }),
701 Effect.catchCause((cause) =>
702 Effect.sync(() => {
703 for (const entry of entries) entry.completeUnsafe(Exit.failCause(cause));
704 }),
705 ),
706 );
707 },
708 }).pipe(
709 RequestResolver.setDelay(HEAD_LOOKUP_BATCH_WINDOW),
710 RequestResolver.batchN(HEAD_LOOKUPS_PER_DOCUMENT),
711 );
712
713 const listByHead = Effect.fn("GitHubCli.listByHead")(function* (input: {
714 readonly cwd: string;
715 readonly headSelector: string;
716 readonly state: PullRequestListState;
717 readonly limit: number;
718 readonly rateLimitHost?: string | undefined;
719 readonly allowReserve: boolean;
720 }) {
721 const locator = yield* resolveRepository({ cwd: input.cwd, host: input.rateLimitHost });
722 const limit = Math.min(Math.max(Math.trunc(input.limit), 1), 100);
723 // `owner:branch` names a fork's branch. GitHub filters on the branch name only, so the
724 // owner is matched on the rows it returns.
725 const ownerMatch = /^([^:/\s]+):(.+)$/u.exec(input.headSelector.trim());
726 const headRefName = ownerMatch?.[2] ?? input.headSelector.trim();
727 const rows = yield* Effect.request(
728 new PullRequestsByHeadRead({
729 cwd: input.cwd,
730 ...locator,
731 headRefName,
732 state: input.state,
733 limit: ownerMatch ? OWNER_HEAD_SCAN_LIMIT : limit,
734 allowReserve: input.allowReserve,
735 }),
736 headResolver,
737 );
738 if (!ownerMatch) return rows;
739 const headOwner = ownerMatch[1]!.toLowerCase();
740 return rows
741 .filter((row) => row.headRepositoryOwnerLogin?.toLowerCase() === headOwner)
742 .slice(0, limit);
743 });
744
745 const toSummaries = (rows: ReadonlyArray<NormalizedGitHubPullRequestRecord>) =>
746 rows.map(pullRequestSummary);
747
748 const readPullRequest = Effect.fn("GitHubCli.readPullRequest")(function* (input: {
749 readonly cwd: string;
750 readonly reference: string;
751 readonly rateLimitHost?: string | undefined;
752 }) {
753 const parsed = parsePullRequestReference(input.reference);
754 if (parsed.kind === "branch") {
755 // `gh pr view <branch>` prefers an open pull request, then the newest of any state.
756 const [open] = yield* listByHead({
757 cwd: input.cwd,
758 headSelector: parsed.headSelector,
759 state: "open",
760 limit: 1,
761 rateLimitHost: input.rateLimitHost,
762 allowReserve: true,
763 });
764 const found =
765 open ??
766 (yield* listByHead({
767 cwd: input.cwd,
768 headSelector: parsed.headSelector,
769 state: "all",
770 limit: 1,
771 rateLimitHost: input.rateLimitHost,
772 allowReserve: true,
773 }))[0];
774 if (found === undefined) {
775 return yield* new GitHubPullRequestNotFoundError({
776 command: "gh",
777 cwd: input.cwd,
778 cause: new Error("No pull request has this head branch."),
779 });
780 }
781 return found;
782 }
783 const locator =
784 parsed.kind === "url"
785 ? parsed.locator
786 : yield* resolveRepository({ cwd: input.cwd, host: input.rateLimitHost });
787 const decodeFailure = (cause: unknown) =>
788 new GitHubPullRequestDecodeError({ command: "gh", cwd: input.cwd, cause });
789 const decoded = yield* graphqlJson(
790 input.cwd,
791 {
792 host: locator.host,
793 operation: "getPullRequest",
794 query: PULL_REQUEST_BY_NUMBER_QUERY,
795 variables: { owner: locator.owner, name: locator.name, number: parsed.number },
796 allowReserve: true,
797 },
798 decodePullRequestByNumber,
799 decodeFailure,
800 );
801 const node = decoded.data.repository?.pullRequest;
802 if (node == null) {
803 return yield* new GitHubPullRequestNotFoundError({
804 command: "gh",
805 cwd: input.cwd,
806 cause: new Error("The pull request does not exist."),
807 });
808 }
809 const [record] = decodeGitHubPullRequestEntries([node]);
810 if (record === undefined) return yield* decodeFailure(new Error("Malformed pull request."));
811 return record;
812 });
813
814 const readRepository = Effect.fn("GitHubCli.readRepository")(function* (
815 cwd: string,
816 locator: GitHubRepositoryLocator,
817 ) {
818 const response = yield* rest(cwd, {
819 host: locator.host,
820 operation: "getRepository",
821 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}`,
822 allowReserve: true,
823 });
824 const decoded = decodeRawRepository(response.body);
825 if (Result.isFailure(decoded)) {
826 return yield* new GitHubRepositoryDecodeError({
827 command: "gh",
828 cwd,
829 cause: decoded.failure,
830 });
831 }
832 return decoded.success;
833 });
834
835 const readViewerLogin = Effect.fn("GitHubCli.readViewerLogin")(function* (
836 cwd: string,
837 host: string,
838 ) {
839 const response = yield* rest(cwd, { host, operation: "getViewer", path: "user" });
840 const decoded = decodeViewerLogin(response.body);
841 if (Result.isFailure(decoded)) {
842 return yield* new GitHubCliCommandError({ command: "gh", cwd, cause: decoded.failure });
843 }
844 return decoded.success.login;
845 });
846
847 const gitFailure = (cwd: string) => (cause: unknown) =>
848 new GitHubCliCommandError({ command: "gh", cwd, cause });
849
850 const runGit = (cwd: string, operation: string, args: ReadonlyArray<string>) =>
851 git.execute({ operation: `GitHubCli.checkoutPullRequest.${operation}`, cwd, args });
852
853 /**
854 * `gh pr checkout` in plain git: the head branch is fetched from the remote that holds it (a
855 * fork gets a remote of its own), checked out under the name gh would give it, and set to
856 * track the head. A head branch that is gone is read from the base's `refs/pull/<n>/head`.
857 * An existing branch fast-forwards, or with `force` is reset to the pull request.
858 */
859 const checkoutPullRequest: GitHubCli["Service"]["checkoutPullRequest"] = Effect.fn(
860 "GitHubCli.checkoutPullRequest",
861 )(function* (input) {
862 const reference = parsePullRequestReference(input.reference);
863 const pullRequest = yield* readPullRequest({ cwd: input.cwd, reference: input.reference });
864 const base =
865 reference.kind === "url" ? reference.locator : yield* resolveRepository({ cwd: input.cwd });
866 const baseNameWithOwner = `${base.owner}/${base.name}`.toLowerCase();
867 const headNameWithOwner = pullRequest.headRepositoryNameWithOwner ?? null;
868 const isCrossRepository =
869 pullRequest.isCrossRepository ??
870 (headNameWithOwner !== null && headNameWithOwner.toLowerCase() !== baseNameWithOwner);
871 const headOwner =
872 pullRequest.headRepositoryOwnerLogin ?? headNameWithOwner?.split("/")[0] ?? null;
873
874 const remotes = yield* gitRead(input.cwd, ["remote", "-v"]).pipe(
875 Effect.map((result) => (result.exitCode === 0 ? result.stdout : "")),
876 Effect.mapError(gitFailure(input.cwd)),
877 );
878 const remoteFor = (nameWithOwner: string) =>
879 remotes
880 .split("\n")
881 .map((line) => /^(\S+)\s+(\S+)\s+\(fetch\)$/u.exec(line.trim()))
882 .find(
883 (match) =>
884 match !== null &&
885 normalizeGitRemoteUrl(match[2]!).split("/").slice(1).join("/") ===
886 nameWithOwner.toLowerCase(),
887 )?.[1] ?? null;
888 const baseRemote = Effect.suspend(() => {
889 const known = remoteFor(baseNameWithOwner);
890 return known === null ? git.resolvePrimaryRemoteName(input.cwd) : Effect.succeed(known);
891 });
892 // A fork's branch named like the base's default branch is checked out under the owner's
893 // prefix. Without the default branch that collision cannot be ruled out, and the checkout
894 // would reset the local default branch to the fork's commit, so it fails instead.
895 const defaultBranch = isCrossRepository
896 ? yield* readRepository(input.cwd, base).pipe(
897 Effect.map((repository) => repository.default_branch ?? null),
898 )
899 : null;
900 const localBranch = pullRequestCheckoutBranchName({
901 headRefName: pullRequest.headRefName,
902 headOwner,
903 isCrossRepository,
904 defaultBranch,
905 });
906
907 /** The remote the head branch lives on; a fork the checkout does not know yet is added. */
908 const headRemote = Effect.gen(function* () {
909 if (!isCrossRepository) return yield* baseRemote;
910 if (headNameWithOwner === null) return yield* commandFailure(input.cwd, "The fork is gone.");
911 const known = remoteFor(headNameWithOwner);
912 if (known !== null) return known;
913 const [owner, name] = headNameWithOwner.split("/");
914 const fork = yield* readRepository(input.cwd, {
915 host: base.host,
916 owner: owner!,
917 name: name!,
918 });
919 const originUrl = yield* git.readConfigValue(input.cwd, "remote.origin.url");
920 return yield* git.ensureRemote({
921 cwd: input.cwd,
922 preferredName: headOwner ?? "fork",
923 url: originUrl !== null && isSshRemoteUrl(originUrl) ? fork.ssh_url : fork.html_url,
924 });
925 });
926
927 const exists = (yield* git
928 .listLocalBranchNames(input.cwd)
929 .pipe(Effect.mapError(gitFailure(input.cwd)))).includes(localBranch);
930
931 // The commit to check out, fetched from the head branch where it still exists.
932 const target = yield* Effect.gen(function* () {
933 const remoteName = yield* headRemote;
934 yield* git.fetchRemoteTrackingBranch({
935 cwd: input.cwd,
936 remoteName,
937 remoteBranch: pullRequest.headRefName,
938 });
939 return {
940 ref: `refs/remotes/${remoteName}/${pullRequest.headRefName}`,
941 upstream: { remoteName, remoteBranch: pullRequest.headRefName },
942 };
943 }).pipe(
944 Effect.catch(() =>
945 Effect.gen(function* () {
946 yield* runGit(input.cwd, "fetchPullRef", [
947 "fetch",
948 "--quiet",
949 "--no-tags",
950 yield* baseRemote,
951 `refs/pull/${pullRequest.number}/head`,
952 ]);
953 const { commitSha } = yield* git.resolveCommit({
954 cwd: input.cwd,
955 revision: "FETCH_HEAD",
956 });
957 return { ref: commitSha, upstream: null };
958 }),
959 ),
960 Effect.mapError(gitFailure(input.cwd)),
961 );
962
963 yield* Effect.gen(function* () {
964 if (!exists) yield* runGit(input.cwd, "branch", ["branch", localBranch, target.ref]);
965 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
966 if (exists) {
967 yield* runGit(
968 input.cwd,
969 "sync",
970 input.force === true
971 ? ["reset", "--hard", "--quiet", target.ref]
972 : ["merge", "--ff-only", "--quiet", target.ref],
973 );
974 }
975 // Tracking is set once the branch is the pull request's, so a sync that fails leaves an
976 // existing branch's upstream as it was.
977 if (target.upstream !== null) {
978 yield* git.setBranchUpstream({ cwd: input.cwd, branch: localBranch, ...target.upstream });
979 }
980 }).pipe(Effect.mapError(gitFailure(input.cwd)));
981 });
982
983 return GitHubCli.of({
984 listPullRequestsByHead: (input) =>
985 AllowGitHubReserve.pipe(
986 Effect.flatMap((allowReserve) => listByHead({ ...input, allowReserve })),
987 ),
988 listOpenPullRequests: (input) =>
989 listByHead({
990 cwd: input.cwd,
991 headSelector: input.headSelector,
992 state: "open",
993 limit: input.limit ?? 1,
994 rateLimitHost: input.rateLimitHost,
995 allowReserve: true,
996 }).pipe(Effect.map(toSummaries)),
997 getPullRequest: (input) => readPullRequest(input).pipe(Effect.map(pullRequestSummary)),
998 getRepositoryCloneUrls: (input) =>
999 Effect.gen(function* () {
1000 const fallbackHost = (yield* resolveRepository({ cwd: input.cwd }).pipe(
1001 Effect.map((locator) => locator.host),
1002 Effect.orElseSucceed(() => environment.GH_HOST ?? "github.com"),
1003 )).toLowerCase();
1004 const locator = parseGitHubRepositorySelector(input.repository, fallbackHost);
1005 if (locator === null) {
1006 return yield* commandFailure(input.cwd, "Repositories are named owner/name.");
1007 }
1008 return repositoryCloneUrls(yield* readRepository(input.cwd, locator));
1009 }),
1010 createRepository: (input) =>
1011 Effect.gen(function* () {
1012 const locator = parseGitHubRepositorySelector(
1013 input.repository,
1014 (environment.GH_HOST ?? "github.com").toLowerCase(),
1015 );
1016 const viewer = locator === null ? null : yield* readViewerLogin(input.cwd, locator.host);
1017 const owner = locator?.owner ?? viewer;
1018 const name = locator?.name ?? input.repository.trim();
1019 const host = locator?.host ?? (environment.GH_HOST?.trim().toLowerCase() || "github.com");
1020 const isViewer = viewer !== null && owner?.toLowerCase() === viewer.toLowerCase();
1021 const response = yield* rest(input.cwd, {
1022 host,
1023 operation: "createRepository",
1024 method: "POST",
1025 path:
1026 isViewer || owner === null ? "user/repos" : `orgs/${encodeURIComponent(owner)}/repos`,
1027 body: { name, private: input.visibility === "private" },
1028 });
1029 const decoded = decodeRawRepository(response.body);
1030 if (Result.isFailure(decoded)) {
1031 return yield* new GitHubRepositoryDecodeError({
1032 command: "gh",
1033 cwd: input.cwd,
1034 cause: decoded.failure,
1035 });
1036 }
1037 return repositoryCloneUrls(decoded.success);
1038 }),
1039 createPullRequest: (input) =>
1040 Effect.gen(function* () {
1041 const locator = yield* resolveRepository({ cwd: input.cwd });
1042 const body = yield* fileSystem
1043 .readFileString(input.bodyFile)
1044 .pipe(Effect.mapError(gitFailure(input.cwd)));
1045 yield* rest(input.cwd, {
1046 host: locator.host,
1047 operation: "createPullRequest",
1048 method: "POST",
1049 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}/pulls`,
1050 // `owner:branch` is how the REST API takes a fork's head, the same as `gh --head`.
1051 // gh allows maintainer edits unless told otherwise; the API's default is not documented.
1052 body: {
1053 base: input.baseBranch,
1054 head: input.headSelector,
1055 title: input.title,
1056 body,
1057 maintainer_can_modify: true,
1058 },
1059 });
1060 }),
1061 getDefaultBranch: (input) =>
1062 Effect.gen(function* () {
1063 const locator = yield* resolveRepository({ cwd: input.cwd, host: input.rateLimitHost });
1064 const repository = yield* readRepository(input.cwd, locator);
1065 const branch = repository.default_branch?.trim() ?? "";
1066 return branch.length > 0 ? branch : null;
1067 }),
1068 checkoutPullRequest,
1069 });
1070});
1071
1072export const layer = Layer.effect(GitHubCli, make).pipe(
1073 Layer.provideMerge(GitHubApi.layer),
1074 Layer.provideMerge(GitHubCredentials.layer),
1075 Layer.provideMerge(GitHubGraphQlBudget.layer),
1076 Layer.provideMerge(SourceControlRateLimit.layer),
1077);