Open History to see the last commit
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 };
101}
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 }));
114}
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 });
193}
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;
213}
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
345class GitHubRepositoryLookupError extends Schema.TaggedError<GitHubRepositoryLookupError>()(
346 "GitHubRepositoryLookupError",
347 {
348 userFacingDetail: Schema.String,
349 cause: Schema.optional(Schema.Defect()),
350 },
351) {}
352
353const failure = (detail: string, cause?: unknown) => new GitHubFailure({ detail, cause });
354
355// A gh login confirms a GitHub Enterprise Server whose hostname does not identify its provider.
356const refineRepositoryIdentity: NonNullable<
357 SourceControlProvider.SourceControlProvider["Service"]["refineRepositoryIdentity"]
358> = Effect.fn("GitHubSourceControlProvider.refineRepositoryIdentity")(function* ({
359 identity,
360 resolveContext,
361}) {
362 if (!identity.rootPath || (identity.provider !== undefined && identity.provider !== "unknown"))
363 return identity;
364 const remote = parseGitRemoteHost(identity.locator.remoteUrl);
365 if (remote === null) return identity;
366 const context = yield* resolveContext({
367 cwd: identity.rootPath,
368 context: {
369 provider: unknownRemoteProvider(remote),
370 remoteName: identity.locator.remoteName,
371 remoteUrl: identity.locator.remoteUrl,
372 },
373 });
374 return context?.provider.kind === "github"
375 ? { ...identity, provider: SourceControlProviderKind.make("github") }
376 : identity;
377});
378
379const PULL_REQUEST_NOT_FOUND = "Pull request not found. Check the PR number or URL and try again.";
380const REPOSITORY_NOT_FOUND = "Repository not found. Check the owner and name and try again.";
381const isGitHubApiNotFoundError = Schema.is(GitHubRequestPolicy.GitHubApiNotFoundError);
382
383function fromGitHubApiError(
384 error: GitHubRequestPolicy.GitHubApiError,
385 notFound = PULL_REQUEST_NOT_FOUND,
386): GitHubFailure {
387 switch (error._tag) {
388 case "GitHubCliMissingError":
389 return failure(
390 "No GitHub credential on the server. Set GH_TOKEN, or install the GitHub CLI and run `gh auth login`.",
391 error,
392 );
393 case "GitHubNotSignedInError":
394 case "GitHubHostDisabledError":
395 case "SettingsSecretUnresolvedError":
396 return failure(error.message, error);
397 case "GitHubApiAuthenticationError":
398 return failure(
399 "GitHub is not authenticated. Run `gh auth login` (or set GH_TOKEN) and retry.",
400 error,
401 );
402 case "GitHubApiRateLimitError":
403 case "SourceControlRateLimitPausedError":
404 return failure(
405 "GitHub API rate limit exceeded. Requests resume when the limit resets.",
406 error,
407 );
408 case "GitHubApiNotFoundError":
409 return failure(notFound, error);
410 case "GitHubCliFailedError":
411 case "GitHubCliTimeoutError":
412 case "GitHubAppSessionError":
413 case "GitHubApiResponseError":
414 case "GitHubApiRequestError":
415 return failure(error.message.trim() || "GitHub request failed.", error);
416 }
417}
418
419const notFound = (cause: string) => failure(PULL_REQUEST_NOT_FOUND, new Error(cause));
420
421const RawRepositorySchema = Schema.Struct({
422 full_name: TrimmedNonEmptyString,
423 html_url: TrimmedNonEmptyString,
424 ssh_url: TrimmedNonEmptyString,
425 default_branch: Schema.optional(Schema.NullOr(Schema.String)),
426});
427const decodeRawRepository = decodeJsonResult(RawRepositorySchema);
428
429function repositoryCloneUrls(
430 raw: Schema.Schema.Type<typeof RawRepositorySchema>,
431): SourceControlRepositoryCloneUrls {
432 return { nameWithOwner: raw.full_name, url: raw.html_url, sshUrl: raw.ssh_url };
433}
434
435const decodeViewerLogin = decodeJsonResult(Schema.Struct({ login: TrimmedNonEmptyString }));
436
437const decodeRestPullRequests = decodeJsonResult(Schema.Array(Schema.Unknown));
438const decodeRestPullRequest = Schema.decodeUnknownOption(
439 Schema.Struct({
440 number: Schema.Number,
441 title: Schema.String,
442 html_url: Schema.String,
443 state: Schema.String,
444 draft: Schema.optional(Schema.Boolean),
445 merged_at: Schema.NullOr(Schema.String),
446 closed_at: Schema.NullOr(Schema.String),
447 updated_at: Schema.String,
448 base: Schema.Struct({ ref: Schema.String, repo: Schema.Struct({ full_name: Schema.String }) }),
449 head: Schema.Struct({
450 ref: Schema.String,
451 sha: Schema.String,
452 repo: Schema.NullOr(
453 Schema.Struct({
454 name: Schema.String,
455 full_name: Schema.String,
456 owner: Schema.Struct({ login: Schema.String, type: Schema.String }),
457 }),
458 ),
459 }),
460 }),
461);
462
463/** Reshapes a REST pull request into the GraphQL node so both decode the same way. */
464function restPullRequestNode(entry: unknown) {
465 const pr = Option.getOrNull(decodeRestPullRequest(entry));
466 if (pr === null) return null;
467 return {
468 number: pr.number,
469 title: pr.title,
470 url: pr.html_url,
471 baseRefName: pr.base.ref,
472 headRefName: pr.head.ref,
473 headRefOid: pr.head.sha,
474 state: pr.merged_at === null ? pr.state.toUpperCase() : "MERGED",
475 isDraft: pr.draft === true,
476 mergedAt: pr.merged_at,
477 closedAt: pr.closed_at,
478 updatedAt: pr.updated_at,
479 isCrossRepository: pr.head.repo?.full_name !== pr.base.repo.full_name,
480 headRepository: pr.head.repo && {
481 name: pr.head.repo.name,
482 nameWithOwner: pr.head.repo.full_name,
483 },
484 headRepositoryOwner: pr.head.repo && {
485 __typename: pr.head.repo.owner.type,
486 login: pr.head.repo.owner.login,
487 },
488 };
489}
490
491type PullRequestListState = "open" | "closed" | "merged" | "all";
492
493const GRAPHQL_STATES: Record<
494 PullRequestListState,
495 NonNullable<PullRequestsByHead.Variables["states"]>
496> = {
497 open: ["OPEN"],
498 closed: ["CLOSED"],
499 merged: ["MERGED"],
500 all: ["OPEN", "CLOSED", "MERGED"],
501};
502/** 50 lookups keeps responses near 0.5s at the same one-point cost as 100. */
503const HEAD_LOOKUPS_PER_DOCUMENT = 50;
504/** Git reads stagger background lookups by ~300ms; gather batches before spending quota. */
505const HEAD_LOOKUP_BATCH_WINDOW = "50 millis";
506const BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW = "500 millis";
507/** For heads matching 100 PRs each, 50 lookups approached GitHub's ~10s limit; 25 took ~7s. */
508const BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT = 25;
509const HEAD_LOOKUP_MAX_RESPONSE_BYTES = 16_000_000;
510const OWNER_HEAD_SCAN_LIMIT = 100;
511
512function trimmed(value: string): string | null {
513 const text = value.trim();
514 return text.length > 0 ? text : null;
515}
516
517/** Null isolates unusable PRs from the rest of a listing. */
518function toPullRequestRecord(node: PullRequestNode): NormalizedGitHubPullRequestRecord | null {
519 const title = trimmed(node.title);
520 const url = trimmed(node.url);
521 const baseRefName = trimmed(node.baseRefName);
522 const headRefName = trimmed(node.headRefName);
523 const updatedAt = DateTime.make(node.updatedAt);
524 if (node.number < 1 || !title || !url || !baseRefName || !headRefName) return null;
525 if (Option.isNone(updatedAt)) return null;
526 return normalizeGitHubPullRequestRecord({
527 ...node,
528 title,
529 url,
530 baseRefName,
531 headRefName,
532 updatedAt: Option.some(DateTime.toUtc(updatedAt.value)),
533 });
534}
535
536export function pullRequestCheckoutBranchName(input: {
537 readonly headRefName: string;
538 readonly headOwner: string | null;
539 readonly isCrossRepository: boolean;
540 readonly defaultBranch: string | null;
541}): string {
542 return input.isCrossRepository &&
543 input.headOwner !== null &&
544 input.defaultBranch !== null &&
545 input.headRefName === input.defaultBranch
546 ? `${input.headOwner}/${input.headRefName}`
547 : input.headRefName;
548}
549
550const contextHost = (context: SourceControlProvider.SourceControlProviderContext | undefined) =>
551 context === undefined ? undefined : new URL(context.provider.baseUrl).host;
552
553export const make = Effect.gen(function* () {
554 const api = yield* GitHubRest.GitHubRest;
555 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
556 const process = sourceControlHost.process;
557 const environment = yield* HostProcess.Environment;
558 const git = sourceControlHost.git;
559 const fileSystem = yield* FileSystem.FileSystem;
560
561 const gitRead = (cwd: string, args: ReadonlyArray<string>) =>
562 process.run({
563 operation: "GitHubSourceControlProvider.resolveRepository",
564 command: "git",
565 args,
566 cwd,
567 allowNonZeroExit: true,
568 timeoutMs: 5_000,
569 });
570
571 const readRemotes = (cwd: string) =>
572 Effect.all([
573 gitRead(cwd, ["remote", "-v"]),
574 gitRead(cwd, ["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"]),
575 ]).pipe(
576 Effect.orElseSucceed(() => [null, null] as const),
577 Effect.map(([remotes, resolved]) => ({
578 remotes: remotes?.exitCode === 0 ? remotes.stdout : "",
579 resolved: resolved?.exitCode === 0 ? resolved.stdout : "",
580 })),
581 );
582
583 const resolveRepository = Effect.fn("GitHubSourceControlProvider.resolveRepository")(
584 function* (input: {
585 readonly cwd: string;
586 readonly host?: string | undefined;
587 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
588 }) {
589 const envRepository = environment.GH_REPO?.trim();
590 const hostHint = input.host ?? contextHost(input.context);
591 const defaultHost = (hostHint ?? environment.GH_HOST ?? "github.com").toLowerCase();
592 if (envRepository) {
593 const locator = parseGitHubRepositorySelector(envRepository, defaultHost);
594 if (locator !== null) return locator;
595 }
596 const { host, locator } = resolveGitHubRepository({
597 ...(yield* readRemotes(input.cwd)),
598 hostHint,
599 defaultHost,
600 });
601 if (locator !== null) return locator;
602 if (input.context) {
603 const remote = normalizeGitRemoteUrl(input.context.remoteUrl);
604 const fallback = parseGitHubRepositorySelector(
605 `${host}/${remote.slice(remote.indexOf("/") + 1)}`,
606 host,
607 );
608 if (fallback !== null) return fallback;
609 }
610 return yield* failure(
611 `No GitHub repository on ${host} was found among this checkout's git remotes.`,
612 );
613 },
614 );
615
616 const client = yield* GraphQLClient.make(
617 GraphQLGroup.make(LenientPullRequestsByHead, PullRequestByNumber).middleware(
618 GitHubGraphQlClient.GitHubGraphQlAuth,
619 ),
620 ).pipe(Effect.provide(GitHubGraphQlClient.layer));
621
622 const graphqlRead = <A, E, R>(
623 target: GitHubGraphQlClient.GitHubGraphQlTarget["Service"],
624 decodeDetail: string,
625 effect: Effect.Effect<A, E, R>,
626 ) =>
627 effect.pipe(
628 GitHubGraphQlClient.call(target),
629 Effect.mapError((error) =>
630 GraphQLClientError.isGraphQLClientError(error)
631 ? failure(decodeDetail, error)
632 : fromGitHubApiError(error as GitHubRequestPolicy.GitHubApiError),
633 ),
634 );
635
636 const rest = (input: GitHubRest.GitHubRestInput, notFoundDetail?: string) =>
637 api.rest(input).pipe(Effect.mapError((error) => fromGitHubApiError(error, notFoundDetail)));
638
639 // Batch by host/credential; isolate missing repositories and interactive/background reserves.
640 const headResolver = GraphQLResolver.aliased(client.PullRequestsByHead, {
641 batchKey: GitHubGraphQlClient.batchKey,
642 }).pipe(RequestResolver.batchN(HEAD_LOOKUPS_PER_DOCUMENT));
643 const interactiveHeadResolver = headResolver.pipe(
644 RequestResolver.setDelay(HEAD_LOOKUP_BATCH_WINDOW),
645 );
646 const backgroundHeadResolver = headResolver.pipe(
647 RequestResolver.batchN(BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT),
648 RequestResolver.setDelay(BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW),
649 );
650
651 const listByHead = Effect.fn("GitHubSourceControlProvider.listByHead")(function* (input: {
652 readonly cwd: string;
653 readonly headSelector: string;
654 readonly state: PullRequestListState;
655 readonly limit: number;
656 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
657 readonly host?: string | undefined;
658 readonly repository?: string | undefined;
659 readonly allowReserve: boolean;
660 }) {
661 const base = yield* resolveRepository(input);
662 const locator =
663 input.repository === undefined
664 ? base
665 : parseGitHubRepositorySelector(input.repository, base.host);
666 if (locator === null) return yield* failure(`${input.repository} is not a GitHub repository.`);
667 const limit = Math.min(Math.max(Math.trunc(input.limit), 1), 100);
668 const ownerMatch = /^([^:/\s]+):(.+)$/u.exec(input.headSelector.trim());
669 const headRefName = ownerMatch?.[2] ?? input.headSelector.trim();
670 if (ownerMatch) {
671 // GraphQL cannot filter heads by owner, and names like a fork's `main` match thousands.
672 const query = new URLSearchParams({
673 head: `${ownerMatch[1]}:${headRefName}`,
674 state: input.state === "all" || input.state === "open" ? input.state : "closed",
675 sort: "created",
676 direction: "desc",
677 per_page: String(OWNER_HEAD_SCAN_LIMIT),
678 });
679 const response = yield* rest({
680 host: locator.host,
681 operation: "listPullRequestsByHead",
682 allowReserve: input.allowReserve,
683 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}/pulls?${query}`,
684 });
685 const decoded = decodeRestPullRequests(response.body);
686 if (Result.isFailure(decoded)) {
687 return yield* failure("GitHub returned an invalid change request list.", decoded.failure);
688 }
689 return decoded.success
690 .flatMap((entry) => {
691 const node = Option.getOrNull(decodePullRequestNode(restPullRequestNode(entry)));
692 const record = node === null ? null : toPullRequestRecord(node);
693 return record === null ? [] : [record];
694 })
695 .filter((row) => input.state === "all" || row.state === input.state)
696 .slice(0, limit);
697 }
698 const result = yield* graphqlRead(
699 {
700 host: locator.host,
701 operation: "listPullRequestsByHead",
702 allowReserve: input.allowReserve,
703 // 50 default-branch lookups can each match 100 fork PRs and exceed the usual cap.
704 maxResponseBytes: HEAD_LOOKUP_MAX_RESPONSE_BYTES,
705 },
706 "GitHub returned an invalid change request list.",
707 GraphQLResolver.request(
708 {
709 owner: locator.owner,
710 name: locator.name,
711 head: headRefName,
712 states: GRAPHQL_STATES[input.state],
713 first: limit,
714 },
715 input.allowReserve ? interactiveHeadResolver : backgroundHeadResolver,
716 ),
717 );
718 if (result.repository === null) return yield* notFound("The repository could not be read.");
719 return (result.repository.pullRequests.nodes ?? []).flatMap((entry) => {
720 const node = Option.getOrNull(decodePullRequestNode(entry));
721 const record = node === null ? null : toPullRequestRecord(node);
722 return record === null ? [] : [record];
723 });
724 });
725
726 const readPullRequest = Effect.fn("GitHubSourceControlProvider.readPullRequest")(
727 function* (input: {
728 readonly cwd: string;
729 readonly reference: string;
730 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
731 readonly host?: string | undefined;
732 }) {
733 const parsed = parsePullRequestReference(input.reference);
734 if (parsed.kind === "branch") {
735 // `gh pr view <branch>` prefers an open pull request, then the newest of any state.
736 const lookup = (state: PullRequestListState) =>
737 listByHead({
738 cwd: input.cwd,
739 headSelector: parsed.headSelector,
740 state,
741 limit: 1,
742 host: input.host,
743 context: input.context,
744 allowReserve: true,
745 });
746 const [open] = yield* lookup("open");
747 const found = open ?? (yield* lookup("all"))[0];
748 if (found === undefined) return yield* notFound("No pull request has this head branch.");
749 return found;
750 }
751 const locator = parsed.kind === "url" ? parsed.locator : yield* resolveRepository(input);
752 const decodeDetail = "GitHub returned an invalid pull request.";
753 const result = yield* graphqlRead(
754 { host: locator.host, operation: "getPullRequest", allowReserve: true },
755 decodeDetail,
756 client.PullRequestByNumber({
757 owner: locator.owner,
758 name: locator.name,
759 number: parsed.number,
760 }),
761 );
762 const node = result.repository?.pullRequest;
763 if (node == null) return yield* notFound("The pull request does not exist.");
764 const record = toPullRequestRecord(node);
765 if (record === null)
766 return yield* failure(decodeDetail, new Error("Malformed pull request."));
767 return record;
768 },
769 );
770
771 const readRepository = Effect.fn("GitHubSourceControlProvider.readRepository")(function* (
772 locator: GitHubRepositoryLocator,
773 ) {
774 const response = yield* rest(
775 {
776 host: locator.host,
777 operation: "getRepository",
778 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}`,
779 allowReserve: true,
780 },
781 REPOSITORY_NOT_FOUND,
782 );
783 const decoded = decodeRawRepository(response.body);
784 if (Result.isFailure(decoded)) {
785 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
786 }
787 return decoded.success;
788 });
789
790 const readViewerLogin = Effect.fn("GitHubSourceControlProvider.readViewerLogin")(function* (
791 host: string,
792 ) {
793 const response = yield* rest({
794 host,
795 operation: "getViewer",
796 path: "user",
797 allowReserve: true,
798 });
799 const decoded = decodeViewerLogin(response.body);
800 if (Result.isFailure(decoded)) {
801 return yield* failure("GitHub request failed.", decoded.failure);
802 }
803 return decoded.success.login;
804 });
805
806 // Keep paths, argv and stderr in cause; expose only a fixed checkout error to clients.
807 const gitFailure = (cause: unknown) =>
808 failure("The pull request could not be checked out with git.", cause);
809
810 const runGit = (cwd: string, operation: string, args: ReadonlyArray<string>) =>
811 git.execute({
812 operation: `GitHubSourceControlProvider.checkoutPullRequest.${operation}`,
813 cwd,
814 args,
815 });
816
817 const checkoutPullRequest = Effect.fn("GitHubSourceControlProvider.checkoutPullRequest")(
818 function* (input: {
819 readonly cwd: string;
820 readonly reference: string;
821 readonly force?: boolean;
822 readonly context?: SourceControlProvider.SourceControlProviderContext;
823 }) {
824 const reference = parsePullRequestReference(input.reference);
825 const pullRequest = yield* readPullRequest(input);
826 const base = reference.kind === "url" ? reference.locator : yield* resolveRepository(input);
827 const baseNameWithOwner = `${base.owner}/${base.name}`.toLowerCase();
828 const headNameWithOwner = pullRequest.headRepositoryNameWithOwner ?? null;
829 const isCrossRepository =
830 pullRequest.isCrossRepository ??
831 (headNameWithOwner !== null && headNameWithOwner.toLowerCase() !== baseNameWithOwner);
832 const headOwner =
833 pullRequest.headRepositoryOwnerLogin ?? headNameWithOwner?.split("/")[0] ?? null;
834
835 const remotes = yield* gitRead(input.cwd, ["remote", "-v"]).pipe(
836 Effect.map((result) => (result.exitCode === 0 ? result.stdout : "")),
837 Effect.mapError(gitFailure),
838 );
839 const remoteFor = (nameWithOwner: string) =>
840 parseFetchRemotes(remotes).find(
841 (remote) =>
842 (gitHubApiHostForRemote(remote.url) ??
843 normalizeGitRemoteUrl(remote.url).split("/")[0]) === base.host &&
844 normalizeGitRemoteUrl(remote.url).split("/").slice(1).join("/") ===
845 nameWithOwner.toLowerCase(),
846 )?.name ?? null;
847 const baseRemote = Effect.suspend(() => {
848 const known = remoteFor(baseNameWithOwner);
849 return known === null ? git.resolvePrimaryRemoteName(input.cwd) : Effect.succeed(known);
850 });
851 // Avoid resetting the default branch; prefix colliding forks and fail if it is unknown.
852 const defaultBranch = isCrossRepository
853 ? yield* readRepository(base).pipe(
854 Effect.map((repository) => repository.default_branch ?? null),
855 )
856 : null;
857 const localBranch = pullRequestCheckoutBranchName({
858 headRefName: pullRequest.headRefName,
859 headOwner,
860 isCrossRepository,
861 defaultBranch,
862 });
863
864 const headRemote = Effect.gen(function* () {
865 if (!isCrossRepository) return yield* baseRemote;
866 if (headNameWithOwner === null) return yield* failure("The fork is gone.");
867 const known = remoteFor(headNameWithOwner);
868 if (known !== null) return known;
869 const [owner, name] = headNameWithOwner.split("/");
870 const fork = yield* readRepository({ host: base.host, owner: owner!, name: name! });
871 // Git fetches from a remote's first URL; `config --get` returns the last of several, and
872 // `git remote -v` applies `insteadOf` rewrites.
873 const originUrl = yield* runGit(input.cwd, "readOriginUrl", [
874 "config",
875 "--get-all",
876 "remote.origin.url",
877 ]).pipe(
878 Effect.map((result) => result.stdout.split("\n", 1)[0]?.trim() || null),
879 Effect.orElseSucceed(() => null),
880 );
881 return yield* git.ensureRemote({
882 cwd: input.cwd,
883 preferredName: headOwner ?? "fork",
884 url: originUrl !== null && isSshRemoteUrl(originUrl) ? fork.ssh_url : fork.html_url,
885 });
886 });
887
888 const exists = (yield* git
889 .listLocalBranchNames(input.cwd)
890 .pipe(Effect.mapError(gitFailure))).includes(localBranch);
891
892 const target = yield* Effect.gen(function* () {
893 const remoteName = yield* headRemote;
894 yield* git.fetchRemoteTrackingBranch({
895 cwd: input.cwd,
896 remoteName,
897 remoteBranch: pullRequest.headRefName,
898 });
899 return {
900 ref: `refs/remotes/${remoteName}/${pullRequest.headRefName}`,
901 upstream: { remoteName, remoteBranch: pullRequest.headRefName },
902 };
903 }).pipe(
904 Effect.catch(() =>
905 Effect.gen(function* () {
906 yield* runGit(input.cwd, "fetchPullRef", [
907 "fetch",
908 "--quiet",
909 "--no-tags",
910 "--",
911 yield* baseRemote,
912 `refs/pull/${pullRequest.number}/head`,
913 ]);
914 const { commitSha } = yield* git.resolveCommit({
915 cwd: input.cwd,
916 revision: "FETCH_HEAD",
917 });
918 return { ref: commitSha, upstream: null };
919 }),
920 ),
921 Effect.mapError(gitFailure),
922 );
923
924 yield* Effect.gen(function* () {
925 if (!exists) {
926 yield* git.createBranch({ cwd: input.cwd, branch: localBranch, startPoint: target.ref });
927 }
928 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
929 if (exists) {
930 yield* runGit(
931 input.cwd,
932 "sync",
933 input.force === true
934 ? ["reset", "--hard", "--quiet", target.ref]
935 : ["merge", "--ff-only", "--quiet", target.ref],
936 );
937 }
938 // Set tracking after sync succeeds so a failed checkout preserves the existing upstream.
939 if (target.upstream !== null) {
940 yield* git.setBranchUpstream({ cwd: input.cwd, branch: localBranch, ...target.upstream });
941 }
942 }).pipe(Effect.mapError(gitFailure));
943 },
944 );
945
946 const providerError =
947 (
948 operation: string,
949 cwd: string,
950 context?: { readonly reference?: string; readonly repository?: string },
951 ) =>
952 (error: GitHubFailure) =>
953 new SourceControlProviderError({
954 provider: SourceControlProviderKind.make("github"),
955 operation,
956 cwd,
957 ...(context?.reference === undefined
958 ? {}
959 : {
960 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
961 context.reference,
962 ),
963 }),
964 ...(context?.repository === undefined
965 ? {}
966 : {
967 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
968 context.repository,
969 ),
970 }),
971 detail: error.detail,
972 cause: error.cause,
973 });
974
975 const readLinkSubject = Effect.fn("GitHubSourceControlProvider.readLinkSubject")(function* (
976 input: { readonly cwd: string; readonly url: URL },
977 endpoint: string,
978 ) {
979 const result = yield* api
980 .rest({
981 host: input.url.host,
982 operation: "resolveLink",
983 path: endpoint,
984 maxResponseBytes: 1_000_000,
985 })
986 .pipe(
987 Effect.timeout("3 seconds"),
988 Effect.mapError(
989 (cause) =>
990 new SourceControlProviderError({
991 provider: SourceControlProviderKind.make("github"),
992 operation: "resolveLink",
993 cwd: input.cwd,
994 detail: "The linked subject could not be read.",
995 cause,
996 }),
997 ),
998 );
999 const subject = yield* decodeLinkSubject(result.body).pipe(
1000 Effect.mapError(
1001 (cause) =>
1002 new SourceControlProviderError({
1003 provider: SourceControlProviderKind.make("github"),
1004 operation: "resolveLink.decode",
1005 cwd: input.cwd,
1006 detail: "The linked subject could not be read.",
1007 cause,
1008 }),
1009 ),
1010 );
1011 return { title: subject.title, body: subject.body ?? null };
1012 });
1013
1014 return SourceControlProvider.SourceControlProvider.of({
1015 kind: SourceControlProviderKind.make("github"),
1016 refineRepositoryIdentity,
1017 resolveRemoteWebHost: Effect.fn("GitHubSourceControlProvider.resolveRemoteWebHost")(
1018 ({ context }) => Effect.succeed(gitHubApiHostForRemote(context.remoteUrl)),
1019 ),
1020 // GitHub matches bare heads; read a full page to disambiguate forks by owner. A default branch
1021 // collides with most forks, so its owner-qualified lookup has GitHub filter by owner instead.
1022 headBranchProbe: ({ headSelectors, ownerHeadSelector }) => ({
1023 headSelectors: ownerHeadSelector
1024 ? [ownerHeadSelector]
1025 : headSelectors.filter((selector) => !selector.includes(":")),
1026 limit: 100,
1027 }),
1028 readChangeRequestTemplate: Effect.fn("GitHubSourceControlProvider.readChangeRequestTemplate")(
1029 function ({ cwd, treeish }) {
1030 return GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute);
1031 },
1032 ),
1033 // `createChangeRequest` targets what `resolveRepository` picks: GH_REPO when it parses, else
1034 // gh's pick among the checkout's remotes, led by the one `gh repo set-default` marked
1035 // (`gh-resolved`). An HTTPS remote keeps a non-default port in the context's host, and the
1036 // mark is then ignored.
1037 createsChangeRequestsIn: Effect.fn("GitHubSourceControlProvider.createsChangeRequestsIn")(
1038 function* ({ cwd, context, repository }) {
1039 const host = URL.canParse(context.provider.baseUrl)
1040 ? new URL(context.provider.baseUrl).host
1041 : null;
1042 const target = repository?.toLowerCase();
1043 const fromEnvironment = parseGitHubRepositorySelector(
1044 environment.GH_REPO ?? "",
1045 host ?? "",
1046 );
1047 if (fromEnvironment !== null) {
1048 const { host: targetHost, owner, name } = fromEnvironment;
1049 return (
1050 host !== null &&
1051 URL.canParse(`https://${targetHost}`) &&
1052 new URL(`https://${targetHost}`).host === host &&
1053 `${owner}/${name}`.toLowerCase() === target
1054 );
1055 }
1056 const { locator } = resolveGitHubRepository({
1057 ...(yield* readRemotes(cwd)),
1058 hostHint: host ?? undefined,
1059 defaultHost: host ?? "github.com",
1060 });
1061 return locator === null || `${locator.owner}/${locator.name}`.toLowerCase() === target;
1062 },
1063 ),
1064 // `gh pr create` run in the checkout, as an agent in a T3 worktree often does, takes its base
1065 // from this key.
1066 recordBranchBase: Effect.fn("GitHubSourceControlProvider.recordBranchBase")(function ({
1067 cwd,
1068 branch,
1069 baseBranch,
1070 }) {
1071 return git
1072 .writeConfigValue({ cwd, key: `branch.${branch}.gh-merge-base`, value: baseBranch })
1073 .pipe(
1074 Effect.catch((cause) =>
1075 Effect.logWarning("Could not record the branch base for gh", { cause }),
1076 ),
1077 );
1078 }),
1079 resolveLink: (input) => {
1080 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
1081 if (input.url.host !== "github.com") return undefined;
1082 const match = /^\/([\w.-]+)\/([\w.-]+)\/(?:pull|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
1083 input.url.pathname,
1084 );
1085 if (!match) return undefined;
1086 return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);
1087 },
1088 listChangeRequests: Effect.fn("GitHubSourceControlProvider.listChangeRequests")(
1089 function (input) {
1090 return (
1091 input.state === "open" ? Effect.succeed(true) : SourceControlRateLimit.Interactive
1092 ).pipe(
1093 Effect.flatMap((allowReserve) =>
1094 listByHead({
1095 cwd: input.cwd,
1096 headSelector: input.headSelector,
1097 state: input.state,
1098 limit: input.limit ?? (input.state === "open" ? 1 : 20),
1099 host: contextHost(input.context),
1100 context: input.context,
1101 repository: input.repository,
1102 allowReserve,
1103 }),
1104 ),
1105 Effect.map((records) => records.map(toChangeRequest)),
1106 Effect.mapError(
1107 providerError("listChangeRequests", input.cwd, { reference: input.headSelector }),
1108 ),
1109 );
1110 },
1111 ),
1112 getChangeRequest: Effect.fn("GitHubSourceControlProvider.getChangeRequest")(function (input) {
1113 return readPullRequest({ ...input, host: contextHost(input.context) }).pipe(
1114 Effect.map(toChangeRequest),
1115 Effect.mapError(
1116 providerError("getChangeRequest", input.cwd, { reference: input.reference }),
1117 ),
1118 );
1119 }),
1120 createsDraftChangeRequests: true,
1121 createChangeRequest: Effect.fn("GitHubSourceControlProvider.createChangeRequest")(
1122 function* (input) {
1123 const locator = yield* resolveRepository(input);
1124 const body = yield* fileSystem
1125 .readFileString(input.bodyFile)
1126 .pipe(
1127 Effect.mapError((cause) =>
1128 failure("The pull request description could not be read.", cause),
1129 ),
1130 );
1131 yield* rest({
1132 host: locator.host,
1133 operation: "createPullRequest",
1134 method: "POST",
1135 allowReserve: true,
1136 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}/pulls`,
1137 // Explicitly allow maintainer edits to match gh; the API default is undocumented.
1138 body: {
1139 base: input.baseRefName,
1140 head: input.headSelector,
1141 title: input.title,
1142 body,
1143 maintainer_can_modify: true,
1144 ...(input.draft === true ? { draft: true } : {}),
1145 },
1146 });
1147 },
1148 (effect, input) =>
1149 effect.pipe(
1150 Effect.mapError(
1151 providerError("createChangeRequest", input.cwd, { reference: input.headSelector }),
1152 ),
1153 ),
1154 ),
1155 getRepositoryCloneUrls: Effect.fn("GitHubSourceControlProvider.getRepositoryCloneUrls")(
1156 function* (input) {
1157 const fallbackHost = (
1158 input.host ??
1159 (yield* resolveRepository(input).pipe(
1160 Effect.map((locator) => locator.host),
1161 Effect.orElseSucceed(() => environment.GH_HOST ?? "github.com"),
1162 ))
1163 ).toLowerCase();
1164 const bareName = input.repository.trim().replace(/\.git$/i, "");
1165 const locator =
1166 parseGitHubRepositorySelector(input.repository, fallbackHost) ??
1167 (/^[^/\s]+$/.test(bareName)
1168 ? {
1169 host: fallbackHost,
1170 owner: yield* readViewerLogin(fallbackHost),
1171 name: bareName,
1172 }
1173 : null);
1174 if (locator === null) {
1175 const detail = "Repositories are named owner/name.";
1176 return yield* failure(
1177 detail,
1178 new GitHubRepositoryLookupError({ userFacingDetail: detail }),
1179 );
1180 }
1181 return repositoryCloneUrls(
1182 yield* readRepository(locator).pipe(
1183 Effect.mapError((error) => {
1184 if (!isGitHubApiNotFoundError(error.cause)) return error;
1185 const detail = SourceControlProvider.repositoryNotFoundDetail(
1186 `${locator.owner}/${locator.name}`,
1187 );
1188 return failure(
1189 detail,
1190 new GitHubRepositoryLookupError({ userFacingDetail: detail, cause: error.cause }),
1191 );
1192 }),
1193 ),
1194 );
1195 },
1196 (effect, input) =>
1197 effect.pipe(
1198 Effect.mapError(
1199 providerError("getRepositoryCloneUrls", input.cwd, {
1200 repository: input.repository,
1201 }),
1202 ),
1203 ),
1204 ),
1205 createRepository: Effect.fn("GitHubSourceControlProvider.createRepository")(
1206 function* (input) {
1207 const locator = parseGitHubRepositorySelector(
1208 input.repository,
1209 (environment.GH_HOST ?? "github.com").toLowerCase(),
1210 );
1211 const viewer = locator === null ? null : yield* readViewerLogin(locator.host);
1212 const owner = locator?.owner ?? viewer;
1213 const name = locator?.name ?? input.repository.trim();
1214 const host = locator?.host ?? (environment.GH_HOST?.trim().toLowerCase() || "github.com");
1215 const isViewer = viewer !== null && owner?.toLowerCase() === viewer.toLowerCase();
1216 const response = yield* rest(
1217 {
1218 host,
1219 operation: "createRepository",
1220 method: "POST",
1221 allowReserve: true,
1222 path:
1223 isViewer || owner === null ? "user/repos" : `orgs/${encodeURIComponent(owner)}/repos`,
1224 body: { name, private: input.visibility === "private" },
1225 },
1226 `No organization named ${owner ?? "that"} that this account can create repositories in.`,
1227 );
1228 const decoded = decodeRawRepository(response.body);
1229 if (Result.isFailure(decoded)) {
1230 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
1231 }
1232 return repositoryCloneUrls(decoded.success);
1233 },
1234 (effect, input) =>
1235 effect.pipe(
1236 Effect.mapError(
1237 providerError("createRepository", input.cwd, { repository: input.repository }),
1238 ),
1239 ),
1240 ),
1241 getDefaultBranch: Effect.fn("GitHubSourceControlProvider.getDefaultBranch")(
1242 function* (input) {
1243 const locator = yield* resolveRepository({
1244 cwd: input.cwd,
1245 host: contextHost(input.context),
1246 context: input.context,
1247 });
1248 const repository = yield* readRepository(locator);
1249 const branch = repository.default_branch?.trim() ?? "";
1250 return branch.length > 0 ? branch : null;
1251 },
1252 (effect, input) => effect.pipe(Effect.mapError(providerError("getDefaultBranch", input.cwd))),
1253 ),
1254 checkoutChangeRequest: Effect.fn("GitHubSourceControlProvider.checkoutChangeRequest")(
1255 function (input) {
1256 return checkoutPullRequest(input).pipe(
1257 Effect.mapError(
1258 providerError("checkoutChangeRequest", input.cwd, { reference: input.reference }),
1259 ),
1260 );
1261 },
1262 ),
1263 });
1264});