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

GitHubSourceControlProvider.ts

1,057 lines40.2 KB

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