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

GitHubSourceControlProvider.ts

1,101 lines41.9 KB

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