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

GitHubSourceControlProvider.ts

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