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

GitHubSourceControlProvider.ts

1,095 lines42.3 KB

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