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

GitHubSourceControlProvider.ts

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