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

GitHubSourceControlProvider.ts

1,118 lines42.4 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", cwd, 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: ({ cwd, context }) => {
309 const url = URL.parse(context.provider.baseUrl);
310 if (!url?.host) return Effect.succeed(null);
311 // A timeout or keyring failure propagates: the registry does not keep that answer.
312 return api.credential(url.host, { cwd }).pipe(
313 Effect.as(true),
314 Effect.catchTags({
315 GitHubCliMissingError: () => Effect.succeed(false),
316 GitHubHostDisabledError: () => Effect.succeed(true),
317 GitHubNotSignedInError: () => Effect.succeed(false),
318 }),
319 Effect.map((known) =>
320 known
321 ? ({
322 kind: SourceControlProviderKind.make("github"),
323 name: "GitHub Self-Hosted",
324 baseUrl: context.provider.baseUrl,
325 } as const)
326 : null,
327 ),
328 );
329 },
330 } satisfies SourceControlManagedCliDiscoverySpec;
331});
332​
333class GitHubFailure extends Schema.TaggedError<GitHubFailure>()("GitHubFailure", {
334 detail: Schema.String,
335 cause: Schema.Defect(),
336}) {}
337​
338const failure = (detail: string, cause?: unknown) => new GitHubFailure({ detail, cause });
339​
340const PULL_REQUEST_NOT_FOUND = "Pull request not found. Check the PR number or URL and try again.";
341const REPOSITORY_NOT_FOUND = "Repository not found. Check the owner and name and try again.";
342​
343function fromGitHubApiError(
344 error: GitHubRequestPolicy.GitHubApiError,
345 notFound = PULL_REQUEST_NOT_FOUND,
346): GitHubFailure {
347 switch (error._tag) {
348 case "GitHubCliMissingError":
349 return failure(
350 "No GitHub credential on the server. Set GH_TOKEN, or install the GitHub CLI and run `gh auth login`.",
351 error,
352 );
353 case "GitHubNotSignedInError":
354 case "GitHubHostDisabledError":
355 case "SettingsSecretUnresolvedError":
356 return failure(error.message, error);
357 case "GitHubApiAuthenticationError":
358 return failure(
359 "GitHub is not authenticated. Run `gh auth login` (or set GH_TOKEN) and retry.",
360 error,
361 );
362 case "GitHubApiRateLimitError":
363 case "SourceControlRateLimitPausedError":
364 return failure(
365 "GitHub API rate limit exceeded. Requests resume when the limit resets.",
366 error,
367 );
368 case "GitHubApiNotFoundError":
369 return failure(notFound, error);
370 case "GitHubCliFailedError":
371 case "GitHubAppSessionError":
372 case "GitHubApiResponseError":
373 case "GitHubApiRequestError":
374 return failure(error.message.trim() || "GitHub request failed.", error);
375 }
377​
378const notFound = (cause: string) => failure(PULL_REQUEST_NOT_FOUND, new Error(cause));
379​
380const RawRepositorySchema = Schema.Struct({
381 full_name: TrimmedNonEmptyString,
382 html_url: TrimmedNonEmptyString,
383 ssh_url: TrimmedNonEmptyString,
384 default_branch: Schema.optional(Schema.NullOr(Schema.String)),
385});
386const decodeRawRepository = decodeJsonResult(RawRepositorySchema);
387​
388function repositoryCloneUrls(
389 raw: Schema.Schema.Type<typeof RawRepositorySchema>,
390): SourceControlRepositoryCloneUrls {
391 return { nameWithOwner: raw.full_name, url: raw.html_url, sshUrl: raw.ssh_url };
393​
394const decodeViewerLogin = decodeJsonResult(Schema.Struct({ login: TrimmedNonEmptyString }));
395​
396type PullRequestListState = "open" | "closed" | "merged" | "all";
397​
398const GRAPHQL_STATES: Record<
399 PullRequestListState,
400 NonNullable<PullRequestsByHead.Variables["states"]>
401> = {
402 open: ["OPEN"],
403 closed: ["CLOSED"],
404 merged: ["MERGED"],
405 all: ["OPEN", "CLOSED", "MERGED"],
406};
407/** 50 lookups keeps responses near 0.5s at the same one-point cost as 100. */
408const HEAD_LOOKUPS_PER_DOCUMENT = 50;
409/** Git reads stagger background lookups by ~300ms; gather batches before spending quota. */
410const HEAD_LOOKUP_BATCH_WINDOW = "50 millis";
411const BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW = "500 millis";
412/** For heads matching 100 PRs each, 50 lookups approached GitHub's ~10s limit; 25 took ~7s. */
413const BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT = 25;
414const HEAD_LOOKUP_MAX_RESPONSE_BYTES = 16_000_000;
415const OWNER_HEAD_SCAN_LIMIT = 100;
416​
417function trimmed(value: string): string | null {
418 const text = value.trim();
419 return text.length > 0 ? text : null;
421​
422/** Null isolates unusable PRs from the rest of a listing. */
423function toPullRequestRecord(node: PullRequestNode): NormalizedGitHubPullRequestRecord | null {
424 const title = trimmed(node.title);
425 const url = trimmed(node.url);
426 const baseRefName = trimmed(node.baseRefName);
427 const headRefName = trimmed(node.headRefName);
428 const updatedAt = DateTime.make(node.updatedAt);
429 if (node.number < 1 || !title || !url || !baseRefName || !headRefName) return null;
430 if (Option.isNone(updatedAt)) return null;
431 return normalizeGitHubPullRequestRecord({
432 ...node,
433 title,
434 url,
435 baseRefName,
436 headRefName,
437 updatedAt: Option.some(DateTime.toUtc(updatedAt.value)),
438 });
440​
441export function pullRequestCheckoutBranchName(input: {
442 readonly headRefName: string;
443 readonly headOwner: string | null;
444 readonly isCrossRepository: boolean;
445 readonly defaultBranch: string | null;
446}): string {
447 return input.isCrossRepository &&
448 input.headOwner !== null &&
449 input.defaultBranch !== null &&
450 input.headRefName === input.defaultBranch
451 ? `${input.headOwner}/${input.headRefName}`
452 : input.headRefName;
454​
455const contextHost = (context: SourceControlProvider.SourceControlProviderContext | undefined) =>
456 context === undefined ? undefined : new URL(context.provider.baseUrl).host;
457​
458export const make = Effect.gen(function* () {
459 const api = yield* GitHubRest.GitHubRest;
460 const policy = yield* GitHubRequestPolicy.GitHubRequestPolicy;
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 resolveRepository = Effect.fn("GitHubSourceControlProvider.resolveRepository")(
478 function* (input: {
479 readonly cwd: string;
480 readonly host?: string | undefined;
481 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
482 }) {
483 const envRepository = environment.GH_REPO?.trim();
484 const hostHint = input.host ?? contextHost(input.context);
485 const defaultHost = (hostHint ?? environment.GH_HOST ?? "github.com").toLowerCase();
486 if (envRepository) {
487 const locator = parseGitHubRepositorySelector(envRepository, defaultHost);
488 if (locator !== null) return locator;
489 }
490 const [remotes, resolved] = yield* Effect.all([
491 gitRead(input.cwd, ["remote", "-v"]),
492 gitRead(input.cwd, ["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"]),
493 ]).pipe(Effect.orElseSucceed(() => [null, null] as const));
494 const { host, locator } = resolveGitHubRepository({
495 remotes: remotes?.exitCode === 0 ? remotes.stdout : "",
496 resolved: resolved?.exitCode === 0 ? resolved.stdout : "",
497 hostHint,
498 defaultHost,
499 });
500 if (locator !== null) return locator;
501 if (input.context) {
502 const remote = normalizeGitRemoteUrl(input.context.remoteUrl);
503 const fallback = parseGitHubRepositorySelector(
504 `${host}/${remote.slice(remote.indexOf("/") + 1)}`,
505 host,
506 );
507 if (fallback !== null) return fallback;
508 }
509 return yield* failure(
510 `No GitHub repository on ${host} was found among this checkout's git remotes.`,
511 );
512 },
513 );
514​
515 const client = yield* GraphQLClient.make(
516 GraphQLGroup.make(LenientPullRequestsByHead, PullRequestByNumber).middleware(
517 GitHubGraphQlClient.GitHubGraphQlAuth,
518 ),
519 ).pipe(Effect.provide(GitHubGraphQlClient.layer));
520​
521 const graphqlRead = <A, E, R>(
522 target: GitHubGraphQlClient.GitHubGraphQlTarget["Service"],
523 decodeDetail: string,
524 effect: Effect.Effect<A, E, R>,
525 ) =>
526 effect.pipe(
527 GitHubGraphQlClient.call(target),
528 Effect.mapError((error) =>
529 GraphQLClientError.isGraphQLClientError(error)
530 ? failure(decodeDetail, error)
531 : fromGitHubApiError(error as GitHubRequestPolicy.GitHubApiError),
532 ),
533 );
534​
535 const rest = (input: GitHubRest.GitHubRestInput, notFoundDetail?: string) =>
536 api.rest(input).pipe(Effect.mapError((error) => fromGitHubApiError(error, notFoundDetail)));
537​
538 // Batch by host/credential; isolate missing repositories and interactive/background reserves.
539 const headResolver = GraphQLResolver.aliased(client.PullRequestsByHead, {
540 batchKey: GitHubGraphQlClient.batchKey,
541 }).pipe(RequestResolver.batchN(HEAD_LOOKUPS_PER_DOCUMENT));
542 const interactiveHeadResolver = headResolver.pipe(
543 RequestResolver.setDelay(HEAD_LOOKUP_BATCH_WINDOW),
544 );
545 const backgroundHeadResolver = headResolver.pipe(
546 RequestResolver.batchN(BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT),
547 RequestResolver.setDelay(BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW),
548 );
549​
550 const listByHead = Effect.fn("GitHubSourceControlProvider.listByHead")(function* (input: {
551 readonly cwd: string;
552 readonly headSelector: string;
553 readonly state: PullRequestListState;
554 readonly limit: number;
555 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
556 readonly host?: string | undefined;
557 readonly allowReserve: boolean;
558 }) {
559 const locator = yield* resolveRepository(input);
560 const limit = Math.min(Math.max(Math.trunc(input.limit), 1), 100);
561 const ownerMatch = /^([^:/\s]+):(.+)$/u.exec(input.headSelector.trim());
562 const headRefName = ownerMatch?.[2] ?? input.headSelector.trim();
563 const result = yield* graphqlRead(
564 {
565 host: locator.host,
566 cwd: input.cwd,
567 operation: "listPullRequestsByHead",
568 allowReserve: input.allowReserve,
569 // 50 default-branch lookups can each match 100 fork PRs and exceed the usual cap.
570 maxResponseBytes: HEAD_LOOKUP_MAX_RESPONSE_BYTES,
571 },
572 "GitHub returned an invalid change request list.",
573 GitHubGraphQlClient.withCheckoutCredential(
574 policy.credential,
575 { cwd: input.cwd, host: locator.host },
576 GraphQLResolver.request(
577 {
578 owner: locator.owner,
579 name: locator.name,
580 head: headRefName,
581 states: GRAPHQL_STATES[input.state],
582 first: ownerMatch ? OWNER_HEAD_SCAN_LIMIT : limit,
583 },
584 input.allowReserve ? interactiveHeadResolver : backgroundHeadResolver,
585 ),
586 ),
587 );
588 if (result.repository === null) return yield* notFound("The repository could not be read.");
589 const rows = (result.repository.pullRequests.nodes ?? []).flatMap((entry) => {
590 const node = Option.getOrNull(decodePullRequestNode(entry));
591 const record = node === null ? null : toPullRequestRecord(node);
592 return record === null ? [] : [record];
593 });
594 if (!ownerMatch) return rows;
595 const headOwner = ownerMatch[1]!.toLowerCase();
596 return rows
597 .filter((row) => row.headRepositoryOwnerLogin?.toLowerCase() === headOwner)
598 .slice(0, limit);
599 });
600​
601 const readPullRequest = Effect.fn("GitHubSourceControlProvider.readPullRequest")(
602 function* (input: {
603 readonly cwd: string;
604 readonly reference: string;
605 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
606 readonly host?: string | undefined;
607 }) {
608 const parsed = parsePullRequestReference(input.reference);
609 if (parsed.kind === "branch") {
610 // `gh pr view <branch>` prefers an open pull request, then the newest of any state.
611 const lookup = (state: PullRequestListState) =>
612 listByHead({
613 cwd: input.cwd,
614 headSelector: parsed.headSelector,
615 state,
616 limit: 1,
617 host: input.host,
618 context: input.context,
619 allowReserve: true,
620 });
621 const [open] = yield* lookup("open");
622 const found = open ?? (yield* lookup("all"))[0];
623 if (found === undefined) return yield* notFound("No pull request has this head branch.");
624 return found;
625 }
626 const locator = parsed.kind === "url" ? parsed.locator : yield* resolveRepository(input);
627 const decodeDetail = "GitHub returned an invalid pull request.";
628 const result = yield* graphqlRead(
629 { host: locator.host, cwd: input.cwd, operation: "getPullRequest", allowReserve: true },
630 decodeDetail,
631 client.PullRequestByNumber({
632 owner: locator.owner,
633 name: locator.name,
634 number: parsed.number,
635 }),
636 );
637 const node = result.repository?.pullRequest;
638 if (node == null) return yield* notFound("The pull request does not exist.");
639 const record = toPullRequestRecord(node);
640 if (record === null)
641 return yield* failure(decodeDetail, new Error("Malformed pull request."));
642 return record;
643 },
644 );
645​
646 const readRepository = Effect.fn("GitHubSourceControlProvider.readRepository")(function* (
647 cwd: string,
648 locator: GitHubRepositoryLocator,
649 ) {
650 const response = yield* rest(
651 {
652 host: locator.host,
653 cwd,
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 cwd: string,
669 host: string,
670 ) {
671 const response = yield* rest({
672 host,
673 cwd,
674 operation: "getViewer",
675 path: "user",
676 allowReserve: true,
677 });
678 const decoded = decodeViewerLogin(response.body);
679 if (Result.isFailure(decoded)) {
680 return yield* failure("GitHub request failed.", decoded.failure);
681 }
682 return decoded.success.login;
683 });
684​
685 // Keep paths, argv and stderr in cause; expose only a fixed checkout error to clients.
686 const gitFailure = (cause: unknown) =>
687 failure("The pull request could not be checked out with git.", cause);
688​
689 const runGit = (cwd: string, operation: string, args: ReadonlyArray<string>) =>
690 git.execute({
691 operation: `GitHubSourceControlProvider.checkoutPullRequest.${operation}`,
692 cwd,
693 args,
694 });
695​
696 const checkoutPullRequest = Effect.fn("GitHubSourceControlProvider.checkoutPullRequest")(
697 function* (input: {
698 readonly cwd: string;
699 readonly reference: string;
700 readonly force?: boolean;
701 readonly context?: SourceControlProvider.SourceControlProviderContext;
702 }) {
703 const reference = parsePullRequestReference(input.reference);
704 const pullRequest = yield* readPullRequest(input);
705 const base = reference.kind === "url" ? reference.locator : yield* resolveRepository(input);
706 const baseNameWithOwner = `${base.owner}/${base.name}`.toLowerCase();
707 const headNameWithOwner = pullRequest.headRepositoryNameWithOwner ?? null;
708 const isCrossRepository =
709 pullRequest.isCrossRepository ??
710 (headNameWithOwner !== null && headNameWithOwner.toLowerCase() !== baseNameWithOwner);
711 const headOwner =
712 pullRequest.headRepositoryOwnerLogin ?? headNameWithOwner?.split("/")[0] ?? null;
713​
714 const remotes = yield* gitRead(input.cwd, ["remote", "-v"]).pipe(
715 Effect.map((result) => (result.exitCode === 0 ? result.stdout : "")),
716 Effect.mapError(gitFailure),
717 );
718 const remoteFor = (nameWithOwner: string) =>
719 parseFetchRemotes(remotes).find(
720 (remote) =>
721 (gitHubApiHostForRemote(remote.url) ??
722 normalizeGitRemoteUrl(remote.url).split("/")[0]) === base.host &&
723 normalizeGitRemoteUrl(remote.url).split("/").slice(1).join("/") ===
724 nameWithOwner.toLowerCase(),
725 )?.name ?? null;
726 const baseRemote = Effect.suspend(() => {
727 const known = remoteFor(baseNameWithOwner);
728 return known === null ? git.resolvePrimaryRemoteName(input.cwd) : Effect.succeed(known);
729 });
730 // Avoid resetting the default branch; prefix colliding forks and fail if it is unknown.
731 const defaultBranch = isCrossRepository
732 ? yield* readRepository(input.cwd, base).pipe(
733 Effect.map((repository) => repository.default_branch ?? null),
734 )
735 : null;
736 const localBranch = pullRequestCheckoutBranchName({
737 headRefName: pullRequest.headRefName,
738 headOwner,
739 isCrossRepository,
740 defaultBranch,
741 });
742​
743 const headRemote = Effect.gen(function* () {
744 if (!isCrossRepository) return yield* baseRemote;
745 if (headNameWithOwner === null) return yield* failure("The fork is gone.");
746 const known = remoteFor(headNameWithOwner);
747 if (known !== null) return known;
748 const [owner, name] = headNameWithOwner.split("/");
749 const fork = yield* readRepository(input.cwd, {
750 host: base.host,
751 owner: owner!,
752 name: name!,
753 });
754 const originUrl = yield* git.readConfigValue(input.cwd, "remote.origin.url");
755 return yield* git.ensureRemote({
756 cwd: input.cwd,
757 preferredName: headOwner ?? "fork",
758 url: originUrl !== null && isSshRemoteUrl(originUrl) ? fork.ssh_url : fork.html_url,
759 });
760 });
761​
762 const exists = (yield* git
763 .listLocalBranchNames(input.cwd)
764 .pipe(Effect.mapError(gitFailure))).includes(localBranch);
765​
766 const target = yield* Effect.gen(function* () {
767 const remoteName = yield* headRemote;
768 yield* git.fetchRemoteTrackingBranch({
769 cwd: input.cwd,
770 remoteName,
771 remoteBranch: pullRequest.headRefName,
772 });
773 return {
774 ref: `refs/remotes/${remoteName}/${pullRequest.headRefName}`,
775 upstream: { remoteName, remoteBranch: pullRequest.headRefName },
776 };
777 }).pipe(
778 Effect.catch(() =>
779 Effect.gen(function* () {
780 yield* runGit(input.cwd, "fetchPullRef", [
781 "fetch",
782 "--quiet",
783 "--no-tags",
784 "--",
785 yield* baseRemote,
786 `refs/pull/${pullRequest.number}/head`,
787 ]);
788 const { commitSha } = yield* git.resolveCommit({
789 cwd: input.cwd,
790 revision: "FETCH_HEAD",
791 });
792 return { ref: commitSha, upstream: null };
793 }),
794 ),
795 Effect.mapError(gitFailure),
796 );
797​
798 yield* Effect.gen(function* () {
799 if (!exists) {
800 yield* git.createBranch({ cwd: input.cwd, branch: localBranch, startPoint: target.ref });
801 }
802 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
803 if (exists) {
804 yield* runGit(
805 input.cwd,
806 "sync",
807 input.force === true
808 ? ["reset", "--hard", "--quiet", target.ref]
809 : ["merge", "--ff-only", "--quiet", target.ref],
810 );
811 }
812 // Set tracking after sync succeeds so a failed checkout preserves the existing upstream.
813 if (target.upstream !== null) {
814 yield* git.setBranchUpstream({ cwd: input.cwd, branch: localBranch, ...target.upstream });
815 }
816 }).pipe(Effect.mapError(gitFailure));
817 },
818 );
819​
820 const providerError =
821 (
822 operation: string,
823 cwd: string,
824 context?: { readonly reference?: string; readonly repository?: string },
825 ) =>
826 (error: GitHubFailure) =>
827 new SourceControlProviderError({
828 provider: SourceControlProviderKind.make("github"),
829 operation,
830 cwd,
831 ...(context?.reference === undefined
832 ? {}
833 : {
834 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
835 context.reference,
836 ),
837 }),
838 ...(context?.repository === undefined
839 ? {}
840 : {
841 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
842 context.repository,
843 ),
844 }),
845 detail: error.detail,
846 cause: error.cause,
847 });
848​
849 const readLinkSubject = Effect.fn("GitHubSourceControlProvider.readLinkSubject")(function* (
850 input: { readonly cwd: string; readonly url: URL },
851 endpoint: string,
852 ) {
853 const result = yield* api
854 .rest({
855 host: input.url.host,
856 cwd: input.cwd,
857 operation: "resolveLink",
858 path: endpoint,
859 maxResponseBytes: 1_000_000,
860 })
861 .pipe(
862 Effect.timeout("3 seconds"),
863 Effect.mapError(
864 (cause) =>
865 new SourceControlProviderError({
866 provider: SourceControlProviderKind.make("github"),
867 operation: "resolveLink",
868 cwd: input.cwd,
869 detail: "The linked subject could not be read.",
870 cause,
871 }),
872 ),
873 );
874 const subject = yield* decodeLinkSubject(result.body).pipe(
875 Effect.mapError(
876 (cause) =>
877 new SourceControlProviderError({
878 provider: SourceControlProviderKind.make("github"),
879 operation: "resolveLink.decode",
880 cwd: input.cwd,
881 detail: "The linked subject could not be read.",
882 cause,
883 }),
884 ),
885 );
886 return { title: subject.title, body: subject.body ?? null };
887 });
888​
889 return SourceControlProvider.SourceControlProvider.of({
890 kind: SourceControlProviderKind.make("github"),
891 resolveRemoteWebHost: Effect.fn("GitHubSourceControlProvider.resolveRemoteWebHost")(
892 ({ context }) => Effect.succeed(gitHubApiHostForRemote(context.remoteUrl)),
893 ),
894 // GitHub matches bare heads; read a full page to disambiguate forks by owner.
895 headBranchProbe: ({ headSelectors }) => ({
896 headSelectors: headSelectors.filter((selector) => !selector.includes(":")),
897 limit: 100,
898 }),
899 readChangeRequestTemplate: Effect.fn("GitHubSourceControlProvider.readChangeRequestTemplate")(
900 function ({ cwd, treeish }) {
901 return GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute);
902 },
903 ),
904 // `createChangeRequest` targets what `resolveRepository` picks: GH_REPO when it parses, else
905 // the remote `gh repo set-default` marked (`gh-resolved`). An HTTPS remote keeps a
906 // non-default port in the context's host, and the mark is then ignored.
907 createsChangeRequestsIn: Effect.fn("GitHubSourceControlProvider.createsChangeRequestsIn")(
908 function* ({ cwd, context, repository }) {
909 const host = URL.canParse(context.provider.baseUrl)
910 ? new URL(context.provider.baseUrl).host
911 : null;
912 const target = repository?.toLowerCase();
913 const fromEnvironment = parseGitHubRepositorySelector(
914 environment.GH_REPO ?? "",
915 host ?? "",
916 );
917 if (fromEnvironment !== null) {
918 const { host: targetHost, owner, name } = fromEnvironment;
919 return (
920 host !== null &&
921 URL.canParse(`https://${targetHost}`) &&
922 new URL(`https://${targetHost}`).host === host &&
923 `${owner}/${name}`.toLowerCase() === target
924 );
925 }
926 const mark = yield* git
927 .readConfigValue(cwd, `remote.${context.remoteName}.gh-resolved`)
928 .pipe(Effect.orElseSucceed(() => null));
929 const { locator } = resolveGitHubRepository({
930 remotes: `${context.remoteName}\t${context.remoteUrl} (fetch)`,
931 resolved: mark === null ? "" : `remote.${context.remoteName}.gh-resolved ${mark}`,
932 hostHint: host ?? undefined,
933 defaultHost: host ?? "github.com",
934 });
935 return locator === null || `${locator.owner}/${locator.name}`.toLowerCase() === target;
936 },
937 ),
938 // `gh pr create` run in the checkout, as an agent in a T3 worktree often does, takes its base
939 // from this key.
940 recordBranchBase: Effect.fn("GitHubSourceControlProvider.recordBranchBase")(function ({
941 cwd,
942 branch,
943 baseBranch,
944 }) {
945 return git
946 .writeConfigValue({ cwd, key: `branch.${branch}.gh-merge-base`, value: baseBranch })
947 .pipe(
948 Effect.catch((cause) =>
949 Effect.logWarning("Could not record the branch base for gh", { cause }),
950 ),
951 );
952 }),
953 resolveLink: (input) => {
954 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
955 if (input.url.host !== "github.com") return undefined;
956 const match = /^\/([\w.-]+)\/([\w.-]+)\/(?:pull|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
957 input.url.pathname,
958 );
959 if (!match) return undefined;
960 return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);
961 },
962 listChangeRequests: Effect.fn("GitHubSourceControlProvider.listChangeRequests")(
963 function (input) {
964 return (
965 input.state === "open" ? Effect.succeed(true) : SourceControlRateLimit.Interactive
966 ).pipe(
967 Effect.flatMap((allowReserve) =>
968 listByHead({
969 cwd: input.cwd,
970 headSelector: input.headSelector,
971 state: input.state,
972 limit: input.limit ?? (input.state === "open" ? 1 : 20),
973 host: contextHost(input.context),
974 context: input.context,
975 allowReserve,
976 }),
977 ),
978 Effect.map((records) => records.map(toChangeRequest)),
979 Effect.mapError(
980 providerError("listChangeRequests", input.cwd, { reference: input.headSelector }),
981 ),
982 );
983 },
984 ),
985 getChangeRequest: Effect.fn("GitHubSourceControlProvider.getChangeRequest")(function (input) {
986 return readPullRequest({ ...input, host: contextHost(input.context) }).pipe(
987 Effect.map(toChangeRequest),
988 Effect.mapError(
989 providerError("getChangeRequest", input.cwd, { reference: input.reference }),
990 ),
991 );
992 }),
993 createChangeRequest: Effect.fn("GitHubSourceControlProvider.createChangeRequest")(
994 function* (input) {
995 const locator = yield* resolveRepository(input);
996 const body = yield* fileSystem
997 .readFileString(input.bodyFile)
998 .pipe(
999 Effect.mapError((cause) =>
1000 failure("The pull request description could not be read.", cause),
1001 ),
1002 );
1003 yield* rest({
1004 host: locator.host,
1005 cwd: input.cwd,
1006 operation: "createPullRequest",
1007 method: "POST",
1008 allowReserve: true,
1009 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}/pulls`,
1010 // Explicitly allow maintainer edits to match gh; the API default is undocumented.
1011 body: {
1012 base: input.baseRefName,
1013 head: input.headSelector,
1014 title: input.title,
1015 body,
1016 maintainer_can_modify: true,
1017 },
1018 });
1019 },
1020 (effect, input) =>
1021 effect.pipe(
1022 Effect.mapError(
1023 providerError("createChangeRequest", input.cwd, { reference: input.headSelector }),
1024 ),
1025 ),
1026 ),
1027 getRepositoryCloneUrls: Effect.fn("GitHubSourceControlProvider.getRepositoryCloneUrls")(
1028 function* (input) {
1029 const fallbackHost = (
1030 input.host ??
1031 (yield* resolveRepository(input).pipe(
1032 Effect.map((locator) => locator.host),
1033 Effect.orElseSucceed(() => environment.GH_HOST ?? "github.com"),
1034 ))
1035 ).toLowerCase();
1036 const bareName = input.repository.trim().replace(/\.git$/i, "");
1037 const locator =
1038 parseGitHubRepositorySelector(input.repository, fallbackHost) ??
1039 (/^[^/\s]+$/.test(bareName)
1040 ? {
1041 host: fallbackHost,
1042 owner: yield* readViewerLogin(input.cwd, fallbackHost),
1043 name: bareName,
1045 : null);
1046 if (locator === null) return yield* failure("Repositories are named owner/name.");
1047 return repositoryCloneUrls(yield* readRepository(input.cwd, locator));
1048 },
1049 (effect, input) =>
1050 effect.pipe(
1051 Effect.mapError(
1052 providerError("getRepositoryCloneUrls", input.cwd, {
1053 repository: input.repository,
1054 }),
1055 ),
1056 ),
1057 ),
1058 createRepository: Effect.fn("GitHubSourceControlProvider.createRepository")(
1059 function* (input) {
1060 const locator = parseGitHubRepositorySelector(
1061 input.repository,
1062 (environment.GH_HOST ?? "github.com").toLowerCase(),
1063 );
1064 const viewer = locator === null ? null : yield* readViewerLogin(input.cwd, locator.host);
1065 const owner = locator?.owner ?? viewer;
1066 const name = locator?.name ?? input.repository.trim();
1067 const host = locator?.host ?? (environment.GH_HOST?.trim().toLowerCase() || "github.com");
1068 const isViewer = viewer !== null && owner?.toLowerCase() === viewer.toLowerCase();
1069 const response = yield* rest(
1071 host,
1072 cwd: input.cwd,
1073 operation: "createRepository",
1074 method: "POST",
1075 allowReserve: true,
1076 path:
1077 isViewer || owner === null ? "user/repos" : `orgs/${encodeURIComponent(owner)}/repos`,
1078 body: { name, private: input.visibility === "private" },
1079 },
1080 `No organization named ${owner ?? "that"} that this account can create repositories in.`,
1081 );
1082 const decoded = decodeRawRepository(response.body);
1083 if (Result.isFailure(decoded)) {
1084 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
1086 return repositoryCloneUrls(decoded.success);
1087 },
1088 (effect, input) =>
1089 effect.pipe(
1090 Effect.mapError(
1091 providerError("createRepository", input.cwd, { repository: input.repository }),
1092 ),
1093 ),
1094 ),
1095 getDefaultBranch: Effect.fn("GitHubSourceControlProvider.getDefaultBranch")(
1096 function* (input) {
1097 const locator = yield* resolveRepository({
1098 cwd: input.cwd,
1099 host: contextHost(input.context),
1100 context: input.context,
1101 });
1102 const repository = yield* readRepository(input.cwd, locator);
1103 const branch = repository.default_branch?.trim() ?? "";
1104 return branch.length > 0 ? branch : null;
1105 },
1106 (effect, input) => effect.pipe(Effect.mapError(providerError("getDefaultBranch", input.cwd))),
1107 ),
1108 checkoutChangeRequest: Effect.fn("GitHubSourceControlProvider.checkoutChangeRequest")(
1109 function (input) {
1110 return checkoutPullRequest(input).pipe(
1111 Effect.mapError(
1112 providerError("checkoutChangeRequest", input.cwd, { reference: input.reference }),
1113 ),
1114 );
1115 },
1116 ),
1117 });
1118});