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

GitCore.ts

815 lines25.9 KB

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;
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 };
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;
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;
78​
79function commandLabel(args: readonly string[]): string {
80 return `git ${args.join(" ")}`;
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 });
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 branchExists = (cwd: string, branch: string): Effect.Effect<boolean, GitCommandError> =>
162 executeGit(
163 "GitCore.branchExists",
164 cwd,
165 ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`],
166 {
167 allowNonZeroExit: true,
168 timeoutMs: 5_000,
169 },
170 ).pipe(Effect.map((result) => result.code === 0));
171​
172 const resolveAvailableBranchName = (
173 cwd: string,
174 desiredBranch: string,
175 ): Effect.Effect<string, GitCommandError> =>
176 Effect.gen(function* () {
177 const isDesiredTaken = yield* branchExists(cwd, desiredBranch);
178 if (!isDesiredTaken) {
179 return desiredBranch;
180 }
181​
182 for (let suffix = 1; suffix <= 100; suffix += 1) {
183 const candidate = `${desiredBranch}-${suffix}`;
184 const isCandidateTaken = yield* branchExists(cwd, candidate);
185 if (!isCandidateTaken) {
186 return candidate;
187 }
188 }
189​
190 return yield* createGitCommandError(
191 "GitCore.renameBranch",
192 cwd,
193 ["branch", "-m", "--", desiredBranch],
194 `Could not find an available branch name for '${desiredBranch}'.`,
195 );
196 });
197​
198 const resolveCurrentUpstream = (
199 cwd: string,
200 ): Effect.Effect<
201 { upstreamRef: string; remoteName: string; upstreamBranch: string } | null,
202 GitCommandError
203 > =>
204 Effect.gen(function* () {
205 const upstreamRef = yield* runGitStdout(
206 "GitCore.resolveCurrentUpstream",
207 cwd,
208 ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"],
209 true,
210 ).pipe(Effect.map((stdout) => stdout.trim()));
211​
212 if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") {
213 return null;
214 }
215​
216 const separatorIndex = upstreamRef.indexOf("/");
217 if (separatorIndex <= 0) {
218 return null;
219 }
220 const remoteName = upstreamRef.slice(0, separatorIndex);
221 const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
222 if (remoteName.length === 0 || upstreamBranch.length === 0) {
223 return null;
224 }
225​
226 return {
227 upstreamRef,
228 remoteName,
229 upstreamBranch,
230 };
231 });
232​
233 const fetchUpstreamRef = (
234 cwd: string,
235 upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
236 ): Effect.Effect<void, GitCommandError> => {
237 const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
238 return runGit(
239 "GitCore.fetchUpstreamRef",
240 cwd,
241 ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
242 true,
243 );
244 };
245​
246 const fetchUpstreamRefForStatus = (
247 cwd: string,
248 upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
249 ): Effect.Effect<void, GitCommandError> => {
250 const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
251 return executeGit(
252 "GitCore.fetchUpstreamRefForStatus",
253 cwd,
254 ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
255 {
256 allowNonZeroExit: true,
257 timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
258 },
259 ).pipe(Effect.asVoid);
260 };
261​
262 const statusUpstreamRefreshCache = yield* Cache.makeWith({
263 capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
264 lookup: (cacheKey: StatusUpstreamRefreshCacheKey) =>
265 Effect.gen(function* () {
266 yield* fetchUpstreamRefForStatus(cacheKey.cwd, {
267 upstreamRef: cacheKey.upstreamRef,
268 remoteName: cacheKey.remoteName,
269 upstreamBranch: cacheKey.upstreamBranch,
270 });
271 return true as const;
272 }),
273 // Keep successful refreshes warm; drop failures immediately so next request can retry.
274 timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_UPSTREAM_REFRESH_INTERVAL : Duration.zero),
275 });
276​
277 const refreshStatusUpstreamIfStale = (cwd: string): Effect.Effect<void, GitCommandError> =>
278 Effect.gen(function* () {
279 const upstream = yield* resolveCurrentUpstream(cwd);
280 if (!upstream) return;
281 yield* Cache.get(
282 statusUpstreamRefreshCache,
283 new StatusUpstreamRefreshCacheKey({
284 cwd,
285 upstreamRef: upstream.upstreamRef,
286 remoteName: upstream.remoteName,
287 upstreamBranch: upstream.upstreamBranch,
288 }),
289 );
290 });
291​
292 const refreshCheckedOutBranchUpstream = (cwd: string): Effect.Effect<void, GitCommandError> =>
293 Effect.gen(function* () {
294 const upstream = yield* resolveCurrentUpstream(cwd);
295 if (!upstream) return;
296 yield* fetchUpstreamRef(cwd, upstream);
297 });
298​
299 const readBranchRecency = (cwd: string): Effect.Effect<Map<string, number>, GitCommandError> =>
300 Effect.gen(function* () {
301 const branchRecency = yield* executeGit(
302 "GitCore.readBranchRecency",
303 cwd,
304 ["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
305 {
306 timeoutMs: 15_000,
307 allowNonZeroExit: true,
308 },
309 );
310​
311 const branchLastCommit = new Map<string, number>();
312 if (branchRecency.code !== 0) {
313 return branchLastCommit;
314 }
315​
316 for (const line of branchRecency.stdout.split("\n")) {
317 if (line.length === 0) {
318 continue;
319 }
320 const [name, lastCommitRaw] = line.split("\t");
321 if (!name) {
322 continue;
323 }
324 const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10);
325 branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0);
326 }
327​
328 return branchLastCommit;
329 });
330​
331 const statusDetails: GitCoreShape["statusDetails"] = (cwd) =>
332 Effect.gen(function* () {
333 yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.catch(() => Effect.void));
334​
335 const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all(
336 [
337 runGitStdout("GitCore.statusDetails.status", cwd, [
338 "status",
339 "--porcelain=2",
340 "--branch",
341 ]),
342 runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]),
343 runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, [
344 "diff",
345 "--cached",
346 "--numstat",
347 ]),
348 ],
349 { concurrency: "unbounded" },
350 );
351​
352 let branch: string | null = null;
353 let upstreamRef: string | null = null;
354 let aheadCount = 0;
355 let behindCount = 0;
356 let hasWorkingTreeChanges = false;
357 const changedFilesWithoutNumstat = new Set<string>();
358​
359 for (const line of statusStdout.split(/\r?\n/g)) {
360 if (line.startsWith("# branch.head ")) {
361 const value = line.slice("# branch.head ".length).trim();
362 branch = value.startsWith("(") ? null : value;
363 continue;
364 }
365 if (line.startsWith("# branch.upstream ")) {
366 const value = line.slice("# branch.upstream ".length).trim();
367 upstreamRef = value.length > 0 ? value : null;
368 continue;
369 }
370 if (line.startsWith("# branch.ab ")) {
371 const value = line.slice("# branch.ab ".length).trim();
372 const parsed = parseBranchAb(value);
373 aheadCount = parsed.ahead;
374 behindCount = parsed.behind;
375 continue;
376 }
377 if (line.trim().length > 0 && !line.startsWith("#")) {
378 hasWorkingTreeChanges = true;
379 const pathValue = parsePorcelainPath(line);
380 if (pathValue) changedFilesWithoutNumstat.add(pathValue);
381 }
382 }
383 const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
384 const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
385 const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
386 for (const entry of [...stagedEntries, ...unstagedEntries]) {
387 const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };
388 existing.insertions += entry.insertions;
389 existing.deletions += entry.deletions;
390 fileStatMap.set(entry.path, existing);
391 }
392​
393 let insertions = 0;
394 let deletions = 0;
395 const files = Array.from(fileStatMap.entries())
396 .map(([filePath, stat]) => {
397 insertions += stat.insertions;
398 deletions += stat.deletions;
399 return { path: filePath, insertions: stat.insertions, deletions: stat.deletions };
400 })
401 .toSorted((a, b) => a.path.localeCompare(b.path));
402​
403 for (const filePath of changedFilesWithoutNumstat) {
404 if (fileStatMap.has(filePath)) continue;
405 files.push({ path: filePath, insertions: 0, deletions: 0 });
406 }
407 files.sort((a, b) => a.path.localeCompare(b.path));
408​
409 return {
410 branch,
411 upstreamRef,
412 hasWorkingTreeChanges,
413 workingTree: {
414 files,
415 insertions,
416 deletions,
417 },
418 hasUpstream: upstreamRef !== null,
419 aheadCount,
420 behindCount,
421 };
422 });
423​
424 const status: GitCoreShape["status"] = (input) =>
425 statusDetails(input.cwd).pipe(
426 Effect.map((details) => ({
427 branch: details.branch,
428 hasWorkingTreeChanges: details.hasWorkingTreeChanges,
429 workingTree: details.workingTree,
430 hasUpstream: details.hasUpstream,
431 aheadCount: details.aheadCount,
432 behindCount: details.behindCount,
433 pr: null,
434 })),
435 );
436​
437 const prepareCommitContext: GitCoreShape["prepareCommitContext"] = (cwd) =>
438 Effect.gen(function* () {
439 yield* runGit("GitCore.prepareCommitContext.addAll", cwd, ["add", "-A"]);
440​
441 const stagedSummary = yield* runGitStdout("GitCore.prepareCommitContext.stagedSummary", cwd, [
442 "diff",
443 "--cached",
444 "--name-status",
445 ]).pipe(Effect.map((stdout) => stdout.trim()));
446 if (stagedSummary.length === 0) {
447 return null;
448 }
449​
450 const stagedPatch = yield* runGitStdout("GitCore.prepareCommitContext.stagedPatch", cwd, [
451 "diff",
452 "--cached",
453 "--patch",
454 "--minimal",
455 ]);
456​
457 return {
458 stagedSummary,
459 stagedPatch,
460 };
461 });
462​
463 const commit: GitCoreShape["commit"] = (cwd, subject, body) =>
464 Effect.gen(function* () {
465 const args = ["commit", "-m", subject];
466 const trimmedBody = body.trim();
467 if (trimmedBody.length > 0) {
468 args.push("-m", trimmedBody);
469 }
470 yield* runGit("GitCore.commit.commit", cwd, args);
471 const commitSha = yield* runGitStdout("GitCore.commit.revParseHead", cwd, [
472 "rev-parse",
473 "HEAD",
474 ]).pipe(Effect.map((stdout) => stdout.trim()));
475​
476 return { commitSha };
477 });
478​
479 const pushCurrentBranch: GitCoreShape["pushCurrentBranch"] = (cwd, fallbackBranch) =>
480 Effect.gen(function* () {
481 const details = yield* statusDetails(cwd);
482 const branch = details.branch ?? fallbackBranch;
483 if (!branch) {
484 return yield* createGitCommandError(
485 "GitCore.pushCurrentBranch",
486 cwd,
487 ["push"],
488 "Cannot push from detached HEAD.",
489 );
490 }
491​
492 if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {
493 return {
494 status: "skipped_up_to_date" as const,
495 branch,
496 ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
497 };
498 }
499​
500 if (!details.hasUpstream) {
501 yield* runGit("GitCore.pushCurrentBranch.pushWithUpstream", cwd, [
502 "push",
503 "-u",
504 "origin",
505 branch,
506 ]);
507 return {
508 status: "pushed" as const,
509 branch,
510 upstreamBranch: `origin/${branch}`,
511 setUpstream: true,
512 };
513 }
514​
515 yield* runGit("GitCore.pushCurrentBranch.push", cwd, ["push"]);
516 return {
517 status: "pushed" as const,
518 branch,
519 ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
520 setUpstream: false,
521 };
522 });
523​
524 const pullCurrentBranch: GitCoreShape["pullCurrentBranch"] = (cwd) =>
525 Effect.gen(function* () {
526 const details = yield* statusDetails(cwd);
527 const branch = details.branch;
528 if (!branch) {
529 return yield* createGitCommandError(
530 "GitCore.pullCurrentBranch",
531 cwd,
532 ["pull", "--ff-only"],
533 "Cannot pull from detached HEAD.",
534 );
535 }
536 if (!details.hasUpstream) {
537 return yield* createGitCommandError(
538 "GitCore.pullCurrentBranch",
539 cwd,
540 ["pull", "--ff-only"],
541 "Current branch has no upstream configured. Push with upstream first.",
542 );
543 }
544 const beforeSha = yield* runGitStdout(
545 "GitCore.pullCurrentBranch.beforeSha",
546 cwd,
547 ["rev-parse", "HEAD"],
548 true,
549 ).pipe(Effect.map((stdout) => stdout.trim()));
550 yield* executeGit("GitCore.pullCurrentBranch.pull", cwd, ["pull", "--ff-only"], {
551 timeoutMs: 30_000,
552 fallbackErrorMessage: "git pull failed",
553 });
554 const afterSha = yield* runGitStdout(
555 "GitCore.pullCurrentBranch.afterSha",
556 cwd,
557 ["rev-parse", "HEAD"],
558 true,
559 ).pipe(Effect.map((stdout) => stdout.trim()));
560​
561 const refreshed = yield* statusDetails(cwd);
562 return {
563 status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
564 branch,
565 upstreamBranch: refreshed.upstreamRef,
566 };
567 });
568​
569 const readRangeContext: GitCoreShape["readRangeContext"] = (cwd, baseBranch) =>
570 Effect.gen(function* () {
571 const range = `${baseBranch}..HEAD`;
572 const [commitSummary, diffSummary, diffPatch] = yield* Effect.all(
573 [
574 runGitStdout("GitCore.readRangeContext.log", cwd, ["log", "--oneline", range]),
575 runGitStdout("GitCore.readRangeContext.diffStat", cwd, ["diff", "--stat", range]),
576 runGitStdout("GitCore.readRangeContext.diffPatch", cwd, [
577 "diff",
578 "--patch",
579 "--minimal",
580 range,
581 ]),
582 ],
583 { concurrency: "unbounded" },
584 );
585​
586 return {
587 commitSummary,
588 diffSummary,
589 diffPatch,
590 };
591 });
592​
593 const readConfigValue: GitCoreShape["readConfigValue"] = (cwd, key) =>
594 runGitStdout("GitCore.readConfigValue", cwd, ["config", "--get", key], true).pipe(
595 Effect.map((stdout) => stdout.trim()),
596 Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),
597 );
598​
599 const listBranches: GitCoreShape["listBranches"] = (input) =>
600 Effect.gen(function* () {
601 const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
602 Effect.catch(() => Effect.succeed(new Map<string, number>())),
603 );
604 const result = yield* executeGit(
605 "GitCore.listBranches.branchNoColor",
606 input.cwd,
607 ["branch", "--no-color"],
608 {
609 timeoutMs: 10_000,
610 allowNonZeroExit: true,
611 },
612 );
613​
614 if (result.code !== 0) {
615 const stderr = result.stderr.trim();
616 if (stderr.toLowerCase().includes("not a git repository")) {
617 return { branches: [], isRepo: false };
618 }
619 return yield* createGitCommandError(
620 "GitCore.listBranches",
621 input.cwd,
622 ["branch", "--no-color"],
623 stderr || "git branch failed",
624 );
625 }
626​
627 const [defaultRef, worktreeList, branchLastCommit] = yield* Effect.all(
628 [
629 executeGit(
630 "GitCore.listBranches.defaultRef",
631 input.cwd,
632 ["symbolic-ref", "refs/remotes/origin/HEAD"],
633 {
634 timeoutMs: 5_000,
635 allowNonZeroExit: true,
636 },
637 ),
638 executeGit(
639 "GitCore.listBranches.worktreeList",
640 input.cwd,
641 ["worktree", "list", "--porcelain"],
642 {
643 timeoutMs: 5_000,
644 allowNonZeroExit: true,
645 },
646 ),
647 branchRecencyPromise,
648 ],
649 { concurrency: "unbounded" },
650 );
651​
652 const defaultBranch =
653 defaultRef.code === 0
654 ? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
655 : null;
656​
657 const worktreeMap = new Map<string, string>();
658 if (worktreeList.code === 0) {
659 let currentPath: string | null = null;
660 for (const line of worktreeList.stdout.split("\n")) {
661 if (line.startsWith("worktree ")) {
662 const candidatePath = line.slice("worktree ".length);
663 const exists = yield* fileSystem.stat(candidatePath).pipe(
664 Effect.map(() => true),
665 Effect.catch(() => Effect.succeed(false)),
666 );
667 currentPath = exists ? candidatePath : null;
668 } else if (line.startsWith("branch refs/heads/") && currentPath) {
669 worktreeMap.set(line.slice("branch refs/heads/".length), currentPath);
670 } else if (line === "") {
671 currentPath = null;
672 }
673 }
674 }
675​
676 const branches = result.stdout
677 .split("\n")
678 .map((line) => line.trim())
679 .filter((line) => line.length > 0)
680 .map((line) => {
681 const name = line.replace(/^[*+]\s+/, "");
682 return {
683 name,
684 current: line.startsWith("* "),
685 isDefault: name === defaultBranch,
686 worktreePath: worktreeMap.get(name) ?? null,
687 };
688 })
689 .toSorted((a, b) => {
690 const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
691 const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
692 if (aPriority !== bPriority) return aPriority - bPriority;
693​
694 const aLastCommit = branchLastCommit.get(a.name) ?? 0;
695 const bLastCommit = branchLastCommit.get(b.name) ?? 0;
696 if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
697 return a.name.localeCompare(b.name);
698 });
699​
700 return { branches, isRepo: true };
701 });
702​
703 const createWorktree: GitCoreShape["createWorktree"] = (input) =>
704 Effect.gen(function* () {
705 const sanitizedBranch = input.newBranch.replace(/\//g, "-");
706 const repoName = path.basename(input.cwd);
707 const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? "/tmp";
708 const worktreePath =
709 input.path ?? path.join(homeDir, ".t3", "worktrees", repoName, sanitizedBranch);
710​
711 yield* executeGit(
712 "GitCore.createWorktree",
713 input.cwd,
714 ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch],
715 {
716 fallbackErrorMessage: "git worktree add failed",
717 },
718 );
719​
720 return {
721 worktree: {
722 path: worktreePath,
723 branch: input.newBranch,
724 },
725 };
726 });
727​
728 const removeWorktree: GitCoreShape["removeWorktree"] = (input) =>
729 Effect.gen(function* () {
730 const args = ["worktree", "remove"];
731 if (input.force) {
732 args.push("--force");
733 }
734 args.push(input.path);
735 yield* executeGit("GitCore.removeWorktree", input.cwd, args, {
736 timeoutMs: 15_000,
737 fallbackErrorMessage: "git worktree remove failed",
738 }).pipe(
739 Effect.mapError((error) =>
740 createGitCommandError(
741 "GitCore.removeWorktree",
742 input.cwd,
743 args,
744 `${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`,
745 error,
746 ),
747 ),
748 );
749 });
750​
751 const renameBranch: GitCoreShape["renameBranch"] = (input) =>
752 Effect.gen(function* () {
753 if (input.oldBranch === input.newBranch) {
754 return { branch: input.newBranch };
755 }
756 const targetBranch = yield* resolveAvailableBranchName(input.cwd, input.newBranch);
757​
758 yield* executeGit(
759 "GitCore.renameBranch",
760 input.cwd,
761 ["branch", "-m", "--", input.oldBranch, targetBranch],
762 {
763 timeoutMs: 10_000,
764 fallbackErrorMessage: "git branch rename failed",
765 },
766 );
767​
768 return { branch: targetBranch };
769 });
770​
771 const createBranch: GitCoreShape["createBranch"] = (input) =>
772 executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {
773 timeoutMs: 10_000,
774 fallbackErrorMessage: "git branch create failed",
775 }).pipe(Effect.asVoid);
776​
777 const checkoutBranch: GitCoreShape["checkoutBranch"] = (input) =>
778 Effect.gen(function* () {
779 yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, ["checkout", input.branch], {
780 timeoutMs: 10_000,
781 fallbackErrorMessage: "git checkout failed",
782 });
783​
784 // Refresh upstream refs in the background so checkout remains responsive.
785 yield* Effect.forkDetach(
786 refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
787 );
788 });
789​
790 const initRepo: GitCoreShape["initRepo"] = (input) =>
791 executeGit("GitCore.initRepo", input.cwd, ["init"], {
792 timeoutMs: 10_000,
793 fallbackErrorMessage: "git init failed",
794 }).pipe(Effect.asVoid);
795​
796 return {
797 status,
798 statusDetails,
799 prepareCommitContext,
800 commit,
801 pushCurrentBranch,
802 pullCurrentBranch,
803 readRangeContext,
804 readConfigValue,
805 listBranches,
806 createWorktree,
807 removeWorktree,
808 renameBranch,
809 createBranch,
810 checkoutBranch,
811 initRepo,
812 } satisfies GitCoreShape;
813});
814​
815export const GitCoreLive = Layer.effect(GitCore, makeGitCore);