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