Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitHubSourceControlProvider.ts

1,036 lines40.4 KB

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 { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
22import { decodeJsonResult } from "@t3tools/shared/schemaJson";
23import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
24​
25import * as ServerSettings from "../serverSettings.ts";
26import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
27import * as GitHubApi from "./GitHubApi.ts";
28import {
29 decodeGitHubPullRequestEntries,
30 type NormalizedGitHubPullRequestRecord,
31} from "./gitHubPullRequests.ts";
32import {
33 parseFetchRemotes,
34 parseGitHubRepositorySelector,
35 parsePullRequestReference,
36 resolveGitHubRepository,
37 type GitHubRepositoryLocator,
38} from "./gitHubRepositoryResolution.ts";
39import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";
40import {
41 effectiveGitHubAccount,
42 findAuthenticatedGitHubAccount,
43 parseGitHubAuthStatus,
44 type GitHubAuthStatusAccount,
45} from "./gitHubAuthStatus.ts";
46import * as SourceControlProvider from "./SourceControlProvider.ts";
47import {
48 combinedAuthOutput,
49 firstSafeAuthLine,
50 probeSourceControlProvider,
51 providerAuth,
52 type SourceControlAuthProbeInput,
53 type SourceControlCliDiscoverySpec,
54 type SourceControlManagedCliDiscoverySpec,
55} from "./SourceControlProviderDiscovery.ts";
56import * as VcsProcess from "../vcs/VcsProcess.ts";
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 };
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 }));
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 });
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;
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 process = yield* VcsProcess.VcsProcess;
195 const environment = yield* HostProcessEnvironment;
196 const serverSettings = yield* ServerSettings.ServerSettingsService;
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* serverSettings.getSettings.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 refineUnknownRemote: () => Effect.succeed(null),
259 } satisfies SourceControlManagedCliDiscoverySpec;
260});
261​
262/**
263 * Why a GitHub read or write failed, in words a user can act on. The provider methods attach the
264 * operation and request context; `cause` keeps the raw failure for logs, never for transport.
265 */
266class GitHubFailure extends Data.TaggedError("GitHubFailure")<{
267 readonly detail: string;
268 readonly cause: unknown;
269}> {}
270​
271const failure = (detail: string, cause?: unknown) => new GitHubFailure({ detail, cause });
272​
273const PULL_REQUEST_NOT_FOUND = "Pull request not found. Check the PR number or URL and try again.";
274const REPOSITORY_NOT_FOUND = "Repository not found. Check the owner and name and try again.";
275​
276/** `notFound` names what was missing, which only the operation knows. */
277function fromGitHubApiError(
278 error: GitHubApi.GitHubApiError,
279 notFound = PULL_REQUEST_NOT_FOUND,
280): GitHubFailure {
281 switch (error._tag) {
282 case "GitHubCliMissingError":
283 return failure(
284 "No GitHub credential on the server. Set GH_TOKEN, or install the GitHub CLI and run `gh auth login`.",
285 error,
286 );
287 case "GitHubNotSignedInError":
288 case "GitHubHostDisabledError":
289 // A missing or turned-off credential already says what to do about it.
290 return failure(error.message, error);
291 case "GitHubApiAuthenticationError":
292 return failure(
293 "GitHub is not authenticated. Run `gh auth login` (or set GH_TOKEN) and retry.",
294 error,
295 );
296 case "GitHubApiRateLimitError":
297 case "SourceControlRateLimitPausedError":
298 return failure(
299 "GitHub API rate limit exceeded. Requests resume when the limit resets.",
300 error,
301 );
302 case "GitHubApiNotFoundError":
303 return failure(notFound, error);
304 case "GitHubCliFailedError":
305 case "GitHubApiResponseError":
306 case "GitHubApiRequestError":
307 // GitHub's own reason ("A pull request already exists…") when it gave one.
308 return failure(error.message.trim() || "GitHub request failed.", error);
309 }
311​
312const notFound = (cause: string) => failure(PULL_REQUEST_NOT_FOUND, new Error(cause));
313​
314const RawRepositorySchema = Schema.Struct({
315 full_name: TrimmedNonEmptyString,
316 html_url: TrimmedNonEmptyString,
317 ssh_url: TrimmedNonEmptyString,
318 default_branch: Schema.optional(Schema.NullOr(Schema.String)),
319});
320const decodeRawRepository = decodeJsonResult(RawRepositorySchema);
321​
322function repositoryCloneUrls(
323 raw: Schema.Schema.Type<typeof RawRepositorySchema>,
324): SourceControlRepositoryCloneUrls {
325 return { nameWithOwner: raw.full_name, url: raw.html_url, sshUrl: raw.ssh_url };
327​
328const decodeViewerLogin = decodeJsonResult(Schema.Struct({ login: TrimmedNonEmptyString }));
329​
330type PullRequestListState = "open" | "closed" | "merged" | "all";
331​
332/** The pull request fields every read selects, in GraphQL. */
333const PULL_REQUEST_NODE_SELECTION =
334 "number title url baseRefName headRefName headRefOid state isDraft mergedAt closedAt updatedAt isCrossRepository headRepository { name nameWithOwner } headRepositoryOwner { login }";
335const GRAPHQL_STATES: Record<PullRequestListState, ReadonlyArray<string>> = {
336 open: ["OPEN"],
337 closed: ["CLOSED"],
338 merged: ["MERGED"],
339 all: ["OPEN", "CLOSED", "MERGED"],
340};
341/**
342 * Head lookups per GraphQL document. A document of a hundred costs one point, the same as one
343 * single lookup, but half that keeps each answer near half a second.
344 */
345const HEAD_LOOKUPS_PER_DOCUMENT = 50;
346/**
347 * How long a head lookup waits for company. Branch discovery reaches GitHub only after each
348 * branch's own git reads, so lookups started together arrive tens of milliseconds apart.
349 * A background sweep's lookups spread over up to ~300ms, and every document costs a point no
350 * matter how few heads it holds, so reads without reserve wait longer.
351 */
352const HEAD_LOOKUP_BATCH_WINDOW = "50 millis";
353const BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW = "500 millis";
354/**
355 * Background documents fill up under the longer window, and a failed document fails every head
356 * in it. Fifty `main`-like heads of a hundred pull requests each took up to ~10s, GitHub's own
357 * processing limit; twenty-five took ~7s.
358 */
359const BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT = 25;
360/** A full document is 5,000 rows of well under 2 KB each. */
361const HEAD_LOOKUP_MAX_RESPONSE_BYTES = 16_000_000;
362/**
363 * Rows read for a fork's `owner:branch` head, which GitHub cannot filter by owner. A branch
364 * named like a busy default (`main`) is the case this bounds; the owner's own row is near the
365 * top because the newest come first.
366 */
367const OWNER_HEAD_SCAN_LIMIT = 100;
368​
369class PullRequestsByHeadRead extends Request.Class<
370 {
371 readonly host: string;
372 readonly owner: string;
373 readonly name: string;
374 readonly headRefName: string;
375 readonly state: PullRequestListState;
376 readonly limit: number;
377 readonly allowReserve: boolean;
378 },
379 ReadonlyArray<NormalizedGitHubPullRequestRecord>,
380 GitHubFailure
381> {}
382​
383/** One aliased `pullRequests` connection per lookup, each head and state passed as a variable. */
384function buildPullRequestsByHeadQuery(
385 lookups: ReadonlyArray<Pick<PullRequestsByHeadRead, "headRefName" | "state" | "limit">>,
386): { readonly document: string; readonly variables: Record<string, unknown> } {
387 const variables: Record<string, unknown> = {};
388 const declarations: string[] = ["$owner: String!", "$name: String!"];
389 const selections: string[] = [];
390 for (const [index, lookup] of lookups.entries()) {
391 variables[`h${index}`] = lookup.headRefName;
392 variables[`s${index}`] = GRAPHQL_STATES[lookup.state];
393 declarations.push(`$h${index}: String!`, `$s${index}: [PullRequestState!]`);
394 // `gh pr list` orders the same way, so a head with more matches than the limit keeps the
395 // same rows.
396 selections.push(
397 ` h${index}: pullRequests(headRefName: $h${index}, states: $s${index}, first: ${lookup.limit}, orderBy: { field: CREATED_AT, direction: DESC }) { nodes { ${PULL_REQUEST_NODE_SELECTION} } }`,
398 );
399 }
400 return {
401 document: `query PullRequestsByHead(${declarations.join(", ")}) {\n repository(owner: $owner, name: $name) {\n${selections.join("\n")}\n }\n}`,
402 variables,
403 };
405​
406const PULL_REQUEST_BY_NUMBER_QUERY = `query PullRequestByNumber($owner: String!, $name: String!, $number: Int!) {
407 repository(owner: $owner, name: $name) {
408 pullRequest(number: $number) { ${PULL_REQUEST_NODE_SELECTION} }
409 }
410}`;
411​
412const decodePullRequestsByHead = decodeJsonResult(
413 Schema.Struct({
414 data: Schema.Struct({
415 repository: Schema.NullOr(
416 Schema.Record(
417 Schema.String,
418 Schema.NullOr(Schema.Struct({ nodes: Schema.Array(Schema.Unknown) })),
419 ),
420 ),
421 }),
422 }),
423);
424​
425const decodePullRequestByNumber = decodeJsonResult(
426 Schema.Struct({
427 data: Schema.Struct({
428 repository: Schema.NullOr(Schema.Struct({ pullRequest: Schema.NullOr(Schema.Unknown) })),
429 }),
430 }),
431);
432​
433/** The local branch a pull request checks out into, the way `gh pr checkout` names it. */
434export function pullRequestCheckoutBranchName(input: {
435 readonly headRefName: string;
436 readonly headOwner: string | null;
437 readonly isCrossRepository: boolean;
438 readonly defaultBranch: string | null;
439}): string {
440 // gh prefixes the owner only where the fork's branch would take over the default branch's
441 // name, which is the one collision every fork pull request from `main` would hit.
442 return input.isCrossRepository &&
443 input.headOwner !== null &&
444 input.defaultBranch !== null &&
445 input.headRefName === input.defaultBranch
446 ? `${input.headOwner}/${input.headRefName}`
447 : input.headRefName;
449​
450/** The checkout's GitHub API host, from the remote the caller resolved the provider from. */
451const contextHost = (context: SourceControlProvider.SourceControlProviderContext | undefined) =>
452 context === undefined ? undefined : new URL(context.provider.baseUrl).host;
453​
454export const make = Effect.gen(function* () {
455 const api = yield* GitHubApi.GitHubApi;
456 const process = yield* VcsProcess.VcsProcess;
457 const environment = yield* HostProcessEnvironment;
458 const git = yield* GitVcsDriver.GitVcsDriver;
459 const fileSystem = yield* FileSystem.FileSystem;
460​
461 const gitRead = (cwd: string, args: ReadonlyArray<string>) =>
462 process.run({
463 operation: "GitHubSourceControlProvider.resolveRepository",
464 command: "git",
465 args,
466 cwd,
467 allowNonZeroExit: true,
468 timeoutMs: 5_000,
469 });
470​
471 /**
472 * The repository `gh` would act on in `cwd`: GH_REPO, else the remote `gh` would pick, else
473 * the remote the caller resolved the provider from, else the best-ranked GitHub remote.
474 */
475 const resolveRepository = Effect.fn("GitHubSourceControlProvider.resolveRepository")(
476 function* (input: { readonly cwd: string; readonly host?: string | undefined }) {
477 const envRepository = environment.GH_REPO?.trim();
478 const defaultHost = (input.host ?? environment.GH_HOST ?? "github.com").toLowerCase();
479 if (envRepository) {
480 const locator = parseGitHubRepositorySelector(envRepository, defaultHost);
481 if (locator !== null) return locator;
482 }
483 const [remotes, resolved] = yield* Effect.all([
484 gitRead(input.cwd, ["remote", "-v"]),
485 gitRead(input.cwd, ["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"]),
486 ]).pipe(Effect.orElseSucceed(() => [null, null] as const));
487 const { host, locator } = resolveGitHubRepository({
488 remotes: remotes?.exitCode === 0 ? remotes.stdout : "",
489 resolved: resolved?.exitCode === 0 ? resolved.stdout : "",
490 hostHint: input.host,
491 defaultHost,
492 });
493 if (locator !== null) return locator;
494 return yield* failure(
495 `No GitHub repository on ${host} was found among this checkout's git remotes.`,
496 );
497 },
498 );
499​
500 const graphqlJson = <A>(
501 input: GitHubApi.GitHubGraphQlInput,
502 decode: (raw: string) => Result.Result<A, unknown>,
503 decodeDetail: string,
504 ) =>
505 api.graphql(input).pipe(
506 Effect.mapError(fromGitHubApiError),
507 Effect.flatMap((raw) => {
508 const decoded = decode(raw);
509 return Result.isSuccess(decoded)
510 ? Effect.succeed(decoded.success)
511 : Effect.fail(failure(decodeDetail, decoded.failure));
512 }),
513 );
514​
515 const rest = (input: GitHubApi.GitHubRestInput, notFoundDetail?: string) =>
516 api.rest(input).pipe(Effect.mapError((error) => fromGitHubApiError(error, notFoundDetail)));
517​
518 const headResolver = RequestResolver.makeGrouped<PullRequestsByHeadRead, string>({
519 key: ({ request, context }) =>
520 [
521 request.host,
522 request.owner,
523 request.name,
524 String(request.allowReserve),
525 Context.getOrElse(context, GitHubApi.PinnedGitHubCredential, () => null)
526 ?.credentialFingerprint ?? "",
527 Context.getOrElse(context, SourceControlRateLimit.CredentialScope, () => ""),
528 Context.getOrElse(context, GitHubApi.GitHubAccount, () => null) ?? "",
529 ].join("\0"),
530 resolver: (entries) => {
531 const [first] = entries;
532 const { host, owner, name, allowReserve } = first.request;
533 const query = buildPullRequestsByHeadQuery(entries.map((entry) => entry.request));
534 return graphqlJson(
535 {
536 host,
537 operation: "listPullRequestsByHead",
538 query: query.document,
539 variables: { owner, name, ...query.variables },
540 allowReserve,
541 // Up to 50 heads of 100 rows each. A default branch such as `main` can match a hundred
542 // fork pull requests, so the usual cap would cut the answer short.
543 maxResponseBytes: HEAD_LOOKUP_MAX_RESPONSE_BYTES,
544 },
545 decodePullRequestsByHead,
546 "GitHub returned an invalid change request list.",
547 ).pipe(
548 Effect.flatMap((decoded) =>
549 decoded.data.repository === null
550 ? Effect.fail(notFound("The repository could not be read."))
551 : Effect.succeed(decoded.data.repository),
552 ),
553 Effect.map((aliases) => {
554 for (const [index, entry] of entries.entries()) {
555 const alias = aliases[`h${index}`];
556 entry.completeUnsafe(
557 Exit.succeed(alias == null ? [] : decodeGitHubPullRequestEntries(alias.nodes)),
558 );
559 }
560 }),
561 Effect.catchCause((cause) =>
562 Effect.sync(() => {
563 for (const entry of entries) entry.completeUnsafe(Exit.failCause(cause));
564 }),
565 ),
566 );
567 },
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 /**
578 * Pull requests whose head is `headSelector` (a branch, or `owner:branch` for a fork), in the
579 * repository `gh pr list` would read in `cwd`. Lookups on one repository that arrive together
580 * share one GraphQL document.
581 */
582 const listByHead = Effect.fn("GitHubSourceControlProvider.listByHead")(function* (input: {
583 readonly cwd: string;
584 readonly headSelector: string;
585 readonly state: PullRequestListState;
586 readonly limit: number;
587 readonly host?: string | undefined;
588 readonly allowReserve: boolean;
589 }) {
590 const locator = yield* resolveRepository({ cwd: input.cwd, host: input.host });
591 const limit = Math.min(Math.max(Math.trunc(input.limit), 1), 100);
592 // `owner:branch` names a fork's branch. GitHub filters on the branch name only, so the
593 // owner is matched on the rows it returns.
594 const ownerMatch = /^([^:/\s]+):(.+)$/u.exec(input.headSelector.trim());
595 const headRefName = ownerMatch?.[2] ?? input.headSelector.trim();
596 const rows = yield* Effect.request(
597 new PullRequestsByHeadRead({
598 ...locator,
599 headRefName,
600 state: input.state,
601 limit: ownerMatch ? OWNER_HEAD_SCAN_LIMIT : limit,
602 allowReserve: input.allowReserve,
603 }),
604 input.allowReserve ? interactiveHeadResolver : backgroundHeadResolver,
605 );
606 if (!ownerMatch) return rows;
607 const headOwner = ownerMatch[1]!.toLowerCase();
608 return rows
609 .filter((row) => row.headRepositoryOwnerLogin?.toLowerCase() === headOwner)
610 .slice(0, limit);
611 });
612​
613 const readPullRequest = Effect.fn("GitHubSourceControlProvider.readPullRequest")(
614 function* (input: {
615 readonly cwd: string;
616 readonly reference: string;
617 readonly host?: string | undefined;
618 }) {
619 const parsed = parsePullRequestReference(input.reference);
620 if (parsed.kind === "branch") {
621 // `gh pr view <branch>` prefers an open pull request, then the newest of any state.
622 const lookup = (state: PullRequestListState) =>
623 listByHead({
624 cwd: input.cwd,
625 headSelector: parsed.headSelector,
626 state,
627 limit: 1,
628 host: input.host,
629 allowReserve: true,
630 });
631 const [open] = yield* lookup("open");
632 const found = open ?? (yield* lookup("all"))[0];
633 if (found === undefined) return yield* notFound("No pull request has this head branch.");
634 return found;
635 }
636 const locator =
637 parsed.kind === "url"
638 ? parsed.locator
639 : yield* resolveRepository({ cwd: input.cwd, host: input.host });
640 const decodeDetail = "GitHub returned an invalid pull request.";
641 const decoded = yield* graphqlJson(
642 {
643 host: locator.host,
644 operation: "getPullRequest",
645 query: PULL_REQUEST_BY_NUMBER_QUERY,
646 variables: { owner: locator.owner, name: locator.name, number: parsed.number },
647 allowReserve: true,
648 },
649 decodePullRequestByNumber,
650 decodeDetail,
651 );
652 const node = decoded.data.repository?.pullRequest;
653 if (node == null) return yield* notFound("The pull request does not exist.");
654 const [record] = decodeGitHubPullRequestEntries([node]);
655 if (record === undefined)
656 return yield* failure(decodeDetail, new Error("Malformed pull request."));
657 return record;
658 },
659 );
660​
661 const readRepository = Effect.fn("GitHubSourceControlProvider.readRepository")(function* (
662 locator: GitHubRepositoryLocator,
663 ) {
664 const response = yield* rest(
665 {
666 host: locator.host,
667 operation: "getRepository",
668 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}`,
669 allowReserve: true,
670 },
671 REPOSITORY_NOT_FOUND,
672 );
673 const decoded = decodeRawRepository(response.body);
674 if (Result.isFailure(decoded)) {
675 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
676 }
677 return decoded.success;
678 });
679​
680 const readViewerLogin = Effect.fn("GitHubSourceControlProvider.readViewerLogin")(function* (
681 host: string,
682 ) {
683 const response = yield* rest({
684 host,
685 operation: "getViewer",
686 path: "user",
687 allowReserve: true,
688 });
689 const decoded = decodeViewerLogin(response.body);
690 if (Result.isFailure(decoded)) {
691 return yield* failure("GitHub request failed.", decoded.failure);
692 }
693 return decoded.success.login;
694 });
695​
696 // Git and filesystem errors can carry arguments, paths and stderr, so the detail a client
697 // sees is fixed and the raw error stays in `cause`.
698 const gitFailure = (cause: unknown) =>
699 failure("The pull request could not be checked out with git.", cause);
700​
701 const runGit = (cwd: string, operation: string, args: ReadonlyArray<string>) =>
702 git.execute({
703 operation: `GitHubSourceControlProvider.checkoutPullRequest.${operation}`,
704 cwd,
705 args,
706 });
707​
708 /**
709 * `gh pr checkout` in plain git: the head branch is fetched from the remote that holds it (a
710 * fork gets a remote of its own), checked out under the name gh would give it, and set to
711 * track the head. A head branch that is gone is read from the base's `refs/pull/<n>/head`.
712 * An existing branch fast-forwards, or with `force` is reset to the pull request.
713 */
714 const checkoutPullRequest = Effect.fn("GitHubSourceControlProvider.checkoutPullRequest")(
715 function* (input: {
716 readonly cwd: string;
717 readonly reference: string;
718 readonly force?: boolean;
719 }) {
720 const reference = parsePullRequestReference(input.reference);
721 const pullRequest = yield* readPullRequest({ cwd: input.cwd, reference: input.reference });
722 const base =
723 reference.kind === "url" ? reference.locator : yield* resolveRepository({ cwd: input.cwd });
724 const baseNameWithOwner = `${base.owner}/${base.name}`.toLowerCase();
725 const headNameWithOwner = pullRequest.headRepositoryNameWithOwner ?? null;
726 const isCrossRepository =
727 pullRequest.isCrossRepository ??
728 (headNameWithOwner !== null && headNameWithOwner.toLowerCase() !== baseNameWithOwner);
729 const headOwner =
730 pullRequest.headRepositoryOwnerLogin ?? headNameWithOwner?.split("/")[0] ?? null;
731​
732 const remotes = yield* gitRead(input.cwd, ["remote", "-v"]).pipe(
733 Effect.map((result) => (result.exitCode === 0 ? result.stdout : "")),
734 Effect.mapError(gitFailure),
735 );
736 const remoteFor = (nameWithOwner: string) =>
737 parseFetchRemotes(remotes).find(
738 (remote) =>
739 normalizeGitRemoteUrl(remote.url).split("/").slice(1).join("/") ===
740 nameWithOwner.toLowerCase(),
741 )?.name ?? null;
742 const baseRemote = Effect.suspend(() => {
743 const known = remoteFor(baseNameWithOwner);
744 return known === null ? git.resolvePrimaryRemoteName(input.cwd) : Effect.succeed(known);
745 });
746 // A fork's branch named like the base's default branch is checked out under the owner's
747 // prefix. Without the default branch that collision cannot be ruled out, and the checkout
748 // would reset the local default branch to the fork's commit, so it fails instead.
749 const defaultBranch = isCrossRepository
750 ? yield* readRepository(base).pipe(
751 Effect.map((repository) => repository.default_branch ?? null),
752 )
753 : null;
754 const localBranch = pullRequestCheckoutBranchName({
755 headRefName: pullRequest.headRefName,
756 headOwner,
757 isCrossRepository,
758 defaultBranch,
759 });
760​
761 /** The remote the head branch lives on; a fork the checkout does not know yet is added. */
762 const headRemote = Effect.gen(function* () {
763 if (!isCrossRepository) return yield* baseRemote;
764 if (headNameWithOwner === null) return yield* failure("The fork is gone.");
765 const known = remoteFor(headNameWithOwner);
766 if (known !== null) return known;
767 const [owner, name] = headNameWithOwner.split("/");
768 const fork = yield* readRepository({ host: base.host, owner: owner!, name: name! });
769 const originUrl = yield* git.readConfigValue(input.cwd, "remote.origin.url");
770 return yield* git.ensureRemote({
771 cwd: input.cwd,
772 preferredName: headOwner ?? "fork",
773 url: originUrl !== null && isSshRemoteUrl(originUrl) ? fork.ssh_url : fork.html_url,
774 });
775 });
776​
777 const exists = (yield* git
778 .listLocalBranchNames(input.cwd)
779 .pipe(Effect.mapError(gitFailure))).includes(localBranch);
780​
781 // The commit to check out, fetched from the head branch where it still exists.
782 const target = yield* Effect.gen(function* () {
783 const remoteName = yield* headRemote;
784 yield* git.fetchRemoteTrackingBranch({
785 cwd: input.cwd,
786 remoteName,
787 remoteBranch: pullRequest.headRefName,
788 });
789 return {
790 ref: `refs/remotes/${remoteName}/${pullRequest.headRefName}`,
791 upstream: { remoteName, remoteBranch: pullRequest.headRefName },
792 };
793 }).pipe(
794 Effect.catch(() =>
795 Effect.gen(function* () {
796 yield* runGit(input.cwd, "fetchPullRef", [
797 "fetch",
798 "--quiet",
799 "--no-tags",
800 yield* baseRemote,
801 `refs/pull/${pullRequest.number}/head`,
802 ]);
803 const { commitSha } = yield* git.resolveCommit({
804 cwd: input.cwd,
805 revision: "FETCH_HEAD",
806 });
807 return { ref: commitSha, upstream: null };
808 }),
809 ),
810 Effect.mapError(gitFailure),
811 );
812​
813 yield* Effect.gen(function* () {
814 if (!exists) yield* runGit(input.cwd, "branch", ["branch", localBranch, target.ref]);
815 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
816 if (exists) {
817 yield* runGit(
818 input.cwd,
819 "sync",
820 input.force === true
821 ? ["reset", "--hard", "--quiet", target.ref]
822 : ["merge", "--ff-only", "--quiet", target.ref],
823 );
824 }
825 // Tracking is set once the branch is the pull request's, so a sync that fails leaves an
826 // existing branch's upstream as it was.
827 if (target.upstream !== null) {
828 yield* git.setBranchUpstream({ cwd: input.cwd, branch: localBranch, ...target.upstream });
829 }
830 }).pipe(Effect.mapError(gitFailure));
831 },
832 );
833​
834 /** Reports a failure against the operation and request that made it, with transport-safe context. */
835 const providerError =
836 (
837 operation: string,
838 cwd: string,
839 context?: { readonly reference?: string; readonly repository?: string },
840 ) =>
841 (error: GitHubFailure) =>
842 new SourceControlProviderError({
843 provider: "github",
844 operation,
845 cwd,
846 ...(context?.reference === undefined
847 ? {}
848 : {
849 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
850 context.reference,
851 ),
852 }),
853 ...(context?.repository === undefined
854 ? {}
855 : {
856 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
857 context.repository,
858 ),
859 }),
860 detail: error.detail,
861 cause: error.cause,
862 });
863​
864 const readLinkSubject = Effect.fn("GitHubSourceControlProvider.readLinkSubject")(function* (
865 input: { readonly cwd: string; readonly url: URL },
866 endpoint: string,
867 ) {
868 const result = yield* api
869 .rest({
870 host: input.url.host,
871 operation: "resolveLink",
872 path: endpoint,
873 maxResponseBytes: 1_000_000,
874 })
875 .pipe(
876 Effect.timeout("3 seconds"),
877 Effect.mapError(
878 (cause) =>
879 new SourceControlProviderError({
880 provider: "github",
881 operation: "resolveLink",
882 cwd: input.cwd,
883 detail: "The linked subject could not be read.",
884 cause,
885 }),
886 ),
887 );
888 const subject = yield* decodeLinkSubject(result.body).pipe(
889 Effect.mapError(
890 (cause) =>
891 new SourceControlProviderError({
892 provider: "github",
893 operation: "resolveLink.decode",
894 cwd: input.cwd,
895 detail: "The linked subject could not be read.",
896 cause,
897 }),
898 ),
899 );
900 return { title: subject.title, body: subject.body ?? null };
901 });
902​
903 return SourceControlProvider.SourceControlProvider.of({
904 kind: "github",
905 resolveLink: (input) => {
906 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
907 if (input.url.host !== "github.com") return undefined;
908 const match = /^\/([\w.-]+)\/([\w.-]+)\/(?:pull|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
909 input.url.pathname,
910 );
911 if (!match) return undefined;
912 return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);
913 },
914 listChangeRequests: (input) =>
915 // An open lookup is a user waiting on a status; the rest may be a background sweep.
916 (input.state === "open" ? Effect.succeed(true) : GitHubApi.AllowGitHubReserve).pipe(
917 Effect.flatMap((allowReserve) =>
918 listByHead({
919 cwd: input.cwd,
920 headSelector: input.headSelector,
921 state: input.state,
922 limit: input.limit ?? (input.state === "open" ? 1 : 20),
923 host: contextHost(input.context),
924 allowReserve,
925 }),
926 ),
927 Effect.map((records) => records.map(toChangeRequest)),
928 Effect.mapError(
929 providerError("listChangeRequests", input.cwd, { reference: input.headSelector }),
930 ),
931 ),
932 getChangeRequest: (input) =>
933 readPullRequest({ ...input, host: contextHost(input.context) }).pipe(
934 Effect.map(toChangeRequest),
935 Effect.mapError(
936 providerError("getChangeRequest", input.cwd, { reference: input.reference }),
937 ),
938 ),
939 createChangeRequest: (input) =>
940 Effect.gen(function* () {
941 const locator = yield* resolveRepository({ cwd: input.cwd });
942 const body = yield* fileSystem
943 .readFileString(input.bodyFile)
944 .pipe(
945 Effect.mapError((cause) =>
946 failure("The pull request description could not be read.", cause),
947 ),
948 );
949 yield* rest({
950 host: locator.host,
951 operation: "createPullRequest",
952 method: "POST",
953 // A user's own write may spend the reserve the background leaves for it.
954 allowReserve: true,
955 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}/pulls`,
956 // `owner:branch` is how the REST API takes a fork's head, the same as `gh --head`.
957 // gh allows maintainer edits unless told otherwise; the API's default is not documented.
958 body: {
959 base: input.baseRefName,
960 head: input.headSelector,
961 title: input.title,
962 body,
963 maintainer_can_modify: true,
964 },
965 });
966 }).pipe(
967 Effect.mapError(
968 providerError("createChangeRequest", input.cwd, { reference: input.headSelector }),
969 ),
970 ),
971 getRepositoryCloneUrls: (input) =>
972 Effect.gen(function* () {
973 const fallbackHost = (yield* resolveRepository({ cwd: input.cwd }).pipe(
974 Effect.map((locator) => locator.host),
975 Effect.orElseSucceed(() => environment.GH_HOST ?? "github.com"),
976 )).toLowerCase();
977 const locator = parseGitHubRepositorySelector(input.repository, fallbackHost);
978 if (locator === null) return yield* failure("Repositories are named owner/name.");
979 return repositoryCloneUrls(yield* readRepository(locator));
980 }).pipe(
981 Effect.mapError(
982 providerError("getRepositoryCloneUrls", input.cwd, { repository: input.repository }),
983 ),
984 ),
985 createRepository: (input) =>
986 Effect.gen(function* () {
987 const locator = parseGitHubRepositorySelector(
988 input.repository,
989 (environment.GH_HOST ?? "github.com").toLowerCase(),
990 );
991 const viewer = locator === null ? null : yield* readViewerLogin(locator.host);
992 const owner = locator?.owner ?? viewer;
993 const name = locator?.name ?? input.repository.trim();
994 const host = locator?.host ?? (environment.GH_HOST?.trim().toLowerCase() || "github.com");
995 const isViewer = viewer !== null && owner?.toLowerCase() === viewer.toLowerCase();
996 const response = yield* rest(
997 {
998 host,
999 operation: "createRepository",
1000 method: "POST",
1001 allowReserve: true,
1002 path:
1003 isViewer || owner === null ? "user/repos" : `orgs/${encodeURIComponent(owner)}/repos`,
1004 body: { name, private: input.visibility === "private" },
1005 },
1006 // GitHub answers 404 for an organization the account cannot create repositories in.
1007 `No organization named ${owner ?? "that"} that this account can create repositories in.`,
1008 );
1009 const decoded = decodeRawRepository(response.body);
1010 if (Result.isFailure(decoded)) {
1011 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
1013 return repositoryCloneUrls(decoded.success);
1014 }).pipe(
1015 Effect.mapError(
1016 providerError("createRepository", input.cwd, { repository: input.repository }),
1017 ),
1018 ),
1019 getDefaultBranch: (input) =>
1020 Effect.gen(function* () {
1021 const locator = yield* resolveRepository({
1022 cwd: input.cwd,
1023 host: contextHost(input.context),
1024 });
1025 const repository = yield* readRepository(locator);
1026 const branch = repository.default_branch?.trim() ?? "";
1027 return branch.length > 0 ? branch : null;
1028 }).pipe(Effect.mapError(providerError("getDefaultBranch", input.cwd))),
1029 checkoutChangeRequest: (input) =>
1030 checkoutPullRequest(input).pipe(
1031 Effect.mapError(
1032 providerError("checkoutChangeRequest", input.cwd, { reference: input.reference }),
1033 ),
1034 ),
1035 });
1036});