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

GitHubSourceControlProvider.ts

1,035 lines40.3 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 ].join("\0"),
529 resolver: (entries) => {
530 const [first] = entries;
531 const { host, owner, name, allowReserve } = first.request;
532 const query = buildPullRequestsByHeadQuery(entries.map((entry) => entry.request));
533 return graphqlJson(
534 {
535 host,
536 operation: "listPullRequestsByHead",
537 query: query.document,
538 variables: { owner, name, ...query.variables },
539 allowReserve,
540 // Up to 50 heads of 100 rows each. A default branch such as `main` can match a hundred
541 // fork pull requests, so the usual cap would cut the answer short.
542 maxResponseBytes: HEAD_LOOKUP_MAX_RESPONSE_BYTES,
543 },
544 decodePullRequestsByHead,
545 "GitHub returned an invalid change request list.",
546 ).pipe(
547 Effect.flatMap((decoded) =>
548 decoded.data.repository === null
549 ? Effect.fail(notFound("The repository could not be read."))
550 : Effect.succeed(decoded.data.repository),
551 ),
552 Effect.map((aliases) => {
553 for (const [index, entry] of entries.entries()) {
554 const alias = aliases[`h${index}`];
555 entry.completeUnsafe(
556 Exit.succeed(alias == null ? [] : decodeGitHubPullRequestEntries(alias.nodes)),
557 );
558 }
559 }),
560 Effect.catchCause((cause) =>
561 Effect.sync(() => {
562 for (const entry of entries) entry.completeUnsafe(Exit.failCause(cause));
563 }),
564 ),
565 );
566 },
567 }).pipe(RequestResolver.batchN(HEAD_LOOKUPS_PER_DOCUMENT));
568 const interactiveHeadResolver = headResolver.pipe(
569 RequestResolver.setDelay(HEAD_LOOKUP_BATCH_WINDOW),
570 );
571 const backgroundHeadResolver = headResolver.pipe(
572 RequestResolver.batchN(BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT),
573 RequestResolver.setDelay(BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW),
574 );
575​
576 /**
577 * Pull requests whose head is `headSelector` (a branch, or `owner:branch` for a fork), in the
578 * repository `gh pr list` would read in `cwd`. Lookups on one repository that arrive together
579 * share one GraphQL document.
580 */
581 const listByHead = Effect.fn("GitHubSourceControlProvider.listByHead")(function* (input: {
582 readonly cwd: string;
583 readonly headSelector: string;
584 readonly state: PullRequestListState;
585 readonly limit: number;
586 readonly host?: string | undefined;
587 readonly allowReserve: boolean;
588 }) {
589 const locator = yield* resolveRepository({ cwd: input.cwd, host: input.host });
590 const limit = Math.min(Math.max(Math.trunc(input.limit), 1), 100);
591 // `owner:branch` names a fork's branch. GitHub filters on the branch name only, so the
592 // owner is matched on the rows it returns.
593 const ownerMatch = /^([^:/\s]+):(.+)$/u.exec(input.headSelector.trim());
594 const headRefName = ownerMatch?.[2] ?? input.headSelector.trim();
595 const rows = yield* Effect.request(
596 new PullRequestsByHeadRead({
597 ...locator,
598 headRefName,
599 state: input.state,
600 limit: ownerMatch ? OWNER_HEAD_SCAN_LIMIT : limit,
601 allowReserve: input.allowReserve,
602 }),
603 input.allowReserve ? interactiveHeadResolver : backgroundHeadResolver,
604 );
605 if (!ownerMatch) return rows;
606 const headOwner = ownerMatch[1]!.toLowerCase();
607 return rows
608 .filter((row) => row.headRepositoryOwnerLogin?.toLowerCase() === headOwner)
609 .slice(0, limit);
610 });
611​
612 const readPullRequest = Effect.fn("GitHubSourceControlProvider.readPullRequest")(
613 function* (input: {
614 readonly cwd: string;
615 readonly reference: string;
616 readonly host?: string | undefined;
617 }) {
618 const parsed = parsePullRequestReference(input.reference);
619 if (parsed.kind === "branch") {
620 // `gh pr view <branch>` prefers an open pull request, then the newest of any state.
621 const lookup = (state: PullRequestListState) =>
622 listByHead({
623 cwd: input.cwd,
624 headSelector: parsed.headSelector,
625 state,
626 limit: 1,
627 host: input.host,
628 allowReserve: true,
629 });
630 const [open] = yield* lookup("open");
631 const found = open ?? (yield* lookup("all"))[0];
632 if (found === undefined) return yield* notFound("No pull request has this head branch.");
633 return found;
634 }
635 const locator =
636 parsed.kind === "url"
637 ? parsed.locator
638 : yield* resolveRepository({ cwd: input.cwd, host: input.host });
639 const decodeDetail = "GitHub returned an invalid pull request.";
640 const decoded = yield* graphqlJson(
641 {
642 host: locator.host,
643 operation: "getPullRequest",
644 query: PULL_REQUEST_BY_NUMBER_QUERY,
645 variables: { owner: locator.owner, name: locator.name, number: parsed.number },
646 allowReserve: true,
647 },
648 decodePullRequestByNumber,
649 decodeDetail,
650 );
651 const node = decoded.data.repository?.pullRequest;
652 if (node == null) return yield* notFound("The pull request does not exist.");
653 const [record] = decodeGitHubPullRequestEntries([node]);
654 if (record === undefined)
655 return yield* failure(decodeDetail, new Error("Malformed pull request."));
656 return record;
657 },
658 );
659​
660 const readRepository = Effect.fn("GitHubSourceControlProvider.readRepository")(function* (
661 locator: GitHubRepositoryLocator,
662 ) {
663 const response = yield* rest(
664 {
665 host: locator.host,
666 operation: "getRepository",
667 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}`,
668 allowReserve: true,
669 },
670 REPOSITORY_NOT_FOUND,
671 );
672 const decoded = decodeRawRepository(response.body);
673 if (Result.isFailure(decoded)) {
674 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
675 }
676 return decoded.success;
677 });
678​
679 const readViewerLogin = Effect.fn("GitHubSourceControlProvider.readViewerLogin")(function* (
680 host: string,
681 ) {
682 const response = yield* rest({
683 host,
684 operation: "getViewer",
685 path: "user",
686 allowReserve: true,
687 });
688 const decoded = decodeViewerLogin(response.body);
689 if (Result.isFailure(decoded)) {
690 return yield* failure("GitHub request failed.", decoded.failure);
691 }
692 return decoded.success.login;
693 });
694​
695 // Git and filesystem errors can carry arguments, paths and stderr, so the detail a client
696 // sees is fixed and the raw error stays in `cause`.
697 const gitFailure = (cause: unknown) =>
698 failure("The pull request could not be checked out with git.", cause);
699​
700 const runGit = (cwd: string, operation: string, args: ReadonlyArray<string>) =>
701 git.execute({
702 operation: `GitHubSourceControlProvider.checkoutPullRequest.${operation}`,
703 cwd,
704 args,
705 });
706​
707 /**
708 * `gh pr checkout` in plain git: the head branch is fetched from the remote that holds it (a
709 * fork gets a remote of its own), checked out under the name gh would give it, and set to
710 * track the head. A head branch that is gone is read from the base's `refs/pull/<n>/head`.
711 * An existing branch fast-forwards, or with `force` is reset to the pull request.
712 */
713 const checkoutPullRequest = Effect.fn("GitHubSourceControlProvider.checkoutPullRequest")(
714 function* (input: {
715 readonly cwd: string;
716 readonly reference: string;
717 readonly force?: boolean;
718 }) {
719 const reference = parsePullRequestReference(input.reference);
720 const pullRequest = yield* readPullRequest({ cwd: input.cwd, reference: input.reference });
721 const base =
722 reference.kind === "url" ? reference.locator : yield* resolveRepository({ cwd: input.cwd });
723 const baseNameWithOwner = `${base.owner}/${base.name}`.toLowerCase();
724 const headNameWithOwner = pullRequest.headRepositoryNameWithOwner ?? null;
725 const isCrossRepository =
726 pullRequest.isCrossRepository ??
727 (headNameWithOwner !== null && headNameWithOwner.toLowerCase() !== baseNameWithOwner);
728 const headOwner =
729 pullRequest.headRepositoryOwnerLogin ?? headNameWithOwner?.split("/")[0] ?? null;
730​
731 const remotes = yield* gitRead(input.cwd, ["remote", "-v"]).pipe(
732 Effect.map((result) => (result.exitCode === 0 ? result.stdout : "")),
733 Effect.mapError(gitFailure),
734 );
735 const remoteFor = (nameWithOwner: string) =>
736 parseFetchRemotes(remotes).find(
737 (remote) =>
738 normalizeGitRemoteUrl(remote.url).split("/").slice(1).join("/") ===
739 nameWithOwner.toLowerCase(),
740 )?.name ?? null;
741 const baseRemote = Effect.suspend(() => {
742 const known = remoteFor(baseNameWithOwner);
743 return known === null ? git.resolvePrimaryRemoteName(input.cwd) : Effect.succeed(known);
744 });
745 // A fork's branch named like the base's default branch is checked out under the owner's
746 // prefix. Without the default branch that collision cannot be ruled out, and the checkout
747 // would reset the local default branch to the fork's commit, so it fails instead.
748 const defaultBranch = isCrossRepository
749 ? yield* readRepository(base).pipe(
750 Effect.map((repository) => repository.default_branch ?? null),
751 )
752 : null;
753 const localBranch = pullRequestCheckoutBranchName({
754 headRefName: pullRequest.headRefName,
755 headOwner,
756 isCrossRepository,
757 defaultBranch,
758 });
759​
760 /** The remote the head branch lives on; a fork the checkout does not know yet is added. */
761 const headRemote = Effect.gen(function* () {
762 if (!isCrossRepository) return yield* baseRemote;
763 if (headNameWithOwner === null) return yield* failure("The fork is gone.");
764 const known = remoteFor(headNameWithOwner);
765 if (known !== null) return known;
766 const [owner, name] = headNameWithOwner.split("/");
767 const fork = yield* readRepository({ host: base.host, owner: owner!, name: name! });
768 const originUrl = yield* git.readConfigValue(input.cwd, "remote.origin.url");
769 return yield* git.ensureRemote({
770 cwd: input.cwd,
771 preferredName: headOwner ?? "fork",
772 url: originUrl !== null && isSshRemoteUrl(originUrl) ? fork.ssh_url : fork.html_url,
773 });
774 });
775​
776 const exists = (yield* git
777 .listLocalBranchNames(input.cwd)
778 .pipe(Effect.mapError(gitFailure))).includes(localBranch);
779​
780 // The commit to check out, fetched from the head branch where it still exists.
781 const target = yield* Effect.gen(function* () {
782 const remoteName = yield* headRemote;
783 yield* git.fetchRemoteTrackingBranch({
784 cwd: input.cwd,
785 remoteName,
786 remoteBranch: pullRequest.headRefName,
787 });
788 return {
789 ref: `refs/remotes/${remoteName}/${pullRequest.headRefName}`,
790 upstream: { remoteName, remoteBranch: pullRequest.headRefName },
791 };
792 }).pipe(
793 Effect.catch(() =>
794 Effect.gen(function* () {
795 yield* runGit(input.cwd, "fetchPullRef", [
796 "fetch",
797 "--quiet",
798 "--no-tags",
799 yield* baseRemote,
800 `refs/pull/${pullRequest.number}/head`,
801 ]);
802 const { commitSha } = yield* git.resolveCommit({
803 cwd: input.cwd,
804 revision: "FETCH_HEAD",
805 });
806 return { ref: commitSha, upstream: null };
807 }),
808 ),
809 Effect.mapError(gitFailure),
810 );
811​
812 yield* Effect.gen(function* () {
813 if (!exists) yield* runGit(input.cwd, "branch", ["branch", localBranch, target.ref]);
814 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
815 if (exists) {
816 yield* runGit(
817 input.cwd,
818 "sync",
819 input.force === true
820 ? ["reset", "--hard", "--quiet", target.ref]
821 : ["merge", "--ff-only", "--quiet", target.ref],
822 );
823 }
824 // Tracking is set once the branch is the pull request's, so a sync that fails leaves an
825 // existing branch's upstream as it was.
826 if (target.upstream !== null) {
827 yield* git.setBranchUpstream({ cwd: input.cwd, branch: localBranch, ...target.upstream });
828 }
829 }).pipe(Effect.mapError(gitFailure));
830 },
831 );
832​
833 /** Reports a failure against the operation and request that made it, with transport-safe context. */
834 const providerError =
835 (
836 operation: string,
837 cwd: string,
838 context?: { readonly reference?: string; readonly repository?: string },
839 ) =>
840 (error: GitHubFailure) =>
841 new SourceControlProviderError({
842 provider: "github",
843 operation,
844 cwd,
845 ...(context?.reference === undefined
846 ? {}
847 : {
848 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
849 context.reference,
850 ),
851 }),
852 ...(context?.repository === undefined
853 ? {}
854 : {
855 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
856 context.repository,
857 ),
858 }),
859 detail: error.detail,
860 cause: error.cause,
861 });
862​
863 const readLinkSubject = Effect.fn("GitHubSourceControlProvider.readLinkSubject")(function* (
864 input: { readonly cwd: string; readonly url: URL },
865 endpoint: string,
866 ) {
867 const result = yield* api
868 .rest({
869 host: input.url.host,
870 operation: "resolveLink",
871 path: endpoint,
872 maxResponseBytes: 1_000_000,
873 })
874 .pipe(
875 Effect.timeout("3 seconds"),
876 Effect.mapError(
877 (cause) =>
878 new SourceControlProviderError({
879 provider: "github",
880 operation: "resolveLink",
881 cwd: input.cwd,
882 detail: "The linked subject could not be read.",
883 cause,
884 }),
885 ),
886 );
887 const subject = yield* decodeLinkSubject(result.body).pipe(
888 Effect.mapError(
889 (cause) =>
890 new SourceControlProviderError({
891 provider: "github",
892 operation: "resolveLink.decode",
893 cwd: input.cwd,
894 detail: "The linked subject could not be read.",
895 cause,
896 }),
897 ),
898 );
899 return { title: subject.title, body: subject.body ?? null };
900 });
901​
902 return SourceControlProvider.SourceControlProvider.of({
903 kind: "github",
904 resolveLink: (input) => {
905 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
906 if (input.url.host !== "github.com") return undefined;
907 const match = /^\/([\w.-]+)\/([\w.-]+)\/(?:pull|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
908 input.url.pathname,
909 );
910 if (!match) return undefined;
911 return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);
912 },
913 listChangeRequests: (input) =>
914 // An open lookup is a user waiting on a status; the rest may be a background sweep.
915 (input.state === "open" ? Effect.succeed(true) : GitHubApi.AllowGitHubReserve).pipe(
916 Effect.flatMap((allowReserve) =>
917 listByHead({
918 cwd: input.cwd,
919 headSelector: input.headSelector,
920 state: input.state,
921 limit: input.limit ?? (input.state === "open" ? 1 : 20),
922 host: contextHost(input.context),
923 allowReserve,
924 }),
925 ),
926 Effect.map((records) => records.map(toChangeRequest)),
927 Effect.mapError(
928 providerError("listChangeRequests", input.cwd, { reference: input.headSelector }),
929 ),
930 ),
931 getChangeRequest: (input) =>
932 readPullRequest({ ...input, host: contextHost(input.context) }).pipe(
933 Effect.map(toChangeRequest),
934 Effect.mapError(
935 providerError("getChangeRequest", input.cwd, { reference: input.reference }),
936 ),
937 ),
938 createChangeRequest: (input) =>
939 Effect.gen(function* () {
940 const locator = yield* resolveRepository({ cwd: input.cwd });
941 const body = yield* fileSystem
942 .readFileString(input.bodyFile)
943 .pipe(
944 Effect.mapError((cause) =>
945 failure("The pull request description could not be read.", cause),
946 ),
947 );
948 yield* rest({
949 host: locator.host,
950 operation: "createPullRequest",
951 method: "POST",
952 // A user's own write may spend the reserve the background leaves for it.
953 allowReserve: true,
954 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}/pulls`,
955 // `owner:branch` is how the REST API takes a fork's head, the same as `gh --head`.
956 // gh allows maintainer edits unless told otherwise; the API's default is not documented.
957 body: {
958 base: input.baseRefName,
959 head: input.headSelector,
960 title: input.title,
961 body,
962 maintainer_can_modify: true,
963 },
964 });
965 }).pipe(
966 Effect.mapError(
967 providerError("createChangeRequest", input.cwd, { reference: input.headSelector }),
968 ),
969 ),
970 getRepositoryCloneUrls: (input) =>
971 Effect.gen(function* () {
972 const fallbackHost = (yield* resolveRepository({ cwd: input.cwd }).pipe(
973 Effect.map((locator) => locator.host),
974 Effect.orElseSucceed(() => environment.GH_HOST ?? "github.com"),
975 )).toLowerCase();
976 const locator = parseGitHubRepositorySelector(input.repository, fallbackHost);
977 if (locator === null) return yield* failure("Repositories are named owner/name.");
978 return repositoryCloneUrls(yield* readRepository(locator));
979 }).pipe(
980 Effect.mapError(
981 providerError("getRepositoryCloneUrls", input.cwd, { repository: input.repository }),
982 ),
983 ),
984 createRepository: (input) =>
985 Effect.gen(function* () {
986 const locator = parseGitHubRepositorySelector(
987 input.repository,
988 (environment.GH_HOST ?? "github.com").toLowerCase(),
989 );
990 const viewer = locator === null ? null : yield* readViewerLogin(locator.host);
991 const owner = locator?.owner ?? viewer;
992 const name = locator?.name ?? input.repository.trim();
993 const host = locator?.host ?? (environment.GH_HOST?.trim().toLowerCase() || "github.com");
994 const isViewer = viewer !== null && owner?.toLowerCase() === viewer.toLowerCase();
995 const response = yield* rest(
996 {
997 host,
998 operation: "createRepository",
999 method: "POST",
1000 allowReserve: true,
1001 path:
1002 isViewer || owner === null ? "user/repos" : `orgs/${encodeURIComponent(owner)}/repos`,
1003 body: { name, private: input.visibility === "private" },
1004 },
1005 // GitHub answers 404 for an organization the account cannot create repositories in.
1006 `No organization named ${owner ?? "that"} that this account can create repositories in.`,
1007 );
1008 const decoded = decodeRawRepository(response.body);
1009 if (Result.isFailure(decoded)) {
1010 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
1012 return repositoryCloneUrls(decoded.success);
1013 }).pipe(
1014 Effect.mapError(
1015 providerError("createRepository", input.cwd, { repository: input.repository }),
1016 ),
1017 ),
1018 getDefaultBranch: (input) =>
1019 Effect.gen(function* () {
1020 const locator = yield* resolveRepository({
1021 cwd: input.cwd,
1022 host: contextHost(input.context),
1023 });
1024 const repository = yield* readRepository(locator);
1025 const branch = repository.default_branch?.trim() ?? "";
1026 return branch.length > 0 ? branch : null;
1027 }).pipe(Effect.mapError(providerError("getDefaultBranch", input.cwd))),
1028 checkoutChangeRequest: (input) =>
1029 checkoutPullRequest(input).pipe(
1030 Effect.mapError(
1031 providerError("checkoutChangeRequest", input.cwd, { reference: input.reference }),
1032 ),
1033 ),
1034 });
1035});