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