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

GitHubSourceControlProvider.ts

1,106 lines41.9 KB

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