Open History to see the last commit
1import { Cache, Data, Duration, Effect, Exit, FileSystem, Layer, Path } from "effect";
2
3import { GitCommandError } from "../Errors.ts";
4import { GitService } from "../Services/GitService.ts";
5import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
6
7const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
8const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
9const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
10
11class StatusUpstreamRefreshCacheKey extends Data.Class<{
12 cwd: string;
13 upstreamRef: string;
14 remoteName: string;
15 upstreamBranch: string;
16}> {}
17
18interface ExecuteGitOptions {
19 timeoutMs?: number | undefined;
20 allowNonZeroExit?: boolean | undefined;
21 fallbackErrorMessage?: string | undefined;
22}
23
24function parseBranchAb(value: string): { ahead: number; behind: number } {
25 const match = value.match(/^\+(\d+)\s+-(\d+)$/);
26 if (!match) return { ahead: 0, behind: 0 };
27 return {
28 ahead: Number(match[1] ?? "0"),
29 behind: Number(match[2] ?? "0"),
30 };
31}
32
33function parseNumstatEntries(
34 stdout: string,
35): Array<{ path: string; insertions: number; deletions: number }> {
36 const entries: Array<{ path: string; insertions: number; deletions: number }> = [];
37 for (const line of stdout.split(/\r?\n/g)) {
38 if (line.trim().length === 0) continue;
39 const [addedRaw, deletedRaw, ...pathParts] = line.split("\t");
40 const rawPath =
41 pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim();
42 if (rawPath.length === 0) continue;
43 const added = Number.parseInt(addedRaw ?? "0", 10);
44 const deleted = Number.parseInt(deletedRaw ?? "0", 10);
45 const renameArrowIndex = rawPath.indexOf(" => ");
46 const normalizedPath =
47 renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath;
48 entries.push({
49 path: normalizedPath.length > 0 ? normalizedPath : rawPath,
50 insertions: Number.isFinite(added) ? added : 0,
51 deletions: Number.isFinite(deleted) ? deleted : 0,
52 });
53 }
54 return entries;
55}
56
57function parsePorcelainPath(line: string): string | null {
58 if (line.startsWith("? ") || line.startsWith("! ")) {
59 const simple = line.slice(2).trim();
60 return simple.length > 0 ? simple : null;
61 }
62
63 if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) {
64 return null;
65 }
66
67 const tabIndex = line.indexOf("\t");
68 if (tabIndex >= 0) {
69 const fromTab = line.slice(tabIndex + 1);
70 const [filePath] = fromTab.split("\t");
71 return filePath?.trim().length ? filePath.trim() : null;
72 }
73
74 const parts = line.trim().split(/\s+/g);
75 const filePath = parts.at(-1) ?? "";
76 return filePath.length > 0 ? filePath : null;
77}
78
79function commandLabel(args: readonly string[]): string {
80 return `git ${args.join(" ")}`;
81}
82
83function createGitCommandError(
84 operation: string,
85 cwd: string,
86 args: readonly string[],
87 detail: string,
88 cause?: unknown,
89): GitCommandError {
90 return new GitCommandError({
91 operation,
92 command: commandLabel(args),
93 cwd,
94 detail,
95 ...(cause !== undefined ? { cause } : {}),
96 });
97}
98
99const makeGitCore = Effect.gen(function* () {
100 const git = yield* GitService;
101 const fileSystem = yield* FileSystem.FileSystem;
102 const path = yield* Path.Path;
103
104 const executeGit = (
105 operation: string,
106 cwd: string,
107 args: readonly string[],
108 options: ExecuteGitOptions = {},
109 ): Effect.Effect<{ code: number; stdout: string; stderr: string }, GitCommandError> =>
110 git
111 .execute({
112 operation,
113 cwd,
114 args,
115 allowNonZeroExit: true,
116 ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
117 })
118 .pipe(
119 Effect.flatMap((result) => {
120 if (options.allowNonZeroExit || result.code === 0) {
121 return Effect.succeed(result);
122 }
123 const stderr = result.stderr.trim();
124 if (stderr.length > 0) {
125 return Effect.fail(createGitCommandError(operation, cwd, args, stderr));
126 }
127 if (options.fallbackErrorMessage) {
128 return Effect.fail(
129 createGitCommandError(operation, cwd, args, options.fallbackErrorMessage),
130 );
131 }
132 return Effect.fail(
133 createGitCommandError(
134 operation,
135 cwd,
136 args,
137 `${commandLabel(args)} failed: code=${result.code ?? "null"}`,
138 ),
139 );
140 }),
141 );
142
143 const runGit = (
144 operation: string,
145 cwd: string,
146 args: readonly string[],
147 allowNonZeroExit = false,
148 ): Effect.Effect<void, GitCommandError> =>
149 executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(Effect.asVoid);
150
151 const runGitStdout = (
152 operation: string,
153 cwd: string,
154 args: readonly string[],
155 allowNonZeroExit = false,
156 ): Effect.Effect<string, GitCommandError> =>
157 executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(
158 Effect.map((result) => result.stdout),
159 );
160
161 const resolveCurrentUpstream = (
162 cwd: string,
163 ): Effect.Effect<
164 { upstreamRef: string; remoteName: string; upstreamBranch: string } | null,
165 GitCommandError
166 > =>
167 Effect.gen(function* () {
168 const upstreamRef = yield* runGitStdout(
169 "GitCore.resolveCurrentUpstream",
170 cwd,
171 ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"],
172 true,
173 ).pipe(Effect.map((stdout) => stdout.trim()));
174
175 if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") {
176 return null;
177 }
178
179 const separatorIndex = upstreamRef.indexOf("/");
180 if (separatorIndex <= 0) {
181 return null;
182 }
183 const remoteName = upstreamRef.slice(0, separatorIndex);
184 const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
185 if (remoteName.length === 0 || upstreamBranch.length === 0) {
186 return null;
187 }
188
189 return {
190 upstreamRef,
191 remoteName,
192 upstreamBranch,
193 };
194 });
195
196 const fetchUpstreamRef = (
197 cwd: string,
198 upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
199 ): Effect.Effect<void, GitCommandError> => {
200 const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
201 return runGit(
202 "GitCore.fetchUpstreamRef",
203 cwd,
204 ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
205 true,
206 );
207 };
208
209 const fetchUpstreamRefForStatus = (
210 cwd: string,
211 upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
212 ): Effect.Effect<void, GitCommandError> => {
213 const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
214 return executeGit(
215 "GitCore.fetchUpstreamRefForStatus",
216 cwd,
217 ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
218 {
219 allowNonZeroExit: true,
220 timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
221 },
222 ).pipe(Effect.asVoid);
223 };
224
225 const statusUpstreamRefreshCache = yield* Cache.makeWith({
226 capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
227 lookup: (cacheKey: StatusUpstreamRefreshCacheKey) =>
228 Effect.gen(function* () {
229 yield* fetchUpstreamRefForStatus(cacheKey.cwd, {
230 upstreamRef: cacheKey.upstreamRef,
231 remoteName: cacheKey.remoteName,
232 upstreamBranch: cacheKey.upstreamBranch,
233 });
234 return true as const;
235 }),
236 // Keep successful refreshes warm; drop failures immediately so next request can retry.
237 timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_UPSTREAM_REFRESH_INTERVAL : Duration.zero),
238 });
239
240 const refreshStatusUpstreamIfStale = (cwd: string): Effect.Effect<void, GitCommandError> =>
241 Effect.gen(function* () {
242 const upstream = yield* resolveCurrentUpstream(cwd);
243 if (!upstream) return;
244 yield* Cache.get(
245 statusUpstreamRefreshCache,
246 new StatusUpstreamRefreshCacheKey({
247 cwd,
248 upstreamRef: upstream.upstreamRef,
249 remoteName: upstream.remoteName,
250 upstreamBranch: upstream.upstreamBranch,
251 }),
252 );
253 });
254
255 const refreshCheckedOutBranchUpstream = (cwd: string): Effect.Effect<void, GitCommandError> =>
256 Effect.gen(function* () {
257 const upstream = yield* resolveCurrentUpstream(cwd);
258 if (!upstream) return;
259 yield* fetchUpstreamRef(cwd, upstream);
260 });
261
262 const readBranchRecency = (cwd: string): Effect.Effect<Map<string, number>, GitCommandError> =>
263 Effect.gen(function* () {
264 const branchRecency = yield* executeGit(
265 "GitCore.readBranchRecency",
266 cwd,
267 ["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
268 {
269 timeoutMs: 15_000,
270 allowNonZeroExit: true,
271 },
272 );
273
274 const branchLastCommit = new Map<string, number>();
275 if (branchRecency.code !== 0) {
276 return branchLastCommit;
277 }
278
279 for (const line of branchRecency.stdout.split("\n")) {
280 if (line.length === 0) {
281 continue;
282 }
283 const [name, lastCommitRaw] = line.split("\t");
284 if (!name) {
285 continue;
286 }
287 const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10);
288 branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0);
289 }
290
291 return branchLastCommit;
292 });
293
294 const statusDetails: GitCoreShape["statusDetails"] = (cwd) =>
295 Effect.gen(function* () {
296 yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.catch(() => Effect.void));
297
298 const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all(
299 [
300 runGitStdout("GitCore.statusDetails.status", cwd, [
301 "status",
302 "--porcelain=2",
303 "--branch",
304 ]),
305 runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]),
306 runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, [
307 "diff",
308 "--cached",
309 "--numstat",
310 ]),
311 ],
312 { concurrency: "unbounded" },
313 );
314
315 let branch: string | null = null;
316 let upstreamRef: string | null = null;
317 let aheadCount = 0;
318 let behindCount = 0;
319 let hasWorkingTreeChanges = false;
320 const changedFilesWithoutNumstat = new Set<string>();
321
322 for (const line of statusStdout.split(/\r?\n/g)) {
323 if (line.startsWith("# branch.head ")) {
324 const value = line.slice("# branch.head ".length).trim();
325 branch = value.startsWith("(") ? null : value;
326 continue;
327 }
328 if (line.startsWith("# branch.upstream ")) {
329 const value = line.slice("# branch.upstream ".length).trim();
330 upstreamRef = value.length > 0 ? value : null;
331 continue;
332 }
333 if (line.startsWith("# branch.ab ")) {
334 const value = line.slice("# branch.ab ".length).trim();
335 const parsed = parseBranchAb(value);
336 aheadCount = parsed.ahead;
337 behindCount = parsed.behind;
338 continue;
339 }
340 if (line.trim().length > 0 && !line.startsWith("#")) {
341 hasWorkingTreeChanges = true;
342 const pathValue = parsePorcelainPath(line);
343 if (pathValue) changedFilesWithoutNumstat.add(pathValue);
344 }
345 }
346 const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
347 const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
348 const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
349 for (const entry of [...stagedEntries, ...unstagedEntries]) {
350 const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };
351 existing.insertions += entry.insertions;
352 existing.deletions += entry.deletions;
353 fileStatMap.set(entry.path, existing);
354 }
355
356 let insertions = 0;
357 let deletions = 0;
358 const files = Array.from(fileStatMap.entries())
359 .map(([filePath, stat]) => {
360 insertions += stat.insertions;
361 deletions += stat.deletions;
362 return { path: filePath, insertions: stat.insertions, deletions: stat.deletions };
363 })
364 .toSorted((a, b) => a.path.localeCompare(b.path));
365
366 for (const filePath of changedFilesWithoutNumstat) {
367 if (fileStatMap.has(filePath)) continue;
368 files.push({ path: filePath, insertions: 0, deletions: 0 });
369 }
370 files.sort((a, b) => a.path.localeCompare(b.path));
371
372 return {
373 branch,
374 upstreamRef,
375 hasWorkingTreeChanges,
376 workingTree: {
377 files,
378 insertions,
379 deletions,
380 },
381 hasUpstream: upstreamRef !== null,
382 aheadCount,
383 behindCount,
384 };
385 });
386
387 const status: GitCoreShape["status"] = (input) =>
388 statusDetails(input.cwd).pipe(
389 Effect.map((details) => ({
390 branch: details.branch,
391 hasWorkingTreeChanges: details.hasWorkingTreeChanges,
392 workingTree: details.workingTree,
393 hasUpstream: details.hasUpstream,
394 aheadCount: details.aheadCount,
395 behindCount: details.behindCount,
396 pr: null,
397 })),
398 );
399
400 const prepareCommitContext: GitCoreShape["prepareCommitContext"] = (cwd) =>
401 Effect.gen(function* () {
402 yield* runGit("GitCore.prepareCommitContext.addAll", cwd, ["add", "-A"]);
403
404 const stagedSummary = yield* runGitStdout("GitCore.prepareCommitContext.stagedSummary", cwd, [
405 "diff",
406 "--cached",
407 "--name-status",
408 ]).pipe(Effect.map((stdout) => stdout.trim()));
409 if (stagedSummary.length === 0) {
410 return null;
411 }
412
413 const stagedPatch = yield* runGitStdout("GitCore.prepareCommitContext.stagedPatch", cwd, [
414 "diff",
415 "--cached",
416 "--patch",
417 "--minimal",
418 ]);
419
420 return {
421 stagedSummary,
422 stagedPatch,
423 };
424 });
425
426 const commit: GitCoreShape["commit"] = (cwd, subject, body) =>
427 Effect.gen(function* () {
428 const args = ["commit", "-m", subject];
429 const trimmedBody = body.trim();
430 if (trimmedBody.length > 0) {
431 args.push("-m", trimmedBody);
432 }
433 yield* runGit("GitCore.commit.commit", cwd, args);
434 const commitSha = yield* runGitStdout("GitCore.commit.revParseHead", cwd, [
435 "rev-parse",
436 "HEAD",
437 ]).pipe(Effect.map((stdout) => stdout.trim()));
438
439 return { commitSha };
440 });
441
442 const pushCurrentBranch: GitCoreShape["pushCurrentBranch"] = (cwd, fallbackBranch) =>
443 Effect.gen(function* () {
444 const details = yield* statusDetails(cwd);
445 const branch = details.branch ?? fallbackBranch;
446 if (!branch) {
447 return yield* createGitCommandError(
448 "GitCore.pushCurrentBranch",
449 cwd,
450 ["push"],
451 "Cannot push from detached HEAD.",
452 );
453 }
454
455 if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {
456 return {
457 status: "skipped_up_to_date" as const,
458 branch,
459 ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
460 };
461 }
462
463 if (!details.hasUpstream) {
464 yield* runGit("GitCore.pushCurrentBranch.pushWithUpstream", cwd, [
465 "push",
466 "-u",
467 "origin",
468 branch,
469 ]);
470 return {
471 status: "pushed" as const,
472 branch,
473 upstreamBranch: `origin/${branch}`,
474 setUpstream: true,
475 };
476 }
477
478 yield* runGit("GitCore.pushCurrentBranch.push", cwd, ["push"]);
479 return {
480 status: "pushed" as const,
481 branch,
482 ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
483 setUpstream: false,
484 };
485 });
486
487 const pullCurrentBranch: GitCoreShape["pullCurrentBranch"] = (cwd) =>
488 Effect.gen(function* () {
489 const details = yield* statusDetails(cwd);
490 const branch = details.branch;
491 if (!branch) {
492 return yield* createGitCommandError(
493 "GitCore.pullCurrentBranch",
494 cwd,
495 ["pull", "--ff-only"],
496 "Cannot pull from detached HEAD.",
497 );
498 }
499 if (!details.hasUpstream) {
500 return yield* createGitCommandError(
501 "GitCore.pullCurrentBranch",
502 cwd,
503 ["pull", "--ff-only"],
504 "Current branch has no upstream configured. Push with upstream first.",
505 );
506 }
507 const beforeSha = yield* runGitStdout(
508 "GitCore.pullCurrentBranch.beforeSha",
509 cwd,
510 ["rev-parse", "HEAD"],
511 true,
512 ).pipe(Effect.map((stdout) => stdout.trim()));
513 yield* executeGit("GitCore.pullCurrentBranch.pull", cwd, ["pull", "--ff-only"], {
514 timeoutMs: 30_000,
515 fallbackErrorMessage: "git pull failed",
516 });
517 const afterSha = yield* runGitStdout(
518 "GitCore.pullCurrentBranch.afterSha",
519 cwd,
520 ["rev-parse", "HEAD"],
521 true,
522 ).pipe(Effect.map((stdout) => stdout.trim()));
523
524 const refreshed = yield* statusDetails(cwd);
525 return {
526 status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
527 branch,
528 upstreamBranch: refreshed.upstreamRef,
529 };
530 });
531
532 const readRangeContext: GitCoreShape["readRangeContext"] = (cwd, baseBranch) =>
533 Effect.gen(function* () {
534 const range = `${baseBranch}..HEAD`;
535 const [commitSummary, diffSummary, diffPatch] = yield* Effect.all(
536 [
537 runGitStdout("GitCore.readRangeContext.log", cwd, ["log", "--oneline", range]),
538 runGitStdout("GitCore.readRangeContext.diffStat", cwd, ["diff", "--stat", range]),
539 runGitStdout("GitCore.readRangeContext.diffPatch", cwd, [
540 "diff",
541 "--patch",
542 "--minimal",
543 range,
544 ]),
545 ],
546 { concurrency: "unbounded" },
547 );
548
549 return {
550 commitSummary,
551 diffSummary,
552 diffPatch,
553 };
554 });
555
556 const readConfigValue: GitCoreShape["readConfigValue"] = (cwd, key) =>
557 runGitStdout("GitCore.readConfigValue", cwd, ["config", "--get", key], true).pipe(
558 Effect.map((stdout) => stdout.trim()),
559 Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),
560 );
561
562 const listBranches: GitCoreShape["listBranches"] = (input) =>
563 Effect.gen(function* () {
564 const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
565 Effect.catch(() => Effect.succeed(new Map<string, number>())),
566 );
567 const result = yield* executeGit(
568 "GitCore.listBranches.branchNoColor",
569 input.cwd,
570 ["branch", "--no-color"],
571 {
572 timeoutMs: 10_000,
573 allowNonZeroExit: true,
574 },
575 );
576
577 if (result.code !== 0) {
578 const stderr = result.stderr.trim();
579 if (stderr.toLowerCase().includes("not a git repository")) {
580 return { branches: [], isRepo: false };
581 }
582 return yield* createGitCommandError(
583 "GitCore.listBranches",
584 input.cwd,
585 ["branch", "--no-color"],
586 stderr || "git branch failed",
587 );
588 }
589
590 const [defaultRef, worktreeList, branchLastCommit] = yield* Effect.all(
591 [
592 executeGit(
593 "GitCore.listBranches.defaultRef",
594 input.cwd,
595 ["symbolic-ref", "refs/remotes/origin/HEAD"],
596 {
597 timeoutMs: 5_000,
598 allowNonZeroExit: true,
599 },
600 ),
601 executeGit(
602 "GitCore.listBranches.worktreeList",
603 input.cwd,
604 ["worktree", "list", "--porcelain"],
605 {
606 timeoutMs: 5_000,
607 allowNonZeroExit: true,
608 },
609 ),
610 branchRecencyPromise,
611 ],
612 { concurrency: "unbounded" },
613 );
614
615 const defaultBranch =
616 defaultRef.code === 0
617 ? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
618 : null;
619
620 const worktreeMap = new Map<string, string>();
621 if (worktreeList.code === 0) {
622 let currentPath: string | null = null;
623 for (const line of worktreeList.stdout.split("\n")) {
624 if (line.startsWith("worktree ")) {
625 const candidatePath = line.slice("worktree ".length);
626 const exists = yield* fileSystem.stat(candidatePath).pipe(
627 Effect.map(() => true),
628 Effect.catch(() => Effect.succeed(false)),
629 );
630 currentPath = exists ? candidatePath : null;
631 } else if (line.startsWith("branch refs/heads/") && currentPath) {
632 worktreeMap.set(line.slice("branch refs/heads/".length), currentPath);
633 } else if (line === "") {
634 currentPath = null;
635 }
636 }
637 }
638
639 const branches = result.stdout
640 .split("\n")
641 .map((line) => line.trim())
642 .filter((line) => line.length > 0)
643 .map((line) => {
644 const name = line.replace(/^[*+]\s+/, "");
645 return {
646 name,
647 current: line.startsWith("* "),
648 isDefault: name === defaultBranch,
649 worktreePath: worktreeMap.get(name) ?? null,
650 };
651 })
652 .toSorted((a, b) => {
653 const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
654 const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
655 if (aPriority !== bPriority) return aPriority - bPriority;
656
657 const aLastCommit = branchLastCommit.get(a.name) ?? 0;
658 const bLastCommit = branchLastCommit.get(b.name) ?? 0;
659 if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
660 return a.name.localeCompare(b.name);
661 });
662
663 return { branches, isRepo: true };
664 });
665
666 const createWorktree: GitCoreShape["createWorktree"] = (input) =>
667 Effect.gen(function* () {
668 const sanitizedBranch = input.newBranch.replace(/\//g, "-");
669 const repoName = path.basename(input.cwd);
670 const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? "/tmp";
671 const worktreePath =
672 input.path ?? path.join(homeDir, ".t3", "worktrees", repoName, sanitizedBranch);
673
674 yield* executeGit(
675 "GitCore.createWorktree",
676 input.cwd,
677 ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch],
678 {
679 fallbackErrorMessage: "git worktree add failed",
680 },
681 );
682
683 return {
684 worktree: {
685 path: worktreePath,
686 branch: input.newBranch,
687 },
688 };
689 });
690
691 const removeWorktree: GitCoreShape["removeWorktree"] = (input) =>
692 Effect.gen(function* () {
693 const args = ["worktree", "remove"];
694 if (input.force) {
695 args.push("--force");
696 }
697 args.push(input.path);
698 yield* executeGit("GitCore.removeWorktree", input.cwd, args, {
699 timeoutMs: 15_000,
700 fallbackErrorMessage: "git worktree remove failed",
701 }).pipe(
702 Effect.mapError((error) =>
703 createGitCommandError(
704 "GitCore.removeWorktree",
705 input.cwd,
706 args,
707 `${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`,
708 error,
709 ),
710 ),
711 );
712 });
713
714 const createBranch: GitCoreShape["createBranch"] = (input) =>
715 executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {
716 timeoutMs: 10_000,
717 fallbackErrorMessage: "git branch create failed",
718 }).pipe(Effect.asVoid);
719
720 const checkoutBranch: GitCoreShape["checkoutBranch"] = (input) =>
721 Effect.gen(function* () {
722 yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, ["checkout", input.branch], {
723 timeoutMs: 10_000,
724 fallbackErrorMessage: "git checkout failed",
725 });
726
727 // Refresh upstream refs in the background so checkout remains responsive.
728 yield* Effect.sync(() => {
729 void Effect.runPromise(
730 refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
731 );
732 });
733 });
734
735 const initRepo: GitCoreShape["initRepo"] = (input) =>
736 executeGit("GitCore.initRepo", input.cwd, ["init"], {
737 timeoutMs: 10_000,
738 fallbackErrorMessage: "git init failed",
739 }).pipe(Effect.asVoid);
740
741 return {
742 status,
743 statusDetails,
744 prepareCommitContext,
745 commit,
746 pushCurrentBranch,
747 pullCurrentBranch,
748 readRangeContext,
749 readConfigValue,
750 listBranches,
751 createWorktree,
752 removeWorktree,
753 createBranch,
754 checkoutBranch,
755 initRepo,
756 } satisfies GitCoreShape;
757});
758
759export const GitCoreLive = Layer.effect(GitCore, makeGitCore);