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