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

GitHubSourceControlProvider.ts

1,195 lines45.1 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​
397const decodeRestPullRequests = decodeJsonResult(Schema.Array(Schema.Unknown));
398const decodeRestPullRequest = Schema.decodeUnknownOption(
399 Schema.Struct({
400 number: Schema.Number,
401 title: Schema.String,
402 html_url: Schema.String,
403 state: Schema.String,
404 draft: Schema.optional(Schema.Boolean),
405 merged_at: Schema.NullOr(Schema.String),
406 closed_at: Schema.NullOr(Schema.String),
407 updated_at: Schema.String,
408 base: Schema.Struct({ ref: Schema.String, repo: Schema.Struct({ full_name: Schema.String }) }),
409 head: Schema.Struct({
410 ref: Schema.String,
411 sha: Schema.String,
412 repo: Schema.NullOr(
413 Schema.Struct({
414 name: Schema.String,
415 full_name: Schema.String,
416 owner: Schema.Struct({ login: Schema.String, type: Schema.String }),
417 }),
418 ),
419 }),
420 }),
421);
422​
423/** Reshapes a REST pull request into the GraphQL node so both decode the same way. */
424function restPullRequestNode(entry: unknown) {
425 const pr = Option.getOrNull(decodeRestPullRequest(entry));
426 if (pr === null) return null;
427 return {
428 number: pr.number,
429 title: pr.title,
430 url: pr.html_url,
431 baseRefName: pr.base.ref,
432 headRefName: pr.head.ref,
433 headRefOid: pr.head.sha,
434 state: pr.merged_at === null ? pr.state.toUpperCase() : "MERGED",
435 isDraft: pr.draft === true,
436 mergedAt: pr.merged_at,
437 closedAt: pr.closed_at,
438 updatedAt: pr.updated_at,
439 isCrossRepository: pr.head.repo?.full_name !== pr.base.repo.full_name,
440 headRepository: pr.head.repo && {
441 name: pr.head.repo.name,
442 nameWithOwner: pr.head.repo.full_name,
443 },
444 headRepositoryOwner: pr.head.repo && {
445 __typename: pr.head.repo.owner.type,
446 login: pr.head.repo.owner.login,
447 },
448 };
450​
451type PullRequestListState = "open" | "closed" | "merged" | "all";
452​
453const GRAPHQL_STATES: Record<
454 PullRequestListState,
455 NonNullable<PullRequestsByHead.Variables["states"]>
456> = {
457 open: ["OPEN"],
458 closed: ["CLOSED"],
459 merged: ["MERGED"],
460 all: ["OPEN", "CLOSED", "MERGED"],
461};
462/** 50 lookups keeps responses near 0.5s at the same one-point cost as 100. */
463const HEAD_LOOKUPS_PER_DOCUMENT = 50;
464/** Git reads stagger background lookups by ~300ms; gather batches before spending quota. */
465const HEAD_LOOKUP_BATCH_WINDOW = "50 millis";
466const BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW = "500 millis";
467/** For heads matching 100 PRs each, 50 lookups approached GitHub's ~10s limit; 25 took ~7s. */
468const BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT = 25;
469const HEAD_LOOKUP_MAX_RESPONSE_BYTES = 16_000_000;
470const OWNER_HEAD_SCAN_LIMIT = 100;
471​
472function trimmed(value: string): string | null {
473 const text = value.trim();
474 return text.length > 0 ? text : null;
476​
477/** Null isolates unusable PRs from the rest of a listing. */
478function toPullRequestRecord(node: PullRequestNode): NormalizedGitHubPullRequestRecord | null {
479 const title = trimmed(node.title);
480 const url = trimmed(node.url);
481 const baseRefName = trimmed(node.baseRefName);
482 const headRefName = trimmed(node.headRefName);
483 const updatedAt = DateTime.make(node.updatedAt);
484 if (node.number < 1 || !title || !url || !baseRefName || !headRefName) return null;
485 if (Option.isNone(updatedAt)) return null;
486 return normalizeGitHubPullRequestRecord({
487 ...node,
488 title,
489 url,
490 baseRefName,
491 headRefName,
492 updatedAt: Option.some(DateTime.toUtc(updatedAt.value)),
493 });
495​
496export function pullRequestCheckoutBranchName(input: {
497 readonly headRefName: string;
498 readonly headOwner: string | null;
499 readonly isCrossRepository: boolean;
500 readonly defaultBranch: string | null;
501}): string {
502 return input.isCrossRepository &&
503 input.headOwner !== null &&
504 input.defaultBranch !== null &&
505 input.headRefName === input.defaultBranch
506 ? `${input.headOwner}/${input.headRefName}`
507 : input.headRefName;
509​
510const contextHost = (context: SourceControlProvider.SourceControlProviderContext | undefined) =>
511 context === undefined ? undefined : new URL(context.provider.baseUrl).host;
512​
513export const make = Effect.gen(function* () {
514 const api = yield* GitHubRest.GitHubRest;
515 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
516 const process = sourceControlHost.process;
517 const environment = yield* HostProcess.Environment;
518 const git = sourceControlHost.git;
519 const fileSystem = yield* FileSystem.FileSystem;
520​
521 const gitRead = (cwd: string, args: ReadonlyArray<string>) =>
522 process.run({
523 operation: "GitHubSourceControlProvider.resolveRepository",
524 command: "git",
525 args,
526 cwd,
527 allowNonZeroExit: true,
528 timeoutMs: 5_000,
529 });
530​
531 const readRemotes = (cwd: string) =>
532 Effect.all([
533 gitRead(cwd, ["remote", "-v"]),
534 gitRead(cwd, ["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"]),
535 ]).pipe(
536 Effect.orElseSucceed(() => [null, null] as const),
537 Effect.map(([remotes, resolved]) => ({
538 remotes: remotes?.exitCode === 0 ? remotes.stdout : "",
539 resolved: resolved?.exitCode === 0 ? resolved.stdout : "",
540 })),
541 );
542​
543 const resolveRepository = Effect.fn("GitHubSourceControlProvider.resolveRepository")(
544 function* (input: {
545 readonly cwd: string;
546 readonly host?: string | undefined;
547 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
548 }) {
549 const envRepository = environment.GH_REPO?.trim();
550 const hostHint = input.host ?? contextHost(input.context);
551 const defaultHost = (hostHint ?? environment.GH_HOST ?? "github.com").toLowerCase();
552 if (envRepository) {
553 const locator = parseGitHubRepositorySelector(envRepository, defaultHost);
554 if (locator !== null) return locator;
555 }
556 const { host, locator } = resolveGitHubRepository({
557 ...(yield* readRemotes(input.cwd)),
558 hostHint,
559 defaultHost,
560 });
561 if (locator !== null) return locator;
562 if (input.context) {
563 const remote = normalizeGitRemoteUrl(input.context.remoteUrl);
564 const fallback = parseGitHubRepositorySelector(
565 `${host}/${remote.slice(remote.indexOf("/") + 1)}`,
566 host,
567 );
568 if (fallback !== null) return fallback;
569 }
570 return yield* failure(
571 `No GitHub repository on ${host} was found among this checkout's git remotes.`,
572 );
573 },
574 );
575​
576 const client = yield* GraphQLClient.make(
577 GraphQLGroup.make(LenientPullRequestsByHead, PullRequestByNumber).middleware(
578 GitHubGraphQlClient.GitHubGraphQlAuth,
579 ),
580 ).pipe(Effect.provide(GitHubGraphQlClient.layer));
581​
582 const graphqlRead = <A, E, R>(
583 target: GitHubGraphQlClient.GitHubGraphQlTarget["Service"],
584 decodeDetail: string,
585 effect: Effect.Effect<A, E, R>,
586 ) =>
587 effect.pipe(
588 GitHubGraphQlClient.call(target),
589 Effect.mapError((error) =>
590 GraphQLClientError.isGraphQLClientError(error)
591 ? failure(decodeDetail, error)
592 : fromGitHubApiError(error as GitHubRequestPolicy.GitHubApiError),
593 ),
594 );
595​
596 const rest = (input: GitHubRest.GitHubRestInput, notFoundDetail?: string) =>
597 api.rest(input).pipe(Effect.mapError((error) => fromGitHubApiError(error, notFoundDetail)));
598​
599 // Batch by host/credential; isolate missing repositories and interactive/background reserves.
600 const headResolver = GraphQLResolver.aliased(client.PullRequestsByHead, {
601 batchKey: GitHubGraphQlClient.batchKey,
602 }).pipe(RequestResolver.batchN(HEAD_LOOKUPS_PER_DOCUMENT));
603 const interactiveHeadResolver = headResolver.pipe(
604 RequestResolver.setDelay(HEAD_LOOKUP_BATCH_WINDOW),
605 );
606 const backgroundHeadResolver = headResolver.pipe(
607 RequestResolver.batchN(BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT),
608 RequestResolver.setDelay(BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW),
609 );
610​
611 const listByHead = Effect.fn("GitHubSourceControlProvider.listByHead")(function* (input: {
612 readonly cwd: string;
613 readonly headSelector: string;
614 readonly state: PullRequestListState;
615 readonly limit: number;
616 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
617 readonly host?: string | undefined;
618 readonly allowReserve: boolean;
619 }) {
620 const locator = yield* resolveRepository(input);
621 const limit = Math.min(Math.max(Math.trunc(input.limit), 1), 100);
622 const ownerMatch = /^([^:/\s]+):(.+)$/u.exec(input.headSelector.trim());
623 const headRefName = ownerMatch?.[2] ?? input.headSelector.trim();
624 if (ownerMatch) {
625 // GraphQL cannot filter heads by owner, and names like a fork's `main` match thousands.
626 const query = new URLSearchParams({
627 head: `${ownerMatch[1]}:${headRefName}`,
628 state: input.state === "all" || input.state === "open" ? input.state : "closed",
629 sort: "created",
630 direction: "desc",
631 per_page: String(OWNER_HEAD_SCAN_LIMIT),
632 });
633 const response = yield* rest({
634 host: locator.host,
635 operation: "listPullRequestsByHead",
636 allowReserve: input.allowReserve,
637 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}/pulls?${query}`,
638 });
639 const decoded = decodeRestPullRequests(response.body);
640 if (Result.isFailure(decoded)) {
641 return yield* failure("GitHub returned an invalid change request list.", decoded.failure);
642 }
643 return decoded.success
644 .flatMap((entry) => {
645 const node = Option.getOrNull(decodePullRequestNode(restPullRequestNode(entry)));
646 const record = node === null ? null : toPullRequestRecord(node);
647 return record === null ? [] : [record];
648 })
649 .filter((row) => input.state === "all" || row.state === input.state)
650 .slice(0, limit);
651 }
652 const result = yield* graphqlRead(
653 {
654 host: locator.host,
655 operation: "listPullRequestsByHead",
656 allowReserve: input.allowReserve,
657 // 50 default-branch lookups can each match 100 fork PRs and exceed the usual cap.
658 maxResponseBytes: HEAD_LOOKUP_MAX_RESPONSE_BYTES,
659 },
660 "GitHub returned an invalid change request list.",
661 GraphQLResolver.request(
662 {
663 owner: locator.owner,
664 name: locator.name,
665 head: headRefName,
666 states: GRAPHQL_STATES[input.state],
667 first: limit,
668 },
669 input.allowReserve ? interactiveHeadResolver : backgroundHeadResolver,
670 ),
671 );
672 if (result.repository === null) return yield* notFound("The repository could not be read.");
673 return (result.repository.pullRequests.nodes ?? []).flatMap((entry) => {
674 const node = Option.getOrNull(decodePullRequestNode(entry));
675 const record = node === null ? null : toPullRequestRecord(node);
676 return record === null ? [] : [record];
677 });
678 });
679​
680 const readPullRequest = Effect.fn("GitHubSourceControlProvider.readPullRequest")(
681 function* (input: {
682 readonly cwd: string;
683 readonly reference: string;
684 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
685 readonly host?: string | undefined;
686 }) {
687 const parsed = parsePullRequestReference(input.reference);
688 if (parsed.kind === "branch") {
689 // `gh pr view <branch>` prefers an open pull request, then the newest of any state.
690 const lookup = (state: PullRequestListState) =>
691 listByHead({
692 cwd: input.cwd,
693 headSelector: parsed.headSelector,
694 state,
695 limit: 1,
696 host: input.host,
697 context: input.context,
698 allowReserve: true,
699 });
700 const [open] = yield* lookup("open");
701 const found = open ?? (yield* lookup("all"))[0];
702 if (found === undefined) return yield* notFound("No pull request has this head branch.");
703 return found;
704 }
705 const locator = parsed.kind === "url" ? parsed.locator : yield* resolveRepository(input);
706 const decodeDetail = "GitHub returned an invalid pull request.";
707 const result = yield* graphqlRead(
708 { host: locator.host, operation: "getPullRequest", allowReserve: true },
709 decodeDetail,
710 client.PullRequestByNumber({
711 owner: locator.owner,
712 name: locator.name,
713 number: parsed.number,
714 }),
715 );
716 const node = result.repository?.pullRequest;
717 if (node == null) return yield* notFound("The pull request does not exist.");
718 const record = toPullRequestRecord(node);
719 if (record === null)
720 return yield* failure(decodeDetail, new Error("Malformed pull request."));
721 return record;
722 },
723 );
724​
725 const readRepository = Effect.fn("GitHubSourceControlProvider.readRepository")(function* (
726 locator: GitHubRepositoryLocator,
727 ) {
728 const response = yield* rest(
729 {
730 host: locator.host,
731 operation: "getRepository",
732 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}`,
733 allowReserve: true,
734 },
735 REPOSITORY_NOT_FOUND,
736 );
737 const decoded = decodeRawRepository(response.body);
738 if (Result.isFailure(decoded)) {
739 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
740 }
741 return decoded.success;
742 });
743​
744 const readViewerLogin = Effect.fn("GitHubSourceControlProvider.readViewerLogin")(function* (
745 host: string,
746 ) {
747 const response = yield* rest({
748 host,
749 operation: "getViewer",
750 path: "user",
751 allowReserve: true,
752 });
753 const decoded = decodeViewerLogin(response.body);
754 if (Result.isFailure(decoded)) {
755 return yield* failure("GitHub request failed.", decoded.failure);
756 }
757 return decoded.success.login;
758 });
759​
760 // Keep paths, argv and stderr in cause; expose only a fixed checkout error to clients.
761 const gitFailure = (cause: unknown) =>
762 failure("The pull request could not be checked out with git.", cause);
763​
764 const runGit = (cwd: string, operation: string, args: ReadonlyArray<string>) =>
765 git.execute({
766 operation: `GitHubSourceControlProvider.checkoutPullRequest.${operation}`,
767 cwd,
768 args,
769 });
770​
771 const checkoutPullRequest = Effect.fn("GitHubSourceControlProvider.checkoutPullRequest")(
772 function* (input: {
773 readonly cwd: string;
774 readonly reference: string;
775 readonly force?: boolean;
776 readonly context?: SourceControlProvider.SourceControlProviderContext;
777 }) {
778 const reference = parsePullRequestReference(input.reference);
779 const pullRequest = yield* readPullRequest(input);
780 const base = reference.kind === "url" ? reference.locator : yield* resolveRepository(input);
781 const baseNameWithOwner = `${base.owner}/${base.name}`.toLowerCase();
782 const headNameWithOwner = pullRequest.headRepositoryNameWithOwner ?? null;
783 const isCrossRepository =
784 pullRequest.isCrossRepository ??
785 (headNameWithOwner !== null && headNameWithOwner.toLowerCase() !== baseNameWithOwner);
786 const headOwner =
787 pullRequest.headRepositoryOwnerLogin ?? headNameWithOwner?.split("/")[0] ?? null;
788​
789 const remotes = yield* gitRead(input.cwd, ["remote", "-v"]).pipe(
790 Effect.map((result) => (result.exitCode === 0 ? result.stdout : "")),
791 Effect.mapError(gitFailure),
792 );
793 const remoteFor = (nameWithOwner: string) =>
794 parseFetchRemotes(remotes).find(
795 (remote) =>
796 (gitHubApiHostForRemote(remote.url) ??
797 normalizeGitRemoteUrl(remote.url).split("/")[0]) === base.host &&
798 normalizeGitRemoteUrl(remote.url).split("/").slice(1).join("/") ===
799 nameWithOwner.toLowerCase(),
800 )?.name ?? null;
801 const baseRemote = Effect.suspend(() => {
802 const known = remoteFor(baseNameWithOwner);
803 return known === null ? git.resolvePrimaryRemoteName(input.cwd) : Effect.succeed(known);
804 });
805 // Avoid resetting the default branch; prefix colliding forks and fail if it is unknown.
806 const defaultBranch = isCrossRepository
807 ? yield* readRepository(base).pipe(
808 Effect.map((repository) => repository.default_branch ?? null),
809 )
810 : null;
811 const localBranch = pullRequestCheckoutBranchName({
812 headRefName: pullRequest.headRefName,
813 headOwner,
814 isCrossRepository,
815 defaultBranch,
816 });
817​
818 const headRemote = Effect.gen(function* () {
819 if (!isCrossRepository) return yield* baseRemote;
820 if (headNameWithOwner === null) return yield* failure("The fork is gone.");
821 const known = remoteFor(headNameWithOwner);
822 if (known !== null) return known;
823 const [owner, name] = headNameWithOwner.split("/");
824 const fork = yield* readRepository({ host: base.host, owner: owner!, name: name! });
825 // Git fetches from a remote's first URL; `config --get` returns the last of several, and
826 // `git remote -v` applies `insteadOf` rewrites.
827 const originUrl = yield* runGit(input.cwd, "readOriginUrl", [
828 "config",
829 "--get-all",
830 "remote.origin.url",
831 ]).pipe(
832 Effect.map((result) => result.stdout.split("\n", 1)[0]?.trim() || null),
833 Effect.orElseSucceed(() => null),
834 );
835 return yield* git.ensureRemote({
836 cwd: input.cwd,
837 preferredName: headOwner ?? "fork",
838 url: originUrl !== null && isSshRemoteUrl(originUrl) ? fork.ssh_url : fork.html_url,
839 });
840 });
841​
842 const exists = (yield* git
843 .listLocalBranchNames(input.cwd)
844 .pipe(Effect.mapError(gitFailure))).includes(localBranch);
845​
846 const target = yield* Effect.gen(function* () {
847 const remoteName = yield* headRemote;
848 yield* git.fetchRemoteTrackingBranch({
849 cwd: input.cwd,
850 remoteName,
851 remoteBranch: pullRequest.headRefName,
852 });
853 return {
854 ref: `refs/remotes/${remoteName}/${pullRequest.headRefName}`,
855 upstream: { remoteName, remoteBranch: pullRequest.headRefName },
856 };
857 }).pipe(
858 Effect.catch(() =>
859 Effect.gen(function* () {
860 yield* runGit(input.cwd, "fetchPullRef", [
861 "fetch",
862 "--quiet",
863 "--no-tags",
864 "--",
865 yield* baseRemote,
866 `refs/pull/${pullRequest.number}/head`,
867 ]);
868 const { commitSha } = yield* git.resolveCommit({
869 cwd: input.cwd,
870 revision: "FETCH_HEAD",
871 });
872 return { ref: commitSha, upstream: null };
873 }),
874 ),
875 Effect.mapError(gitFailure),
876 );
877​
878 yield* Effect.gen(function* () {
879 if (!exists) {
880 yield* git.createBranch({ cwd: input.cwd, branch: localBranch, startPoint: target.ref });
881 }
882 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
883 if (exists) {
884 yield* runGit(
885 input.cwd,
886 "sync",
887 input.force === true
888 ? ["reset", "--hard", "--quiet", target.ref]
889 : ["merge", "--ff-only", "--quiet", target.ref],
890 );
891 }
892 // Set tracking after sync succeeds so a failed checkout preserves the existing upstream.
893 if (target.upstream !== null) {
894 yield* git.setBranchUpstream({ cwd: input.cwd, branch: localBranch, ...target.upstream });
895 }
896 }).pipe(Effect.mapError(gitFailure));
897 },
898 );
899​
900 const providerError =
901 (
902 operation: string,
903 cwd: string,
904 context?: { readonly reference?: string; readonly repository?: string },
905 ) =>
906 (error: GitHubFailure) =>
907 new SourceControlProviderError({
908 provider: SourceControlProviderKind.make("github"),
909 operation,
910 cwd,
911 ...(context?.reference === undefined
912 ? {}
913 : {
914 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
915 context.reference,
916 ),
917 }),
918 ...(context?.repository === undefined
919 ? {}
920 : {
921 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
922 context.repository,
923 ),
924 }),
925 detail: error.detail,
926 cause: error.cause,
927 });
928​
929 const readLinkSubject = Effect.fn("GitHubSourceControlProvider.readLinkSubject")(function* (
930 input: { readonly cwd: string; readonly url: URL },
931 endpoint: string,
932 ) {
933 const result = yield* api
934 .rest({
935 host: input.url.host,
936 operation: "resolveLink",
937 path: endpoint,
938 maxResponseBytes: 1_000_000,
939 })
940 .pipe(
941 Effect.timeout("3 seconds"),
942 Effect.mapError(
943 (cause) =>
944 new SourceControlProviderError({
945 provider: SourceControlProviderKind.make("github"),
946 operation: "resolveLink",
947 cwd: input.cwd,
948 detail: "The linked subject could not be read.",
949 cause,
950 }),
951 ),
952 );
953 const subject = yield* decodeLinkSubject(result.body).pipe(
954 Effect.mapError(
955 (cause) =>
956 new SourceControlProviderError({
957 provider: SourceControlProviderKind.make("github"),
958 operation: "resolveLink.decode",
959 cwd: input.cwd,
960 detail: "The linked subject could not be read.",
961 cause,
962 }),
963 ),
964 );
965 return { title: subject.title, body: subject.body ?? null };
966 });
967​
968 return SourceControlProvider.SourceControlProvider.of({
969 kind: SourceControlProviderKind.make("github"),
970 resolveRemoteWebHost: Effect.fn("GitHubSourceControlProvider.resolveRemoteWebHost")(
971 ({ context }) => Effect.succeed(gitHubApiHostForRemote(context.remoteUrl)),
972 ),
973 // GitHub matches bare heads; read a full page to disambiguate forks by owner. A default branch
974 // collides with most forks, so its owner-qualified lookup has GitHub filter by owner instead.
975 headBranchProbe: ({ headSelectors, ownerHeadSelector }) => ({
976 headSelectors: ownerHeadSelector
977 ? [ownerHeadSelector]
978 : headSelectors.filter((selector) => !selector.includes(":")),
979 limit: 100,
980 }),
981 readChangeRequestTemplate: Effect.fn("GitHubSourceControlProvider.readChangeRequestTemplate")(
982 function ({ cwd, treeish }) {
983 return GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute);
984 },
985 ),
986 // `createChangeRequest` targets what `resolveRepository` picks: GH_REPO when it parses, else
987 // gh's pick among the checkout's remotes, led by the one `gh repo set-default` marked
988 // (`gh-resolved`). An HTTPS remote keeps a non-default port in the context's host, and the
989 // mark is then ignored.
990 createsChangeRequestsIn: Effect.fn("GitHubSourceControlProvider.createsChangeRequestsIn")(
991 function* ({ cwd, context, repository }) {
992 const host = URL.canParse(context.provider.baseUrl)
993 ? new URL(context.provider.baseUrl).host
994 : null;
995 const target = repository?.toLowerCase();
996 const fromEnvironment = parseGitHubRepositorySelector(
997 environment.GH_REPO ?? "",
998 host ?? "",
999 );
1000 if (fromEnvironment !== null) {
1001 const { host: targetHost, owner, name } = fromEnvironment;
1002 return (
1003 host !== null &&
1004 URL.canParse(`https://${targetHost}`) &&
1005 new URL(`https://${targetHost}`).host === host &&
1006 `${owner}/${name}`.toLowerCase() === target
1007 );
1009 const { locator } = resolveGitHubRepository({
1010 ...(yield* readRemotes(cwd)),
1011 hostHint: host ?? undefined,
1012 defaultHost: host ?? "github.com",
1013 });
1014 return locator === null || `${locator.owner}/${locator.name}`.toLowerCase() === target;
1015 },
1016 ),
1017 // `gh pr create` run in the checkout, as an agent in a T3 worktree often does, takes its base
1018 // from this key.
1019 recordBranchBase: Effect.fn("GitHubSourceControlProvider.recordBranchBase")(function ({
1020 cwd,
1021 branch,
1022 baseBranch,
1023 }) {
1024 return git
1025 .writeConfigValue({ cwd, key: `branch.${branch}.gh-merge-base`, value: baseBranch })
1026 .pipe(
1027 Effect.catch((cause) =>
1028 Effect.logWarning("Could not record the branch base for gh", { cause }),
1029 ),
1030 );
1031 }),
1032 resolveLink: (input) => {
1033 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
1034 if (input.url.host !== "github.com") return undefined;
1035 const match = /^\/([\w.-]+)\/([\w.-]+)\/(?:pull|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
1036 input.url.pathname,
1037 );
1038 if (!match) return undefined;
1039 return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);
1040 },
1041 listChangeRequests: Effect.fn("GitHubSourceControlProvider.listChangeRequests")(
1042 function (input) {
1043 return (
1044 input.state === "open" ? Effect.succeed(true) : SourceControlRateLimit.Interactive
1045 ).pipe(
1046 Effect.flatMap((allowReserve) =>
1047 listByHead({
1048 cwd: input.cwd,
1049 headSelector: input.headSelector,
1050 state: input.state,
1051 limit: input.limit ?? (input.state === "open" ? 1 : 20),
1052 host: contextHost(input.context),
1053 context: input.context,
1054 allowReserve,
1055 }),
1056 ),
1057 Effect.map((records) => records.map(toChangeRequest)),
1058 Effect.mapError(
1059 providerError("listChangeRequests", input.cwd, { reference: input.headSelector }),
1060 ),
1061 );
1062 },
1063 ),
1064 getChangeRequest: Effect.fn("GitHubSourceControlProvider.getChangeRequest")(function (input) {
1065 return readPullRequest({ ...input, host: contextHost(input.context) }).pipe(
1066 Effect.map(toChangeRequest),
1067 Effect.mapError(
1068 providerError("getChangeRequest", input.cwd, { reference: input.reference }),
1069 ),
1070 );
1071 }),
1072 createChangeRequest: Effect.fn("GitHubSourceControlProvider.createChangeRequest")(
1073 function* (input) {
1074 const locator = yield* resolveRepository(input);
1075 const body = yield* fileSystem
1076 .readFileString(input.bodyFile)
1077 .pipe(
1078 Effect.mapError((cause) =>
1079 failure("The pull request description could not be read.", cause),
1080 ),
1081 );
1082 yield* rest({
1083 host: locator.host,
1084 operation: "createPullRequest",
1085 method: "POST",
1086 allowReserve: true,
1087 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}/pulls`,
1088 // Explicitly allow maintainer edits to match gh; the API default is undocumented.
1089 body: {
1090 base: input.baseRefName,
1091 head: input.headSelector,
1092 title: input.title,
1093 body,
1094 maintainer_can_modify: true,
1095 },
1096 });
1097 },
1098 (effect, input) =>
1099 effect.pipe(
1100 Effect.mapError(
1101 providerError("createChangeRequest", input.cwd, { reference: input.headSelector }),
1102 ),
1103 ),
1104 ),
1105 getRepositoryCloneUrls: Effect.fn("GitHubSourceControlProvider.getRepositoryCloneUrls")(
1106 function* (input) {
1107 const fallbackHost = (
1108 input.host ??
1109 (yield* resolveRepository(input).pipe(
1110 Effect.map((locator) => locator.host),
1111 Effect.orElseSucceed(() => environment.GH_HOST ?? "github.com"),
1112 ))
1113 ).toLowerCase();
1114 const bareName = input.repository.trim().replace(/\.git$/i, "");
1115 const locator =
1116 parseGitHubRepositorySelector(input.repository, fallbackHost) ??
1117 (/^[^/\s]+$/.test(bareName)
1118 ? {
1119 host: fallbackHost,
1120 owner: yield* readViewerLogin(fallbackHost),
1121 name: bareName,
1123 : null);
1124 if (locator === null) return yield* failure("Repositories are named owner/name.");
1125 return repositoryCloneUrls(yield* readRepository(locator));
1126 },
1127 (effect, input) =>
1128 effect.pipe(
1129 Effect.mapError(
1130 providerError("getRepositoryCloneUrls", input.cwd, {
1131 repository: input.repository,
1132 }),
1133 ),
1134 ),
1135 ),
1136 createRepository: Effect.fn("GitHubSourceControlProvider.createRepository")(
1137 function* (input) {
1138 const locator = parseGitHubRepositorySelector(
1139 input.repository,
1140 (environment.GH_HOST ?? "github.com").toLowerCase(),
1141 );
1142 const viewer = locator === null ? null : yield* readViewerLogin(locator.host);
1143 const owner = locator?.owner ?? viewer;
1144 const name = locator?.name ?? input.repository.trim();
1145 const host = locator?.host ?? (environment.GH_HOST?.trim().toLowerCase() || "github.com");
1146 const isViewer = viewer !== null && owner?.toLowerCase() === viewer.toLowerCase();
1147 const response = yield* rest(
1149 host,
1150 operation: "createRepository",
1151 method: "POST",
1152 allowReserve: true,
1153 path:
1154 isViewer || owner === null ? "user/repos" : `orgs/${encodeURIComponent(owner)}/repos`,
1155 body: { name, private: input.visibility === "private" },
1156 },
1157 `No organization named ${owner ?? "that"} that this account can create repositories in.`,
1158 );
1159 const decoded = decodeRawRepository(response.body);
1160 if (Result.isFailure(decoded)) {
1161 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
1163 return repositoryCloneUrls(decoded.success);
1164 },
1165 (effect, input) =>
1166 effect.pipe(
1167 Effect.mapError(
1168 providerError("createRepository", input.cwd, { repository: input.repository }),
1169 ),
1170 ),
1171 ),
1172 getDefaultBranch: Effect.fn("GitHubSourceControlProvider.getDefaultBranch")(
1173 function* (input) {
1174 const locator = yield* resolveRepository({
1175 cwd: input.cwd,
1176 host: contextHost(input.context),
1177 context: input.context,
1178 });
1179 const repository = yield* readRepository(locator);
1180 const branch = repository.default_branch?.trim() ?? "";
1181 return branch.length > 0 ? branch : null;
1182 },
1183 (effect, input) => effect.pipe(Effect.mapError(providerError("getDefaultBranch", input.cwd))),
1184 ),
1185 checkoutChangeRequest: Effect.fn("GitHubSourceControlProvider.checkoutChangeRequest")(
1186 function (input) {
1187 return checkoutPullRequest(input).pipe(
1188 Effect.mapError(
1189 providerError("checkoutChangeRequest", input.cwd, { reference: input.reference }),
1190 ),
1191 );
1192 },
1193 ),
1194 });
1195});