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

GitHubSourceControlProvider.ts

1,308 lines49.3 KB

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