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

GitHubSourceControlProvider.ts

1,336 lines50.4 KB

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