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

GitHubSourceControlProvider.ts

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