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