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

GitHubSourceControlProvider.ts

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