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