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

GitHubSourceControlProvider.ts

1,088 lines41.4 KB

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