Open History to see the last commit
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 };
96}
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 }));
109}
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 });
187}
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;
207}
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 }
344}
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 };
360}
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;
388}
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 });
407}
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;
421}
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) yield* runGit(input.cwd, "branch", ["branch", "--", localBranch, target.ref]);
754 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
755 if (exists) {
756 yield* runGit(
757 input.cwd,
758 "sync",
759 input.force === true
760 ? ["reset", "--hard", "--quiet", target.ref]
761 : ["merge", "--ff-only", "--quiet", target.ref],
762 );
763 }
764 // Set tracking after sync succeeds so a failed checkout preserves the existing upstream.
765 if (target.upstream !== null) {
766 yield* git.setBranchUpstream({ cwd: input.cwd, branch: localBranch, ...target.upstream });
767 }
768 }).pipe(Effect.mapError(gitFailure));
769 },
770 );
771
772 const providerError =
773 (
774 operation: string,
775 cwd: string,
776 context?: { readonly reference?: string; readonly repository?: string },
777 ) =>
778 (error: GitHubFailure) =>
779 new SourceControlProviderError({
780 provider: SourceControlProviderKind.make("github"),
781 operation,
782 cwd,
783 ...(context?.reference === undefined
784 ? {}
785 : {
786 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
787 context.reference,
788 ),
789 }),
790 ...(context?.repository === undefined
791 ? {}
792 : {
793 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
794 context.repository,
795 ),
796 }),
797 detail: error.detail,
798 cause: error.cause,
799 });
800
801 const readLinkSubject = Effect.fn("GitHubSourceControlProvider.readLinkSubject")(function* (
802 input: { readonly cwd: string; readonly url: URL },
803 endpoint: string,
804 ) {
805 const result = yield* api
806 .rest({
807 host: input.url.host,
808 operation: "resolveLink",
809 path: endpoint,
810 maxResponseBytes: 1_000_000,
811 })
812 .pipe(
813 Effect.timeout("3 seconds"),
814 Effect.mapError(
815 (cause) =>
816 new SourceControlProviderError({
817 provider: SourceControlProviderKind.make("github"),
818 operation: "resolveLink",
819 cwd: input.cwd,
820 detail: "The linked subject could not be read.",
821 cause,
822 }),
823 ),
824 );
825 const subject = yield* decodeLinkSubject(result.body).pipe(
826 Effect.mapError(
827 (cause) =>
828 new SourceControlProviderError({
829 provider: SourceControlProviderKind.make("github"),
830 operation: "resolveLink.decode",
831 cwd: input.cwd,
832 detail: "The linked subject could not be read.",
833 cause,
834 }),
835 ),
836 );
837 return { title: subject.title, body: subject.body ?? null };
838 });
839
840 return SourceControlProvider.SourceControlProvider.of({
841 kind: SourceControlProviderKind.make("github"),
842 // GitHub matches bare heads; read a full page to disambiguate forks by owner.
843 headBranchProbe: ({ headSelectors }) => ({
844 headSelectors: headSelectors.filter((selector) => !selector.includes(":")),
845 limit: 100,
846 }),
847 readChangeRequestTemplate: ({ cwd, treeish }) =>
848 GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute),
849 // `createChangeRequest` targets what `resolveRepository` picks: GH_REPO when it parses, else
850 // the remote `gh repo set-default` marked (`gh-resolved`). An HTTPS remote keeps a
851 // non-default port in the context's host, and the mark is then ignored.
852 createsChangeRequestsIn: Effect.fn("GitHubSourceControlProvider.createsChangeRequestsIn")(
853 function* ({ cwd, context, repository }) {
854 const host = URL.canParse(context.provider.baseUrl)
855 ? new URL(context.provider.baseUrl).host
856 : null;
857 const target = repository?.toLowerCase();
858 const fromEnvironment = parseGitHubRepositorySelector(
859 environment.GH_REPO ?? "",
860 host ?? "",
861 );
862 if (fromEnvironment !== null) {
863 const { host: targetHost, owner, name } = fromEnvironment;
864 return (
865 host !== null &&
866 URL.canParse(`https://${targetHost}`) &&
867 new URL(`https://${targetHost}`).host === host &&
868 `${owner}/${name}`.toLowerCase() === target
869 );
870 }
871 const mark = yield* git
872 .readConfigValue(cwd, `remote.${context.remoteName}.gh-resolved`)
873 .pipe(Effect.orElseSucceed(() => null));
874 const { locator } = resolveGitHubRepository({
875 remotes: `${context.remoteName}\t${context.remoteUrl} (fetch)`,
876 resolved: mark === null ? "" : `remote.${context.remoteName}.gh-resolved ${mark}`,
877 hostHint: host ?? undefined,
878 defaultHost: host ?? "github.com",
879 });
880 return locator === null || `${locator.owner}/${locator.name}`.toLowerCase() === target;
881 },
882 ),
883 // `gh pr create` run in the checkout, as an agent in a T3 worktree often does, takes its base
884 // from this key.
885 recordBranchBase: ({ cwd, branch, baseBranch }) =>
886 git
887 .execute({
888 operation: "GitHubSourceControlProvider.recordBranchBase",
889 cwd,
890 args: ["config", `branch.${branch}.gh-merge-base`, baseBranch],
891 })
892 .pipe(
893 Effect.asVoid,
894 Effect.catch((cause) =>
895 Effect.logWarning("Could not record the branch base for gh", { cause }),
896 ),
897 ),
898 resolveLink: (input) => {
899 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
900 if (input.url.host !== "github.com") return undefined;
901 const match = /^\/([\w.-]+)\/([\w.-]+)\/(?:pull|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
902 input.url.pathname,
903 );
904 if (!match) return undefined;
905 return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);
906 },
907 listChangeRequests: (input) =>
908 (input.state === "open" ? Effect.succeed(true) : SourceControlRateLimit.Interactive).pipe(
909 Effect.flatMap((allowReserve) =>
910 listByHead({
911 cwd: input.cwd,
912 headSelector: input.headSelector,
913 state: input.state,
914 limit: input.limit ?? (input.state === "open" ? 1 : 20),
915 host: contextHost(input.context),
916 context: input.context,
917 allowReserve,
918 }),
919 ),
920 Effect.map((records) => records.map(toChangeRequest)),
921 Effect.mapError(
922 providerError("listChangeRequests", input.cwd, { reference: input.headSelector }),
923 ),
924 ),
925 getChangeRequest: (input) =>
926 readPullRequest({ ...input, host: contextHost(input.context) }).pipe(
927 Effect.map(toChangeRequest),
928 Effect.mapError(
929 providerError("getChangeRequest", input.cwd, { reference: input.reference }),
930 ),
931 ),
932 createChangeRequest: Effect.fn("GitHubSourceControlProvider.createChangeRequest")(
933 function* (input) {
934 const locator = yield* resolveRepository(input);
935 const body = yield* fileSystem
936 .readFileString(input.bodyFile)
937 .pipe(
938 Effect.mapError((cause) =>
939 failure("The pull request description could not be read.", cause),
940 ),
941 );
942 yield* rest({
943 host: locator.host,
944 operation: "createPullRequest",
945 method: "POST",
946 allowReserve: true,
947 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}/pulls`,
948 // Explicitly allow maintainer edits to match gh; the API default is undocumented.
949 body: {
950 base: input.baseRefName,
951 head: input.headSelector,
952 title: input.title,
953 body,
954 maintainer_can_modify: true,
955 },
956 });
957 },
958 (effect, input) =>
959 effect.pipe(
960 Effect.mapError(
961 providerError("createChangeRequest", input.cwd, { reference: input.headSelector }),
962 ),
963 ),
964 ),
965 getRepositoryCloneUrls: Effect.fn("GitHubSourceControlProvider.getRepositoryCloneUrls")(
966 function* (input) {
967 const fallbackHost = (yield* resolveRepository(input).pipe(
968 Effect.map((locator) => locator.host),
969 Effect.orElseSucceed(() => environment.GH_HOST ?? "github.com"),
970 )).toLowerCase();
971 const bareName = input.repository.trim().replace(/\.git$/i, "");
972 const locator =
973 parseGitHubRepositorySelector(input.repository, fallbackHost) ??
974 (/^[^/\s]+$/.test(bareName)
975 ? { host: fallbackHost, owner: yield* readViewerLogin(fallbackHost), name: bareName }
976 : null);
977 if (locator === null) return yield* failure("Repositories are named owner/name.");
978 return repositoryCloneUrls(yield* readRepository(locator));
979 },
980 (effect, input) =>
981 effect.pipe(
982 Effect.mapError(
983 providerError("getRepositoryCloneUrls", input.cwd, { repository: input.repository }),
984 ),
985 ),
986 ),
987 createRepository: Effect.fn("GitHubSourceControlProvider.createRepository")(
988 function* (input) {
989 const locator = parseGitHubRepositorySelector(
990 input.repository,
991 (environment.GH_HOST ?? "github.com").toLowerCase(),
992 );
993 const viewer = locator === null ? null : yield* readViewerLogin(locator.host);
994 const owner = locator?.owner ?? viewer;
995 const name = locator?.name ?? input.repository.trim();
996 const host = locator?.host ?? (environment.GH_HOST?.trim().toLowerCase() || "github.com");
997 const isViewer = viewer !== null && owner?.toLowerCase() === viewer.toLowerCase();
998 const response = yield* rest(
999 {
1000 host,
1001 operation: "createRepository",
1002 method: "POST",
1003 allowReserve: true,
1004 path:
1005 isViewer || owner === null ? "user/repos" : `orgs/${encodeURIComponent(owner)}/repos`,
1006 body: { name, private: input.visibility === "private" },
1007 },
1008 `No organization named ${owner ?? "that"} that this account can create repositories in.`,
1009 );
1010 const decoded = decodeRawRepository(response.body);
1011 if (Result.isFailure(decoded)) {
1012 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
1013 }
1014 return repositoryCloneUrls(decoded.success);
1015 },
1016 (effect, input) =>
1017 effect.pipe(
1018 Effect.mapError(
1019 providerError("createRepository", input.cwd, { repository: input.repository }),
1020 ),
1021 ),
1022 ),
1023 getDefaultBranch: Effect.fn("GitHubSourceControlProvider.getDefaultBranch")(
1024 function* (input) {
1025 const locator = yield* resolveRepository({
1026 cwd: input.cwd,
1027 host: contextHost(input.context),
1028 context: input.context,
1029 });
1030 const repository = yield* readRepository(locator);
1031 const branch = repository.default_branch?.trim() ?? "";
1032 return branch.length > 0 ? branch : null;
1033 },
1034 (effect, input) => effect.pipe(Effect.mapError(providerError("getDefaultBranch", input.cwd))),
1035 ),
1036 checkoutChangeRequest: (input) =>
1037 checkoutPullRequest(input).pipe(
1038 Effect.mapError(
1039 providerError("checkoutChangeRequest", input.cwd, { reference: input.reference }),
1040 ),
1041 ),
1042 });
1043});