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

GitHubSourceControlProvider.ts

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