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

GitHubSourceControlProvider.ts

1,236 lines46.7 KB

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