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

TanStackSourceSourceControlProvider.ts

654 lines26.2 KB

1import {
2 requireSettingsSecretLiteral,
3 SourceControlProviderError,
4 type ChangeRequest,
5 type SourceControlProviderAuth,
6 type SourceControlProviderDiscoveryItem,
7} from "@t3tools/contracts";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9import {
10 isExecutableOnPath,
11 isMissingExecutable,
12 providerAuth,
13 type SourceControlManagedCliDiscoverySpec,
14} from "@t3tools/source-control-core/server/discovery";
15import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
16import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
17import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition";
18import * as DateTime from "effect/DateTime";
19import * as Effect from "effect/Effect";
20import * as FileSystem from "effect/FileSystem";
21import * as Option from "effect/Option";
22import * as Result from "effect/Result";
23import * as Schema from "effect/Schema";
24​
25import * as TanStackSource from "../shared/definition.ts";
26import * as TanStackSourceApi from "./TanStackSourceApi.ts";
27import { parseTanStackSourceAuthStatus } from "./tanStackSourceAuthStatus.ts";
28import * as TanStackSourceCredentials from "./TanStackSourceCredentials.ts";
29import * as Hosts from "./tanStackSourceHosts.ts";
30import * as Json from "./tanStackSourceJson.ts";
31​
32const HOST = TanStackSource.TANSTACK_SOURCE_HOST;
33/** Pull requests from one branch name, across forks, read in full when looking one up. */
34const MAX_BRANCH_MATCHES = 20;
35const LABEL = "TanStack Source";
36const LOGIN = `src auth login --web --hostname ${HOST}`;
37​
38const INSTALL_HINT = `Install the TanStack Source CLI with \`curl -fsSL https://${HOST}/install | sh\`, then run \`${LOGIN}\`, save a token in Settings, or set SRC_TOKEN on the server.`;
39​
40/** The account a request would use: SRC_TOKEN, else the one picked in Settings, else the active one. */
41export function effectiveAccount(
42 accounts: ReturnType<typeof parseTanStackSourceAuthStatus>,
43 choice: string | undefined,
44) {
45 const usable = accounts.filter((entry) => entry.host === HOST && entry.authenticated);
46 return (
47 usable.find((entry) => entry.environmentVariable !== null) ??
48 (choice === undefined ? undefined : usable.find((entry) => entry.account === choice)) ??
49 usable.find((entry) => entry.active) ??
50 usable[0]
51 );
53​
54const decodeUser = Schema.decodeEffect(Schema.fromJsonString(Json.SourceUser));
55​
56const authAccounts = (accounts: ReturnType<typeof parseTanStackSourceAuthStatus>) =>
57 accounts
58 .filter((entry) => entry.account !== "")
59 .map((entry) => ({
60 host: entry.host,
61 account: entry.account,
62 active: entry.active,
63 authenticated: entry.authenticated,
64 ...(entry.error === null ? {} : { error: entry.error }),
65 ...(entry.environmentVariable === null
66 ? {}
67 : { environmentVariable: entry.environmentVariable }),
68 }));
69​
70/**
71 * `src` has no version flag, so its sign-in status is the only probe. A saved token or SRC_TOKEN
72 * is checked against the API, since the CLI knows nothing of the first.
73 */
74export const makeDiscovery = Effect.gen(function* () {
75 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
76 const api = yield* TanStackSourceApi.TanStackSourceApi;
77 const environment = yield* HostProcess.Environment;
78​
79 const viewer = api.request({ host: HOST, operation: "discovery", path: "/user" }).pipe(
80 Effect.flatMap((raw) =>
81 decodeUser(raw).pipe(
82 Effect.mapError(
83 (cause) =>
84 new TanStackSourceApi.TanStackSourceApiError({
85 host: HOST,
86 operation: "discovery",
87 status: null,
88 reason: "failed",
89 detail: "TanStack Source returned an unreadable account.",
90 cause,
91 }),
92 ),
93 ),
94 ),
95 Effect.result,
96 );
97​
98 const probe = Effect.fn("TanStackSourceSourceControlProvider.discovery")(function* (cwd: string) {
99 const current = yield* sourceControlHost.settings
100 .getWithSecrets(TanStackSource.definition.kind)
101 .pipe(Effect.orElseSucceed(() => undefined));
102 const settings = readSourceControlHostSettings(
103 TanStackSource.settings,
104 current?.sourceControlHosts[TanStackSource.definition.kind],
105 );
106 // An absent src is never spawned; a saved token or SRC_TOKEN still answers through the API.
107 const status = (yield* isExecutableOnPath("src"))
108 ? yield* sourceControlHost.process
109 .run({
110 operation: "source-control.discovery.auth",
111 command: "src",
112 args: ["auth", "status"],
113 cwd,
114 env: { SRC_NO_TELEMETRY: "1" },
115 allowNonZeroExit: true,
116 timeoutMs: 5_000,
117 maxOutputBytes: 8_000,
118 appendTruncationMarker: true,
119 })
120 .pipe(Effect.result)
121 : undefined;
122 const installed =
123 status !== undefined && (Result.isSuccess(status) || !isMissingExecutable(status.failure));
124 const accounts =
125 status !== undefined && Result.isSuccess(status)
126 ? parseTanStackSourceAuthStatus(`${status.success.stdout}\n${status.success.stderr}`)
127 : [];
128 const item = (fields: {
129 readonly auth: SourceControlProviderAuth;
130 readonly available: boolean;
131 }): SourceControlProviderDiscoveryItem => ({
132 kind: TanStackSource.definition.kind,
133 label: LABEL,
134 executable: "src",
135 status: fields.available ? "available" : "missing",
136 version: Option.none(),
137 installHint: INSTALL_HINT,
138 detail: Option.none(),
139 auth:
140 accounts.length === 0 ? fields.auth : { ...fields.auth, accounts: authAccounts(accounts) },
141 });
142​
143 if (settings.hosts[HOST]?.enabled === false)
144 return item({
145 available: installed,
146 auth: providerAuth({
147 status: "unauthenticated",
148 host: HOST,
149 detail: `${HOST} is turned off in Settings → Source control & issues.`,
150 }),
151 });
152​
153 const saved = yield* Effect.result(
154 requireSettingsSecretLiteral(settings.tokens[HOST], current?.secretProviders ?? {}),
155 );
156 if (Result.isFailure(saved))
157 return item({
158 available: true,
159 auth: providerAuth({
160 status: "unauthenticated",
161 host: HOST,
162 detail: saved.failure.message,
163 }),
164 });
165 const savedToken = saved.success.trim() !== "";
166 const envToken = TanStackSourceCredentials.environmentToken(HOST, environment) !== null;
167 if (savedToken || envToken) {
168 const tokenSource = savedToken ? "the token saved in Settings" : "SRC_TOKEN";
169 const answer = yield* viewer;
170 return item({
171 available: true,
172 auth: Result.isSuccess(answer)
173 ? providerAuth({
174 status: "authenticated",
175 host: HOST,
176 account: answer.success.username,
177 detail: savedToken
178 ? "Using the token saved in Settings; it overrides SRC_TOKEN and the src login."
179 : "Using SRC_TOKEN from the server environment; it overrides the account chosen in Settings.",
180 })
181 : answer.failure.reason === "unauthenticated"
182 ? providerAuth({
183 status: "unauthenticated",
184 host: HOST,
185 detail: savedToken
186 ? "TanStack Source refused the token saved in Settings. Replace or remove it in Settings → Source control & issues."
187 : "TanStack Source refused the token in SRC_TOKEN. Replace it, or unset it to use `src auth login`.",
188 })
189 : providerAuth({
190 status: "unknown",
191 host: HOST,
192 detail: `Could not check ${tokenSource}: ${answer.failure.detail}`,
193 }),
194 });
195 }
196​
197 if (!installed)
198 return item({
199 available: false,
200 auth: providerAuth({ status: "unknown", detail: INSTALL_HINT }),
201 });
202 const chosen = effectiveAccount(accounts, settings.hosts[HOST]?.account);
203 if (chosen !== undefined)
204 return item({
205 available: true,
206 auth: providerAuth({ status: "authenticated", host: HOST, account: chosen.account }),
207 });
208 const failed = accounts.find((entry) => entry.host === HOST);
209 return item({
210 available: true,
211 auth: providerAuth({
212 status: status !== undefined && Result.isSuccess(status) ? "unauthenticated" : "unknown",
213 host: HOST,
214 detail: failed?.error ?? `Run \`${LOGIN}\` to sign the src CLI in.`,
215 }),
216 });
217 });
218​
219 return {
220 type: "managed-cli",
221 kind: TanStackSource.definition.kind,
222 label: LABEL,
223 installHint: INSTALL_HINT,
224 probe,
225 // Source's remotes are recognized by host alone, so an unknown remote is never one.
226 refineUnknownRemote: () => Effect.succeed(null),
227 } satisfies SourceControlManagedCliDiscoverySpec;
228});
229​
230const Repository = Schema.Struct({
231 owner: Schema.String,
232 name: Schema.String,
233 defaultBranch: Schema.NullOr(Schema.String),
234 cloneUrl: Schema.String,
235});
236​
237interface Target {
238 readonly host: Hosts.TanStackSourceHost;
239 readonly repository: string;
241​
242const cloneUrls = (target: Target, cloneUrl?: string) => {
243 const url = cloneUrl ?? `${Hosts.webRepositoryUrl(target.host, target.repository)}.git`;
244 // Source serves git over HTTPS only.
245 return { nameWithOwner: target.repository, url, sshUrl: url };
246};
247​
248export const make = Effect.gen(function* () {
249 const api = yield* TanStackSourceApi.TanStackSourceApi;
250 const host = yield* SourceControlHost.SourceControlHost;
251 const fileSystem = yield* FileSystem.FileSystem;
252​
253 const error = (operation: string, cwd: string, detail: string, cause?: unknown) =>
254 new SourceControlProviderError({
255 provider: TanStackSource.definition.kind,
256 operation,
257 cwd,
258 detail,
259 ...(cause === undefined ? {} : { cause }),
260 });
261 const read = <S extends Schema.Codec<unknown, unknown, never, never>>(
262 operation: string,
263 cwd: string,
264 request: Omit<TanStackSourceApi.TanStackSourceApiRequest, "operation">,
265 schema: S,
266 ) =>
267 api.request({ ...request, operation }).pipe(
268 Effect.mapError((cause) => error(operation, cwd, cause.detail, cause)),
269 Effect.flatMap((raw) =>
270 Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
271 Effect.mapError((cause) =>
272 error(operation, cwd, "TanStack Source returned an unreadable response.", cause),
273 ),
274 ),
275 ),
276 );
277​
278 const resolveTarget = Effect.fn("TanStackSourceSourceControlProvider.resolveTarget")(function* (
279 operation: string,
280 input: {
281 readonly cwd: string;
282 readonly context?: SourceControlProvider.SourceControlProviderContext;
283 readonly repository?: string;
284 },
285 ) {
286 const named =
287 input.repository === undefined ? null : Hosts.parseTanStackSourceRemote(input.repository);
288 if (named) return named;
289 if (input.repository !== undefined) {
290 const repository = Hosts.tanStackSourceRepositoryPath(input.repository);
291 if (repository !== null) return { host: HOST, repository } satisfies Target;
292 return yield* error(
293 operation,
294 input.cwd,
295 "A TanStack Source repository is named owner/name or by its source.tanstack.com URL.",
296 );
297 }
298 const remoteUrl =
299 input.context?.remoteUrl ??
300 (yield* host.git.resolvePrimaryRemoteName(input.cwd).pipe(
301 Effect.flatMap((remote) => host.git.readConfigValue(input.cwd, `remote.${remote}.url`)),
302 Effect.mapError((cause) =>
303 error(operation, input.cwd, "Could not read the TanStack Source remote.", cause),
304 ),
305 ));
306 const remote = remoteUrl ? Hosts.parseTanStackSourceRemote(remoteUrl) : null;
307 if (remote) return remote;
308 return yield* error(operation, input.cwd, "No TanStack Source repository remote was found.");
309 });
310​
311 const toChangeRequest = (target: Target, pull: Json.SourcePullDetail): ChangeRequest => {
312 const headRepository = pull.headRepo ?? target.repository;
313 const headBranch = Json.headBranchName(pull.head);
314 // A pull request synced from a GitHub fork names its head only by its pull ref.
315 const crossRepository =
316 headRepository.toLowerCase() !== target.repository.toLowerCase() ||
317 headBranch.startsWith("refs/");
318 const updatedAt = pull.mergedAt ?? pull.createdAt;
319 return {
320 provider: TanStackSource.definition.kind,
321 number: pull.number,
322 title: pull.title,
323 url: Json.pullUrl(target.host, target.repository, pull.number),
324 baseRefName: pull.base,
325 headRefName: headBranch,
326 ...(pull.headSha ? { headSha: pull.headSha } : {}),
327 state: pull.state,
328 ...(pull.draft ? { isDraft: true } : {}),
329 mergedAt: pull.mergedAt === null ? null : Json.iso(pull.mergedAt),
330 updatedAt: Option.some(DateTime.makeUnsafe(updatedAt)),
331 isCrossRepository: crossRepository,
332 headRepositoryNameWithOwner: headRepository,
333 headRepositoryOwnerLogin: headRepository.split("/")[0] ?? null,
334 };
335 };
336​
337 const readPull = (operation: string, cwd: string, target: Target, number: number) =>
338 read(
339 operation,
340 cwd,
341 { host: target.host, path: `/repos/${target.repository}/pulls/${number}` },
342 Json.SourcePullDetail,
343 ).pipe(Effect.map((pull) => toChangeRequest(target, pull)));
344​
345 const getPull = Effect.fn("TanStackSourceSourceControlProvider.getPull")(function* (input: {
346 readonly cwd: string;
347 readonly context?: SourceControlProvider.SourceControlProviderContext;
348 readonly reference: string;
349 }) {
350 const link = TanStackSource.parsePullRequestUrl(input.reference.trim());
351 const target: Target = link
352 ? { host: HOST, repository: link.repository }
353 : yield* resolveTarget("getChangeRequest", input);
354 const number = link ? link.number : Number(/^#?([1-9]\d*)$/u.exec(input.reference.trim())?.[1]);
355 if (!Number.isSafeInteger(number) || number < 1)
356 return yield* error(
357 "getChangeRequest",
358 input.cwd,
359 "A TanStack Source pull request is a number or a source.tanstack.com pull request URL.",
360 );
361 return yield* readPull("getChangeRequest", input.cwd, target, number);
362 });
363​
364 return SourceControlProvider.SourceControlProvider.of({
365 kind: TanStackSource.definition.kind,
366 repositoryNameFromRemoteUrl: (url) => Hosts.parseTanStackSourceRemote(url)?.repository ?? null,
367 getChangeRequest: getPull,
368 listChangeRequests: Effect.fn("TanStackSourceSourceControlProvider.listChangeRequests")(
369 function* (input) {
370 const target = yield* resolveTarget("listChangeRequests", input);
371 const source = SourceControlProvider.sourceControlRefFromInput(input);
372 const branch = SourceControlProvider.sourceBranch(input);
373 const limit = input.limit ?? 20;
374 const query = new URLSearchParams({ head: branch });
375 if (input.state !== "all") query.set("state", input.state);
376 const page = yield* read(
377 "listChangeRequests",
378 input.cwd,
379 { host: target.host, path: `/repos/${target.repository}/pulls?${query}` },
380 Json.SourcePulls,
381 );
382 // List rows name neither the base nor the head's repository, so matches are read in full
383 // and the limit counts only those whose head is the one asked for.
384 const matches = page.items
385 .filter((pull) => Json.headBranchName(pull.head) === branch)
386 .slice(0, MAX_BRANCH_MATCHES);
387 const details = yield* Effect.forEach(
388 matches,
389 (pull) => readPull("listChangeRequests", input.cwd, target, pull.number),
390 { concurrency: 4 },
391 );
392 const owned = details.filter(
393 (detail) =>
394 (!source?.repository ||
395 detail.headRepositoryNameWithOwner?.toLowerCase() ===
396 source.repository.toLowerCase()) &&
397 (!source?.owner ||
398 detail.headRepositoryOwnerLogin?.toLowerCase() === source.owner.toLowerCase()),
399 );
400 return owned.slice(0, limit);
401 },
402 ),
403 createsDraftChangeRequests: true,
404 privateChangeRequestRemote: Effect.fn(
405 "TanStackSourceSourceControlProvider.privateChangeRequestRemote",
406 )(function* (input) {
407 const target = yield* resolveTarget("privateChangeRequestRemote", input);
408 const companion = yield* read(
409 "privateChangeRequestRemote",
410 input.cwd,
411 { host: target.host, method: "POST", path: `/repos/${target.repository}/private-remote` },
412 Repository,
413 );
414 return { url: companion.cloneUrl, repository: `${companion.owner}/${companion.name}` };
415 }),
416 createChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.createChangeRequest")(
417 function* (input) {
418 const target = yield* resolveTarget("createChangeRequest", {
419 ...input,
420 ...(input.target?.repository ? { repository: input.target.repository } : {}),
421 });
422 const source = SourceControlProvider.sourceControlRefFromInput(input);
423 if (
424 (source?.repository &&
425 source.repository.toLowerCase() !== target.repository.toLowerCase()) ||
426 (source?.owner &&
427 source.owner.toLowerCase() !== target.repository.split("/")[0]?.toLowerCase())
428 )
429 return yield* error(
430 "createChangeRequest",
431 input.cwd,
432 "TanStack Source opens pull requests from a branch of the same repository. Push the branch there first.",
433 );
434 const body = yield* fileSystem
435 .readFileString(input.bodyFile)
436 .pipe(
437 Effect.mapError((cause) =>
438 error(
439 "createChangeRequest",
440 input.cwd,
441 "Could not read the pull request description.",
442 cause,
443 ),
444 ),
445 );
446 yield* api
447 .request({
448 host: target.host,
449 operation: "createChangeRequest",
450 method: "POST",
451 path: `/repos/${target.repository}/pulls`,
452 body: {
453 title: input.title,
454 head: SourceControlProvider.sourceBranch(input),
455 base: input.target?.refName ?? input.baseRefName,
456 ...(body.trim().length === 0 ? {} : { body }),
457 ...(input.draft === true ? { draft: true } : {}),
458 ...(input.private === true ? { private: true } : {}),
459 },
460 })
461 .pipe(
462 Effect.mapError((cause) =>
463 error("createChangeRequest", input.cwd, cause.detail, cause),
464 ),
465 );
466 },
467 ),
468 getRepositoryCloneUrls: Effect.fn("TanStackSourceSourceControlProvider.getRepositoryCloneUrls")(
469 function* (input) {
470 const target = yield* resolveTarget("getRepositoryCloneUrls", input);
471 const repository = yield* read(
472 "getRepositoryCloneUrls",
473 input.cwd,
474 { host: target.host, path: `/repos/${target.repository}` },
475 Repository,
476 );
477 return cloneUrls(
478 { host: target.host, repository: `${repository.owner}/${repository.name}` },
479 repository.cloneUrl,
480 );
481 },
482 ),
483 createRepository: Effect.fn("TanStackSourceSourceControlProvider.createRepository")(
484 function* (input) {
485 const target = yield* resolveTarget("createRepository", input);
486 const [owner, name] = target.repository.split("/");
487 const created = yield* read(
488 "createRepository",
489 input.cwd,
490 {
491 host: target.host,
492 method: "POST",
493 path: "/repos",
494 body: { name, owner, visibility: input.visibility },
495 },
496 Repository,
497 );
498 return cloneUrls(
499 { host: target.host, repository: `${created.owner}/${created.name}` },
500 created.cloneUrl,
501 );
502 },
503 ),
504 getDefaultBranch: Effect.fn("TanStackSourceSourceControlProvider.getDefaultBranch")(
505 function* (input) {
506 const target = yield* resolveTarget("getDefaultBranch", input);
507 const repository = yield* read(
508 "getDefaultBranch",
509 input.cwd,
510 { host: target.host, path: `/repos/${target.repository}` },
511 Repository,
512 );
513 return repository.defaultBranch;
514 },
515 ),
516 // A pull request's head is published as `refs/pull/<n>/head`, forks and GitHub sync too. A
517 // private one has no such ref: its branch is read from the companion repository.
518 checkoutChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.checkoutChangeRequest")(
519 function* (input) {
520 const pull = yield* getPull(input);
521 const target = yield* resolveTarget("checkoutChangeRequest", input).pipe(
522 Effect.orElseSucceed(() => null),
523 );
524 const pullRepository = Hosts.tanStackSourceRepositoryPath(
525 new URL(pull.url).pathname.split("/pull/")[0] ?? "",
526 );
527 const git = host.git;
528 yield* Effect.gen(function* () {
529 const remoteName =
530 input.context &&
531 target !== null &&
532 pullRepository !== null &&
533 target.repository.toLowerCase() === pullRepository.toLowerCase()
534 ? input.context.remoteName
535 : yield* git.ensureRemote({
536 cwd: input.cwd,
537 preferredName: "source",
538 url: `${Hosts.webRepositoryUrl(HOST, pullRepository ?? "")}.git`,
539 });
540 const operation = "TanStackSourceSourceControlProvider.checkoutChangeRequest";
541 const branches = yield* git.listLocalBranchNames(input.cwd);
542 const companion =
543 pullRepository !== null &&
544 pull.headRepositoryNameWithOwner?.toLowerCase() ===
545 `${pullRepository}.private`.toLowerCase()
546 ? pull.headRepositoryNameWithOwner
547 : null;
548 if (!pull.isCrossRepository || companion !== null) {
549 const localBranch = pull.headRefName;
550 const remoteBranch = {
551 cwd: input.cwd,
552 remoteName:
553 companion === null
554 ? remoteName
555 : yield* git.ensureRemote({
556 cwd: input.cwd,
557 preferredName: companion.split("/")[0] ?? "private",
558 url: `${Hosts.webRepositoryUrl(HOST, companion)}.git`,
559 }),
560 remoteBranch: localBranch,
561 };
562 if (input.force !== true && !branches.includes(localBranch))
563 yield* git.fetchRemoteBranch({ ...remoteBranch, localBranch });
564 else yield* git.fetchRemoteTrackingBranch(remoteBranch);
565 if (input.force === true)
566 yield* git.execute({
567 operation,
568 cwd: input.cwd,
569 // The upstream is recorded next, through the host's serialized config write.
570 args: [
571 "checkout",
572 "--no-track",
573 "-B",
574 localBranch,
575 `refs/remotes/${remoteBranch.remoteName}/${localBranch}`,
576 "--",
577 ],
578 });
579 yield* git.setBranchUpstream({ ...remoteBranch, branch: localBranch });
580 // Whatever push defaults say, this branch must not be published to the public remote.
581 if (companion !== null)
582 yield* git.writeConfigValue({
583 cwd: input.cwd,
584 key: `branch.${localBranch}.pushRemote`,
585 value: remoteBranch.remoteName,
586 });
587 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
588 return;
589 }
590 // A fork's head, or one synced from GitHub, is only reachable through its pull ref.
591 const localBranch = `pr-${pull.number}`;
592 const tracking = `refs/remotes/${remoteName}/pull/${pull.number}`;
593 yield* git.execute({
594 operation,
595 cwd: input.cwd,
596 args: ["fetch", "--no-tags", remoteName, `+refs/pull/${pull.number}/head:${tracking}`],
597 });
598 const exists = branches.includes(localBranch);
599 // T3 records which pull request it made `pr-<n>` for, and reuses only that branch, and
600 // only while it holds nothing the pull request lacks: an unrelated branch of the name,
601 // or local commits, are never switched to, moved or lost.
602 const ownerKey = `branch.${localBranch}.t3TanstackSourcePull`;
603 const owner = `${pullRepository ?? ""}#${pull.number}`;
604 if (exists && input.force !== true) {
605 const recorded = yield* git
606 .readConfigValue(input.cwd, ownerKey)
607 .pipe(Effect.orElseSucceed(() => null));
608 const behind =
609 recorded === owner &&
610 (yield* git
611 .execute({
612 operation,
613 cwd: input.cwd,
614 args: ["merge-base", "--is-ancestor", `refs/heads/${localBranch}`, tracking],
615 })
616 .pipe(
617 Effect.as(true),
618 Effect.orElseSucceed(() => false),
619 ));
620 if (!behind)
621 return yield* error(
622 "checkoutChangeRequest",
623 input.cwd,
624 recorded === owner
625 ? `Local branch ${localBranch} has commits pull request #${pull.number} does not. Rename it, or check out with force to replace it.`
626 : `Local branch ${localBranch} was not made for pull request #${pull.number}. Rename it, or check out with force to replace it.`,
627 );
628 }
629 if (exists)
630 yield* git.execute({
631 operation,
632 cwd: input.cwd,
633 args: ["checkout", "--no-track", "-B", localBranch, tracking, "--"],
634 });
635 else
636 yield* git.createBranch({ cwd: input.cwd, branch: localBranch, startPoint: tracking });
637 yield* git.writeConfigValue({ cwd: input.cwd, key: ownerKey, value: owner });
638 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
639 }).pipe(
640 Effect.mapError((cause) =>
641 cause._tag === "SourceControlProviderError"
642 ? cause
643 : error(
644 "checkoutChangeRequest",
645 input.cwd,
646 "Could not check out the TanStack Source pull request.",
647 cause,
648 ),
649 ),
650 );
651 },
652 ),
653 });
654});