Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import * as Data from "effect/Data";
3import * as DateTime from "effect/DateTime";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import {
7 GraphQL,
8 GraphQLClient,
9 GraphQLClientError,
10 GraphQLGroup,
11 GraphQLResolver,
12} from "effect/graphql";
13import * as Option from "effect/Option";
14import * as RequestResolver from "effect/RequestResolver";
15import * as Result from "effect/Result";
16import * as Schema from "effect/Schema";
17import {
18 SourceControlProviderError,
19 TrimmedNonEmptyString,
20 type ChangeRequest,
21 type SourceControlProviderDiscoveryItem,
22 type SourceControlRepositoryCloneUrls,
23} from "@t3tools/contracts";
24import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
25import * as HostProcess from "@t3tools/shared/HostProcess";
26import { decodeJsonResult } from "@t3tools/shared/schemaJson";
27import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
28
29import * as GitHubRest from "./GitHubRest.ts";
30import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
31import * as GitHubChangeRequestTemplate from "./gitHubChangeRequestTemplate.ts";
32import * as GitHubGraphQlClient from "./gitHubGraphQlClient.ts";
33import {
34 normalizeGitHubPullRequestRecord,
35 type NormalizedGitHubPullRequestRecord,
36} from "./gitHubPullRequests.ts";
37import {
38 gitHubApiHostForRemote,
39 parseFetchRemotes,
40 parseGitHubRepositorySelector,
41 parsePullRequestReference,
42 resolveGitHubRepository,
43 type GitHubRepositoryLocator,
44} from "./gitHubRepositoryResolution.ts";
45import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
46import {
47 effectiveGitHubAccount,
48 findAuthenticatedGitHubAccount,
49 parseGitHubAuthStatus,
50 type GitHubAuthStatusAccount,
51} from "./gitHubAuthStatus.ts";
52import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
53import {
54 combinedAuthOutput,
55 firstSafeAuthLine,
56 probeSourceControlProvider,
57 providerAuth,
58 type SourceControlAuthProbeInput,
59 type SourceControlCliDiscoverySpec,
60 type SourceControlManagedCliDiscoverySpec,
61} from "@t3tools/source-control-core/server/discovery";
62import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
63import { readSourceControlHostSettings } from "@t3tools/source-control-core/client/definition";
64
65import * as GitHubClient from "../client/definition.ts";
66import {
67 PullRequestByNumber,
68 PullRequestNode,
69 PullRequestsByHead,
70} from "./sourceControlProvider.graphql.ts";
71
72/**
73 * The generated head lookup with its rows left undecoded, so `listByHead` decodes them one at a
74 * time: a row whose fields no longer decode is skipped rather than failing every lookup that
75 * shared its document.
76 */
77const LenientPullRequestsByHead = GraphQL.query(PullRequestsByHead.name, {
78 // The template, not the joined text: `GraphQLResolver.aliased` repeats it per lookup.
79 document: PullRequestsByHead.template!,
80 variables: PullRequestsByHead.variables,
81 result: Schema.Struct({
82 repository: Schema.NullOr(
83 Schema.Struct({
84 pullRequests: Schema.Struct({ nodes: Schema.NullOr(Schema.Array(Schema.Unknown)) }),
85 }),
86 ),
87 }),
88});
89const decodePullRequestNode = Schema.decodeUnknownOption(PullRequestNode);
90
91const decodeLinkSubject = Schema.decodeUnknownEffect(
92 Schema.fromJsonString(
93 Schema.Struct({ title: Schema.String, body: Schema.optional(Schema.NullOr(Schema.String)) }),
94 ),
95);
96
97function toChangeRequest(record: NormalizedGitHubPullRequestRecord): ChangeRequest {
98 return { provider: SourceControlProviderKind.make("github"), ...record };
99}
100
101function authAccounts(accounts: ReadonlyArray<GitHubAuthStatusAccount>) {
102 return accounts.map((entry) => ({
103 host: entry.host,
104 account: entry.account,
105 active: entry.active,
106 authenticated: entry.authenticated,
107 ...(entry.error === null ? {} : { error: entry.error }),
108 ...(entry.environmentVariable === null
109 ? {}
110 : { environmentVariable: entry.environmentVariable }),
111 }));
112}
113
114/**
115 * Reads `gh auth status --json hosts`. The headline account is the one GitHub requests will
116 * use: Settings can pin a login per host or turn a host off, and an environment token beats both.
117 */
118export function parseGitHubAuth(
119 input: SourceControlAuthProbeInput,
120 settings: GitHubClient.GitHubSettings = readSourceControlHostSettings(GitHubClient.settings, {}),
121) {
122 const output = combinedAuthOutput(input);
123 const authStatus = parseGitHubAuthStatus(input.stdout);
124 const hosts = [...new Set(authStatus.accounts.map((entry) => entry.host))];
125 const fallback = findAuthenticatedGitHubAccount(authStatus.accounts);
126 // Lead with the host gh would pick, unless Settings turned it off.
127 const orderedHosts = fallback
128 ? [fallback.host, ...hosts.filter((host) => host !== fallback.host)]
129 : hosts;
130 const chosen = orderedHosts
131 .map((host) => effectiveGitHubAccount(host, authStatus.accounts, settings))
132 .find((entry) => entry !== undefined);
133 const accounts = authStatus.parsed ? { accounts: authAccounts(authStatus.accounts) } : {};
134
135 if (chosen) {
136 return {
137 ...providerAuth({
138 status: "authenticated",
139 account: chosen.account,
140 host: chosen.host,
141 detail:
142 chosen.environmentVariable === null
143 ? undefined
144 : `Using ${chosen.environmentVariable} from the server environment; it overrides the account chosen in Settings.`,
145 }),
146 ...accounts,
147 };
148 }
149
150 if (fallback) {
151 return {
152 ...providerAuth({
153 status: "unauthenticated",
154 host: fallback.host,
155 detail: "Every GitHub host gh is signed in to is turned off in Settings → Source Control.",
156 }),
157 ...accounts,
158 };
159 }
160
161 const failedAccount = authStatus.accounts.find((entry) => entry.active) ?? authStatus.accounts[0];
162 if (authStatus.parsed) {
163 return {
164 ...providerAuth({
165 status: "unauthenticated",
166 host: failedAccount?.host,
167 detail:
168 failedAccount?.error ??
169 "Run `gh auth login` to authenticate GitHub CLI with an active account.",
170 }),
171 ...accounts,
172 };
173 }
174
175 // gh gained `auth status --json` in 2.81.0. Older versions reject the flag and exit
176 // non-zero, which reads exactly like a signed-out CLI. Name the real problem instead.
177 if (input.exitCode !== 0 && output.includes("unknown flag: --json")) {
178 return providerAuth({
179 status: "unknown",
180 detail:
181 "GitHub CLI is too old to report sign-in status. Update `gh` to 2.81.0 or newer (for example `brew upgrade gh`) and rescan.",
182 });
183 }
184
185 if (input.exitCode !== 0) {
186 return providerAuth({
187 status: "unauthenticated",
188 detail: firstSafeAuthLine(output) ?? "Run `gh auth login` to authenticate GitHub CLI.",
189 });
190 }
191
192 return providerAuth({
193 status: "unknown",
194 detail: firstSafeAuthLine(output) ?? "GitHub CLI auth status could not be parsed.",
195 });
196}
197
198export const discovery = {
199 type: "cli",
200 kind: SourceControlProviderKind.make("github"),
201 label: "GitHub",
202 executable: "gh",
203 versionArgs: ["--version"],
204 authArgs: ["auth", "status", "--json", "hosts"],
205 parseAuth: parseGitHubAuth,
206 installHint:
207 "Install the GitHub command-line tool (`gh`) via https://cli.github.com/ or your package manager (for example `brew install gh`).",
208} satisfies SourceControlCliDiscoverySpec;
209
210const decodeViewer = Schema.decodeUnknownOption(
211 Schema.fromJsonString(Schema.Struct({ login: Schema.String })),
212);
213
214/** The environment variable gh would take a github.com token from, if one is set. */
215function environmentTokenVariable(environment: NodeJS.ProcessEnv): string | null {
216 return ["GH_TOKEN", "GITHUB_TOKEN"].find((name) => environment[name]?.trim()) ?? null;
217}
218
219/**
220 * GitHub is usable with a token saved in Settings, one from the environment, or `gh` to hand one
221 * over. Reads the
222 * GitHub settings on every probe, so a saved account choice shows on rescan. An environment
223 * token is checked against the API, since `gh auth status` may not know it.
224 */
225export const makeDiscovery = Effect.gen(function* () {
226 const api = yield* GitHubRest.GitHubRest;
227 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
228 const process = sourceControlHost.process;
229 const environment = yield* HostProcess.Environment;
230
231 return {
232 type: "managed-cli",
233 kind: discovery.kind,
234 label: discovery.label,
235 installHint: discovery.installHint,
236 probe: Effect.fn("GitHubSourceControlProvider.discovery")(function* (cwd: string) {
237 const settings = readSourceControlHostSettings(
238 GitHubClient.settings,
239 yield* sourceControlHost.settings.get.pipe(
240 Effect.map((current) => current.sourceControlHosts[GitHubClient.definition.kind]),
241 Effect.orElseSucceed(() => undefined),
242 ),
243 );
244 const cli = yield* probeSourceControlProvider({
245 cwd,
246 process,
247 spec: { ...discovery, parseAuth: (input) => parseGitHubAuth(input, settings) },
248 });
249 // A token saved in Settings wins over the environment, which wins over gh.
250 const savedToken = (settings.tokens["github.com"] ?? "").trim() !== "";
251 const variable = environmentTokenVariable(environment);
252 const tokenSource = savedToken ? "the token saved in Settings" : variable;
253 // A host turned off in Settings stays off even with a token.
254 if (tokenSource === null || settings.hosts["github.com"]?.enabled === false) return cli;
255 const viewer = yield* api
256 .rest({ host: "github.com", operation: "discovery", path: "user" })
257 .pipe(Effect.result);
258 const login = Result.isSuccess(viewer)
259 ? Option.getOrUndefined(decodeViewer(viewer.success.body))?.login
260 : undefined;
261 // The per-host logins stay, so the account picker still lists every host gh knows.
262 const accounts = cli.auth.accounts === undefined ? {} : { accounts: cli.auth.accounts };
263 return {
264 ...cli,
265 status: "available" as const,
266 auth: {
267 ...(login !== undefined
268 ? providerAuth({
269 status: "authenticated",
270 account: login,
271 host: "github.com",
272 detail: savedToken
273 ? "Using the token saved in Settings; it overrides GH_TOKEN and the gh login."
274 : `Using ${variable} from the server environment; it overrides the account chosen in Settings.`,
275 })
276 : Result.isFailure(viewer) && viewer.failure._tag !== "GitHubApiAuthenticationError"
277 ? // Only a refusal says the token is bad; a network error or a pause says nothing.
278 providerAuth({
279 status: "unknown",
280 host: "github.com",
281 detail: `Could not check ${savedToken ? tokenSource : `the token in ${tokenSource}`}: ${viewer.failure.message}`,
282 })
283 : providerAuth({
284 status: "unauthenticated",
285 host: "github.com",
286 detail: savedToken
287 ? "GitHub refused the token saved in Settings. Replace or remove it in Settings → Source Control."
288 : `GitHub refused the token in ${tokenSource}. Replace it, or unset it to use \`gh auth login\`.`,
289 })),
290 ...accounts,
291 },
292 } satisfies SourceControlProviderDiscoveryItem;
293 }),
294 /**
295 * Claims a custom host GitHub holds a credential for, from whichever source supplies it
296 * (Settings, the environment or gh). A host turned off in Settings is claimed too, so its
297 * error says so instead of "unsupported host".
298 */
299 refineUnknownRemote: ({ context }) => {
300 // Identity resolution also probes providers before a web base URL is known.
301 const url = URL.parse(context.provider.baseUrl);
302 if (!url?.host) return Effect.succeed(null);
303 // A timeout or keyring failure propagates: the registry does not keep that answer.
304 return api.credential(url.host).pipe(
305 Effect.as(true),
306 Effect.catchTags({
307 GitHubCliMissingError: () => Effect.succeed(false),
308 GitHubHostDisabledError: () => Effect.succeed(true),
309 GitHubNotSignedInError: () => Effect.succeed(false),
310 }),
311 Effect.map((known) =>
312 known
313 ? ({
314 kind: SourceControlProviderKind.make("github"),
315 name: "GitHub Self-Hosted",
316 baseUrl: context.provider.baseUrl,
317 } as const)
318 : null,
319 ),
320 );
321 },
322 } satisfies SourceControlManagedCliDiscoverySpec;
323});
324
325/**
326 * Why a GitHub read or write failed, in words a user can act on. The provider methods attach the
327 * operation and request context; `cause` keeps the raw failure for logs, never for transport.
328 */
329class GitHubFailure extends Data.TaggedError("GitHubFailure")<{
330 readonly detail: string;
331 readonly cause: unknown;
332}> {}
333
334const failure = (detail: string, cause?: unknown) => new GitHubFailure({ detail, cause });
335
336const PULL_REQUEST_NOT_FOUND = "Pull request not found. Check the PR number or URL and try again.";
337const REPOSITORY_NOT_FOUND = "Repository not found. Check the owner and name and try again.";
338
339/** `notFound` names what was missing, which only the operation knows. */
340function fromGitHubApiError(
341 error: GitHubRequestPolicy.GitHubApiError,
342 notFound = PULL_REQUEST_NOT_FOUND,
343): GitHubFailure {
344 switch (error._tag) {
345 case "GitHubCliMissingError":
346 return failure(
347 "No GitHub credential on the server. Set GH_TOKEN, or install the GitHub CLI and run `gh auth login`.",
348 error,
349 );
350 case "GitHubNotSignedInError":
351 case "GitHubHostDisabledError":
352 // A missing or turned-off credential already says what to do about it.
353 return failure(error.message, error);
354 case "GitHubApiAuthenticationError":
355 return failure(
356 "GitHub is not authenticated. Run `gh auth login` (or set GH_TOKEN) and retry.",
357 error,
358 );
359 case "GitHubApiRateLimitError":
360 case "SourceControlRateLimitPausedError":
361 return failure(
362 "GitHub API rate limit exceeded. Requests resume when the limit resets.",
363 error,
364 );
365 case "GitHubApiNotFoundError":
366 return failure(notFound, error);
367 case "GitHubCliFailedError":
368 case "GitHubApiResponseError":
369 case "GitHubApiRequestError":
370 // GitHub's own reason ("A pull request already exists…") when it gave one.
371 return failure(error.message.trim() || "GitHub request failed.", error);
372 }
373}
374
375const notFound = (cause: string) => failure(PULL_REQUEST_NOT_FOUND, new Error(cause));
376
377const RawRepositorySchema = Schema.Struct({
378 full_name: TrimmedNonEmptyString,
379 html_url: TrimmedNonEmptyString,
380 ssh_url: TrimmedNonEmptyString,
381 default_branch: Schema.optional(Schema.NullOr(Schema.String)),
382});
383const decodeRawRepository = decodeJsonResult(RawRepositorySchema);
384
385function repositoryCloneUrls(
386 raw: Schema.Schema.Type<typeof RawRepositorySchema>,
387): SourceControlRepositoryCloneUrls {
388 return { nameWithOwner: raw.full_name, url: raw.html_url, sshUrl: raw.ssh_url };
389}
390
391const decodeViewerLogin = decodeJsonResult(Schema.Struct({ login: TrimmedNonEmptyString }));
392
393type PullRequestListState = "open" | "closed" | "merged" | "all";
394
395const GRAPHQL_STATES: Record<
396 PullRequestListState,
397 NonNullable<PullRequestsByHead.Variables["states"]>
398> = {
399 open: ["OPEN"],
400 closed: ["CLOSED"],
401 merged: ["MERGED"],
402 all: ["OPEN", "CLOSED", "MERGED"],
403};
404/**
405 * Head lookups per GraphQL document. A document of a hundred costs one point, the same as one
406 * single lookup, but half that keeps each answer near half a second.
407 */
408const HEAD_LOOKUPS_PER_DOCUMENT = 50;
409/**
410 * How long a head lookup waits for company. Branch discovery reaches GitHub only after each
411 * branch's own git reads, so lookups started together arrive tens of milliseconds apart.
412 * A background sweep's lookups spread over up to ~300ms, and every document costs a point no
413 * matter how few heads it holds, so reads without reserve wait longer.
414 */
415const HEAD_LOOKUP_BATCH_WINDOW = "50 millis";
416const BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW = "500 millis";
417/**
418 * Background documents fill up under the longer window, and a failed document fails every head
419 * in it. Fifty `main`-like heads of a hundred pull requests each took up to ~10s, GitHub's own
420 * processing limit; twenty-five took ~7s.
421 */
422const BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT = 25;
423/** A full document is 5,000 rows of well under 2 KB each. */
424const HEAD_LOOKUP_MAX_RESPONSE_BYTES = 16_000_000;
425/**
426 * Rows read for a fork's `owner:branch` head, which GitHub cannot filter by owner. A branch
427 * named like a busy default (`main`) is the case this bounds; the owner's own row is near the
428 * top because the newest come first.
429 */
430const OWNER_HEAD_SCAN_LIMIT = 100;
431
432function trimmed(value: string): string | null {
433 const text = value.trim();
434 return text.length > 0 ? text : null;
435}
436
437/**
438 * A pull request as every read reports it, or null for a row this cannot use: a number below
439 * one, a blank title, URL or branch name, or an `updatedAt` that is not a date. A list skips a
440 * null, so one such row cannot hide the rest. The generated schema already holds every row to
441 * GitHub's own types, with `state` as a lenient enum.
442 */
443function toPullRequestRecord(node: PullRequestNode): NormalizedGitHubPullRequestRecord | null {
444 const title = trimmed(node.title);
445 const url = trimmed(node.url);
446 const baseRefName = trimmed(node.baseRefName);
447 const headRefName = trimmed(node.headRefName);
448 const updatedAt = DateTime.make(node.updatedAt);
449 if (node.number < 1 || !title || !url || !baseRefName || !headRefName) return null;
450 if (Option.isNone(updatedAt)) return null;
451 return normalizeGitHubPullRequestRecord({
452 ...node,
453 title,
454 url,
455 baseRefName,
456 headRefName,
457 updatedAt: Option.some(DateTime.toUtc(updatedAt.value)),
458 });
459}
460
461/** The local branch a pull request checks out into, the way `gh pr checkout` names it. */
462export function pullRequestCheckoutBranchName(input: {
463 readonly headRefName: string;
464 readonly headOwner: string | null;
465 readonly isCrossRepository: boolean;
466 readonly defaultBranch: string | null;
467}): string {
468 // gh prefixes the owner only where the fork's branch would take over the default branch's
469 // name, which is the one collision every fork pull request from `main` would hit.
470 return input.isCrossRepository &&
471 input.headOwner !== null &&
472 input.defaultBranch !== null &&
473 input.headRefName === input.defaultBranch
474 ? `${input.headOwner}/${input.headRefName}`
475 : input.headRefName;
476}
477
478/** The checkout's GitHub API host, from the remote the caller resolved the provider from. */
479const contextHost = (context: SourceControlProvider.SourceControlProviderContext | undefined) =>
480 context === undefined ? undefined : new URL(context.provider.baseUrl).host;
481
482export const make = Effect.gen(function* () {
483 const api = yield* GitHubRest.GitHubRest;
484 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
485 const process = sourceControlHost.process;
486 const environment = yield* HostProcess.Environment;
487 const git = sourceControlHost.git;
488 const fileSystem = yield* FileSystem.FileSystem;
489
490 const gitRead = (cwd: string, args: ReadonlyArray<string>) =>
491 process.run({
492 operation: "GitHubSourceControlProvider.resolveRepository",
493 command: "git",
494 args,
495 cwd,
496 allowNonZeroExit: true,
497 timeoutMs: 5_000,
498 });
499
500 /**
501 * Uses GH_REPO, then gh's remote selection on the detected host. The provider context is
502 * a fallback when the checkout's remotes cannot resolve that repository.
503 */
504 const resolveRepository = Effect.fn("GitHubSourceControlProvider.resolveRepository")(
505 function* (input: {
506 readonly cwd: string;
507 readonly host?: string | undefined;
508 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
509 }) {
510 const envRepository = environment.GH_REPO?.trim();
511 const hostHint = input.host ?? contextHost(input.context);
512 const defaultHost = (hostHint ?? environment.GH_HOST ?? "github.com").toLowerCase();
513 if (envRepository) {
514 const locator = parseGitHubRepositorySelector(envRepository, defaultHost);
515 if (locator !== null) return locator;
516 }
517 const [remotes, resolved] = yield* Effect.all([
518 gitRead(input.cwd, ["remote", "-v"]),
519 gitRead(input.cwd, ["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"]),
520 ]).pipe(Effect.orElseSucceed(() => [null, null] as const));
521 const { host, locator } = resolveGitHubRepository({
522 remotes: remotes?.exitCode === 0 ? remotes.stdout : "",
523 resolved: resolved?.exitCode === 0 ? resolved.stdout : "",
524 hostHint,
525 defaultHost,
526 });
527 if (locator !== null) return locator;
528 if (input.context) {
529 const remote = normalizeGitRemoteUrl(input.context.remoteUrl);
530 const fallback = parseGitHubRepositorySelector(
531 `${host}/${remote.slice(remote.indexOf("/") + 1)}`,
532 host,
533 );
534 if (fallback !== null) return fallback;
535 }
536 return yield* failure(
537 `No GitHub repository on ${host} was found among this checkout's git remotes.`,
538 );
539 },
540 );
541
542 const client = yield* GraphQLClient.make(
543 GraphQLGroup.make(LenientPullRequestsByHead, PullRequestByNumber).middleware(
544 GitHubGraphQlClient.GitHubGraphQlAuth,
545 ),
546 ).pipe(Effect.provide(GitHubGraphQlClient.layer));
547
548 /**
549 * Runs a generated read against `target`. GitHub's refusals and `errors` fail the way REST
550 * ones do; an answer that does not decode is a `decodeDetail` failure.
551 */
552 const graphqlRead = <A, E, R>(
553 target: GitHubGraphQlClient.GitHubGraphQlTarget["Service"],
554 decodeDetail: string,
555 effect: Effect.Effect<A, E, R>,
556 ) =>
557 effect.pipe(
558 GitHubGraphQlClient.call(target),
559 Effect.mapError((error) =>
560 GraphQLClientError.isGraphQLClientError(error)
561 ? failure(decodeDetail, error)
562 : fromGitHubApiError(error as GitHubRequestPolicy.GitHubApiError),
563 ),
564 );
565
566 const rest = (input: GitHubRest.GitHubRestInput, notFoundDetail?: string) =>
567 api.rest(input).pipe(Effect.mapError((error) => fromGitHubApiError(error, notFoundDetail)));
568
569 /**
570 * Head lookups to one host under one credential share aliased documents: the resolver batches by
571 * the host's endpoint and `batchKey`. Each lookup has its own `repository` root, so lookups on
572 * different repositories may share a document, and a repository GitHub cannot find fails only
573 * its own. Interactive and background lookups never share one, since they use separate
574 * resolvers, so a document is sent under one reserve setting.
575 */
576 const headResolver = GraphQLResolver.aliased(client.PullRequestsByHead, {
577 batchKey: GitHubGraphQlClient.batchKey,
578 }).pipe(RequestResolver.batchN(HEAD_LOOKUPS_PER_DOCUMENT));
579 const interactiveHeadResolver = headResolver.pipe(
580 RequestResolver.setDelay(HEAD_LOOKUP_BATCH_WINDOW),
581 );
582 const backgroundHeadResolver = headResolver.pipe(
583 RequestResolver.batchN(BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT),
584 RequestResolver.setDelay(BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW),
585 );
586
587 /**
588 * Pull requests whose head is `headSelector` (a branch, or `owner:branch` for a fork), in the
589 * repository `gh pr list` would read in `cwd`. Lookups on one repository that arrive together
590 * share one GraphQL document.
591 */
592 const listByHead = Effect.fn("GitHubSourceControlProvider.listByHead")(function* (input: {
593 readonly cwd: string;
594 readonly headSelector: string;
595 readonly state: PullRequestListState;
596 readonly limit: number;
597 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
598 readonly host?: string | undefined;
599 readonly allowReserve: boolean;
600 }) {
601 const locator = yield* resolveRepository(input);
602 const limit = Math.min(Math.max(Math.trunc(input.limit), 1), 100);
603 // `owner:branch` names a fork's branch. GitHub filters on the branch name only, so the
604 // owner is matched on the rows it returns.
605 const ownerMatch = /^([^:/\s]+):(.+)$/u.exec(input.headSelector.trim());
606 const headRefName = ownerMatch?.[2] ?? input.headSelector.trim();
607 const result = yield* graphqlRead(
608 {
609 host: locator.host,
610 operation: "listPullRequestsByHead",
611 allowReserve: input.allowReserve,
612 // Up to 50 heads of 100 rows each. A default branch such as `main` can match a hundred
613 // fork pull requests, so the usual cap would cut the answer short.
614 maxResponseBytes: HEAD_LOOKUP_MAX_RESPONSE_BYTES,
615 },
616 "GitHub returned an invalid change request list.",
617 GraphQLResolver.request(
618 {
619 owner: locator.owner,
620 name: locator.name,
621 head: headRefName,
622 states: GRAPHQL_STATES[input.state],
623 first: ownerMatch ? OWNER_HEAD_SCAN_LIMIT : limit,
624 },
625 input.allowReserve ? interactiveHeadResolver : backgroundHeadResolver,
626 ),
627 );
628 if (result.repository === null) return yield* notFound("The repository could not be read.");
629 const rows = (result.repository.pullRequests.nodes ?? []).flatMap((entry) => {
630 const node = Option.getOrNull(decodePullRequestNode(entry));
631 const record = node === null ? null : toPullRequestRecord(node);
632 return record === null ? [] : [record];
633 });
634 if (!ownerMatch) return rows;
635 const headOwner = ownerMatch[1]!.toLowerCase();
636 return rows
637 .filter((row) => row.headRepositoryOwnerLogin?.toLowerCase() === headOwner)
638 .slice(0, limit);
639 });
640
641 const readPullRequest = Effect.fn("GitHubSourceControlProvider.readPullRequest")(
642 function* (input: {
643 readonly cwd: string;
644 readonly reference: string;
645 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
646 readonly host?: string | undefined;
647 }) {
648 const parsed = parsePullRequestReference(input.reference);
649 if (parsed.kind === "branch") {
650 // `gh pr view <branch>` prefers an open pull request, then the newest of any state.
651 const lookup = (state: PullRequestListState) =>
652 listByHead({
653 cwd: input.cwd,
654 headSelector: parsed.headSelector,
655 state,
656 limit: 1,
657 host: input.host,
658 context: input.context,
659 allowReserve: true,
660 });
661 const [open] = yield* lookup("open");
662 const found = open ?? (yield* lookup("all"))[0];
663 if (found === undefined) return yield* notFound("No pull request has this head branch.");
664 return found;
665 }
666 const locator = parsed.kind === "url" ? parsed.locator : yield* resolveRepository(input);
667 const decodeDetail = "GitHub returned an invalid pull request.";
668 const result = yield* graphqlRead(
669 { host: locator.host, operation: "getPullRequest", allowReserve: true },
670 decodeDetail,
671 client.PullRequestByNumber({
672 owner: locator.owner,
673 name: locator.name,
674 number: parsed.number,
675 }),
676 );
677 const node = result.repository?.pullRequest;
678 if (node == null) return yield* notFound("The pull request does not exist.");
679 const record = toPullRequestRecord(node);
680 if (record === null)
681 return yield* failure(decodeDetail, new Error("Malformed pull request."));
682 return record;
683 },
684 );
685
686 const readRepository = Effect.fn("GitHubSourceControlProvider.readRepository")(function* (
687 locator: GitHubRepositoryLocator,
688 ) {
689 const response = yield* rest(
690 {
691 host: locator.host,
692 operation: "getRepository",
693 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}`,
694 allowReserve: true,
695 },
696 REPOSITORY_NOT_FOUND,
697 );
698 const decoded = decodeRawRepository(response.body);
699 if (Result.isFailure(decoded)) {
700 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
701 }
702 return decoded.success;
703 });
704
705 const readViewerLogin = Effect.fn("GitHubSourceControlProvider.readViewerLogin")(function* (
706 host: string,
707 ) {
708 const response = yield* rest({
709 host,
710 operation: "getViewer",
711 path: "user",
712 allowReserve: true,
713 });
714 const decoded = decodeViewerLogin(response.body);
715 if (Result.isFailure(decoded)) {
716 return yield* failure("GitHub request failed.", decoded.failure);
717 }
718 return decoded.success.login;
719 });
720
721 // Git and filesystem errors can carry arguments, paths and stderr, so the detail a client
722 // sees is fixed and the raw error stays in `cause`.
723 const gitFailure = (cause: unknown) =>
724 failure("The pull request could not be checked out with git.", cause);
725
726 const runGit = (cwd: string, operation: string, args: ReadonlyArray<string>) =>
727 git.execute({
728 operation: `GitHubSourceControlProvider.checkoutPullRequest.${operation}`,
729 cwd,
730 args,
731 });
732
733 /**
734 * `gh pr checkout` in plain git: the head branch is fetched from the remote that holds it (a
735 * fork gets a remote of its own), checked out under the name gh would give it, and set to
736 * track the head. A head branch that is gone is read from the base's `refs/pull/<n>/head`.
737 * An existing branch fast-forwards, or with `force` is reset to the pull request.
738 */
739 const checkoutPullRequest = Effect.fn("GitHubSourceControlProvider.checkoutPullRequest")(
740 function* (input: {
741 readonly cwd: string;
742 readonly reference: string;
743 readonly force?: boolean;
744 readonly context?: SourceControlProvider.SourceControlProviderContext;
745 }) {
746 const reference = parsePullRequestReference(input.reference);
747 const pullRequest = yield* readPullRequest(input);
748 const base = reference.kind === "url" ? reference.locator : yield* resolveRepository(input);
749 const baseNameWithOwner = `${base.owner}/${base.name}`.toLowerCase();
750 const headNameWithOwner = pullRequest.headRepositoryNameWithOwner ?? null;
751 const isCrossRepository =
752 pullRequest.isCrossRepository ??
753 (headNameWithOwner !== null && headNameWithOwner.toLowerCase() !== baseNameWithOwner);
754 const headOwner =
755 pullRequest.headRepositoryOwnerLogin ?? headNameWithOwner?.split("/")[0] ?? null;
756
757 const remotes = yield* gitRead(input.cwd, ["remote", "-v"]).pipe(
758 Effect.map((result) => (result.exitCode === 0 ? result.stdout : "")),
759 Effect.mapError(gitFailure),
760 );
761 const remoteFor = (nameWithOwner: string) =>
762 parseFetchRemotes(remotes).find(
763 (remote) =>
764 (gitHubApiHostForRemote(remote.url) ??
765 normalizeGitRemoteUrl(remote.url).split("/")[0]) === base.host &&
766 normalizeGitRemoteUrl(remote.url).split("/").slice(1).join("/") ===
767 nameWithOwner.toLowerCase(),
768 )?.name ?? null;
769 const baseRemote = Effect.suspend(() => {
770 const known = remoteFor(baseNameWithOwner);
771 return known === null ? git.resolvePrimaryRemoteName(input.cwd) : Effect.succeed(known);
772 });
773 // A fork's branch named like the base's default branch is checked out under the owner's
774 // prefix. Without the default branch that collision cannot be ruled out, and the checkout
775 // would reset the local default branch to the fork's commit, so it fails instead.
776 const defaultBranch = isCrossRepository
777 ? yield* readRepository(base).pipe(
778 Effect.map((repository) => repository.default_branch ?? null),
779 )
780 : null;
781 const localBranch = pullRequestCheckoutBranchName({
782 headRefName: pullRequest.headRefName,
783 headOwner,
784 isCrossRepository,
785 defaultBranch,
786 });
787
788 /** The remote the head branch lives on; a fork the checkout does not know yet is added. */
789 const headRemote = Effect.gen(function* () {
790 if (!isCrossRepository) return yield* baseRemote;
791 if (headNameWithOwner === null) return yield* failure("The fork is gone.");
792 const known = remoteFor(headNameWithOwner);
793 if (known !== null) return known;
794 const [owner, name] = headNameWithOwner.split("/");
795 const fork = yield* readRepository({ host: base.host, owner: owner!, name: name! });
796 const originUrl = yield* git.readConfigValue(input.cwd, "remote.origin.url");
797 return yield* git.ensureRemote({
798 cwd: input.cwd,
799 preferredName: headOwner ?? "fork",
800 url: originUrl !== null && isSshRemoteUrl(originUrl) ? fork.ssh_url : fork.html_url,
801 });
802 });
803
804 const exists = (yield* git
805 .listLocalBranchNames(input.cwd)
806 .pipe(Effect.mapError(gitFailure))).includes(localBranch);
807
808 // The commit to check out, fetched from the head branch where it still exists.
809 const target = yield* Effect.gen(function* () {
810 const remoteName = yield* headRemote;
811 yield* git.fetchRemoteTrackingBranch({
812 cwd: input.cwd,
813 remoteName,
814 remoteBranch: pullRequest.headRefName,
815 });
816 return {
817 ref: `refs/remotes/${remoteName}/${pullRequest.headRefName}`,
818 upstream: { remoteName, remoteBranch: pullRequest.headRefName },
819 };
820 }).pipe(
821 Effect.catch(() =>
822 Effect.gen(function* () {
823 yield* runGit(input.cwd, "fetchPullRef", [
824 "fetch",
825 "--quiet",
826 "--no-tags",
827 yield* baseRemote,
828 `refs/pull/${pullRequest.number}/head`,
829 ]);
830 const { commitSha } = yield* git.resolveCommit({
831 cwd: input.cwd,
832 revision: "FETCH_HEAD",
833 });
834 return { ref: commitSha, upstream: null };
835 }),
836 ),
837 Effect.mapError(gitFailure),
838 );
839
840 yield* Effect.gen(function* () {
841 if (!exists) yield* runGit(input.cwd, "branch", ["branch", localBranch, target.ref]);
842 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
843 if (exists) {
844 yield* runGit(
845 input.cwd,
846 "sync",
847 input.force === true
848 ? ["reset", "--hard", "--quiet", target.ref]
849 : ["merge", "--ff-only", "--quiet", target.ref],
850 );
851 }
852 // Tracking is set once the branch is the pull request's, so a sync that fails leaves an
853 // existing branch's upstream as it was.
854 if (target.upstream !== null) {
855 yield* git.setBranchUpstream({ cwd: input.cwd, branch: localBranch, ...target.upstream });
856 }
857 }).pipe(Effect.mapError(gitFailure));
858 },
859 );
860
861 /** Reports a failure against the operation and request that made it, with transport-safe context. */
862 const providerError =
863 (
864 operation: string,
865 cwd: string,
866 context?: { readonly reference?: string; readonly repository?: string },
867 ) =>
868 (error: GitHubFailure) =>
869 new SourceControlProviderError({
870 provider: SourceControlProviderKind.make("github"),
871 operation,
872 cwd,
873 ...(context?.reference === undefined
874 ? {}
875 : {
876 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
877 context.reference,
878 ),
879 }),
880 ...(context?.repository === undefined
881 ? {}
882 : {
883 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
884 context.repository,
885 ),
886 }),
887 detail: error.detail,
888 cause: error.cause,
889 });
890
891 const readLinkSubject = Effect.fn("GitHubSourceControlProvider.readLinkSubject")(function* (
892 input: { readonly cwd: string; readonly url: URL },
893 endpoint: string,
894 ) {
895 const result = yield* api
896 .rest({
897 host: input.url.host,
898 operation: "resolveLink",
899 path: endpoint,
900 maxResponseBytes: 1_000_000,
901 })
902 .pipe(
903 Effect.timeout("3 seconds"),
904 Effect.mapError(
905 (cause) =>
906 new SourceControlProviderError({
907 provider: SourceControlProviderKind.make("github"),
908 operation: "resolveLink",
909 cwd: input.cwd,
910 detail: "The linked subject could not be read.",
911 cause,
912 }),
913 ),
914 );
915 const subject = yield* decodeLinkSubject(result.body).pipe(
916 Effect.mapError(
917 (cause) =>
918 new SourceControlProviderError({
919 provider: SourceControlProviderKind.make("github"),
920 operation: "resolveLink.decode",
921 cwd: input.cwd,
922 detail: "The linked subject could not be read.",
923 cause,
924 }),
925 ),
926 );
927 return { title: subject.title, body: subject.body ?? null };
928 });
929
930 return SourceControlProvider.SourceControlProvider.of({
931 kind: SourceControlProviderKind.make("github"),
932 // `gh pr list --head` filters on the head ref name alone and accepts anything, so an
933 // `owner:branch` or `remote:branch` selector silently lists zero pull requests while
934 // spending a GraphQL call; the bare branch is always among the selectors. Without the owner,
935 // a bare branch also lists same-named branches on other forks (`main`, `patch-1`), so read a
936 // full page and let the owner check pick the right head. gh fetches up to 100 in one
937 // request, and GitHub prices a first:100 connection like first:1.
938 headBranchProbe: ({ headSelectors }) => ({
939 headSelectors: headSelectors.filter((selector) => !selector.includes(":")),
940 limit: 100,
941 }),
942 readChangeRequestTemplate: ({ cwd, treeish }) =>
943 GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute),
944 resolveLink: (input) => {
945 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
946 if (input.url.host !== "github.com") return undefined;
947 const match = /^\/([\w.-]+)\/([\w.-]+)\/(?:pull|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
948 input.url.pathname,
949 );
950 if (!match) return undefined;
951 return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);
952 },
953 listChangeRequests: (input) =>
954 // An open lookup is a user waiting on a status; the rest may be a background sweep.
955 (input.state === "open" ? Effect.succeed(true) : SourceControlRateLimit.Interactive).pipe(
956 Effect.flatMap((allowReserve) =>
957 listByHead({
958 cwd: input.cwd,
959 headSelector: input.headSelector,
960 state: input.state,
961 limit: input.limit ?? (input.state === "open" ? 1 : 20),
962 host: contextHost(input.context),
963 context: input.context,
964 allowReserve,
965 }),
966 ),
967 Effect.map((records) => records.map(toChangeRequest)),
968 Effect.mapError(
969 providerError("listChangeRequests", input.cwd, { reference: input.headSelector }),
970 ),
971 ),
972 getChangeRequest: (input) =>
973 readPullRequest({ ...input, host: contextHost(input.context) }).pipe(
974 Effect.map(toChangeRequest),
975 Effect.mapError(
976 providerError("getChangeRequest", input.cwd, { reference: input.reference }),
977 ),
978 ),
979 createChangeRequest: (input) =>
980 Effect.gen(function* () {
981 const locator = yield* resolveRepository(input);
982 const body = yield* fileSystem
983 .readFileString(input.bodyFile)
984 .pipe(
985 Effect.mapError((cause) =>
986 failure("The pull request description could not be read.", cause),
987 ),
988 );
989 yield* rest({
990 host: locator.host,
991 operation: "createPullRequest",
992 method: "POST",
993 // A user's own write may spend the reserve the background leaves for it.
994 allowReserve: true,
995 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}/pulls`,
996 // `owner:branch` is how the REST API takes a fork's head, the same as `gh --head`.
997 // gh allows maintainer edits unless told otherwise; the API's default is not documented.
998 body: {
999 base: input.baseRefName,
1000 head: input.headSelector,
1001 title: input.title,
1002 body,
1003 maintainer_can_modify: true,
1004 },
1005 });
1006 }).pipe(
1007 Effect.mapError(
1008 providerError("createChangeRequest", input.cwd, { reference: input.headSelector }),
1009 ),
1010 ),
1011 getRepositoryCloneUrls: (input) =>
1012 Effect.gen(function* () {
1013 const fallbackHost = (yield* resolveRepository(input).pipe(
1014 Effect.map((locator) => locator.host),
1015 Effect.orElseSucceed(() => environment.GH_HOST ?? "github.com"),
1016 )).toLowerCase();
1017 // A bare name is the signed-in account's repository, the way `gh repo view` reads it.
1018 const bareName = input.repository.trim().replace(/\.git$/i, "");
1019 const locator =
1020 parseGitHubRepositorySelector(input.repository, fallbackHost) ??
1021 (/^[^/\s]+$/.test(bareName)
1022 ? { host: fallbackHost, owner: yield* readViewerLogin(fallbackHost), name: bareName }
1023 : null);
1024 if (locator === null) return yield* failure("Repositories are named owner/name.");
1025 return repositoryCloneUrls(yield* readRepository(locator));
1026 }).pipe(
1027 Effect.mapError(
1028 providerError("getRepositoryCloneUrls", input.cwd, { repository: input.repository }),
1029 ),
1030 ),
1031 createRepository: (input) =>
1032 Effect.gen(function* () {
1033 const locator = parseGitHubRepositorySelector(
1034 input.repository,
1035 (environment.GH_HOST ?? "github.com").toLowerCase(),
1036 );
1037 const viewer = locator === null ? null : yield* readViewerLogin(locator.host);
1038 const owner = locator?.owner ?? viewer;
1039 const name = locator?.name ?? input.repository.trim();
1040 const host = locator?.host ?? (environment.GH_HOST?.trim().toLowerCase() || "github.com");
1041 const isViewer = viewer !== null && owner?.toLowerCase() === viewer.toLowerCase();
1042 const response = yield* rest(
1043 {
1044 host,
1045 operation: "createRepository",
1046 method: "POST",
1047 allowReserve: true,
1048 path:
1049 isViewer || owner === null ? "user/repos" : `orgs/${encodeURIComponent(owner)}/repos`,
1050 body: { name, private: input.visibility === "private" },
1051 },
1052 // GitHub answers 404 for an organization the account cannot create repositories in.
1053 `No organization named ${owner ?? "that"} that this account can create repositories in.`,
1054 );
1055 const decoded = decodeRawRepository(response.body);
1056 if (Result.isFailure(decoded)) {
1057 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
1058 }
1059 return repositoryCloneUrls(decoded.success);
1060 }).pipe(
1061 Effect.mapError(
1062 providerError("createRepository", input.cwd, { repository: input.repository }),
1063 ),
1064 ),
1065 getDefaultBranch: (input) =>
1066 Effect.gen(function* () {
1067 const locator = yield* resolveRepository({
1068 cwd: input.cwd,
1069 host: contextHost(input.context),
1070 context: input.context,
1071 });
1072 const repository = yield* readRepository(locator);
1073 const branch = repository.default_branch?.trim() ?? "";
1074 return branch.length > 0 ? branch : null;
1075 }).pipe(Effect.mapError(providerError("getDefaultBranch", input.cwd))),
1076 checkoutChangeRequest: (input) =>
1077 checkoutPullRequest(input).pipe(
1078 Effect.mapError(
1079 providerError("checkoutChangeRequest", input.cwd, { reference: input.reference }),
1080 ),
1081 ),
1082 });
1083});