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 parseBranchLine(line: string): { name: string; current: boolean } | null {
80 const trimmed = line.trim();
81 if (trimmed.length === 0) return null;
82
83 const name = trimmed.replace(/^[*+]\s+/, "");
84 // Exclude symbolic refs like: "origin/HEAD -> origin/main".
85 // Exclude detached HEAD pseudo-refs like: "(HEAD detached at origin/main)".
86 if (name.includes(" -> ") || name.startsWith("(")) return null;
87
88 return {
89 name,
90 current: trimmed.startsWith("* "),
91 };
92}
93
94function parseRemoteNames(stdout: string): ReadonlyArray<string> {
95 return stdout
96 .split("\n")
97 .map((line) => line.trim())
98 .filter((line) => line.length > 0)
99 .toSorted((a, b) => b.length - a.length);
100}
101
102function parseRemoteRefWithRemoteNames(
103 branchName: string,
104 remoteNames: ReadonlyArray<string>,
105): { remoteRef: string; remoteName: string; localBranch: string } | null {
106 const trimmedBranchName = branchName.trim();
107 if (trimmedBranchName.length === 0) return null;
108
109 for (const remoteName of remoteNames) {
110 const remotePrefix = `${remoteName}/`;
111 if (!trimmedBranchName.startsWith(remotePrefix)) {
112 continue;
113 }
114 const localBranch = trimmedBranchName.slice(remotePrefix.length).trim();
115 if (localBranch.length === 0) {
116 return null;
117 }
118 return {
119 remoteRef: trimmedBranchName,
120 remoteName,
121 localBranch,
122 };
123 }
124
125 return null;
126}
127
128function parseTrackingBranchByUpstreamRef(
129 stdout: string,
130 upstreamRef: string,
131): string | null {
132 for (const line of stdout.split("\n")) {
133 const trimmedLine = line.trim();
134 if (trimmedLine.length === 0) {
135 continue;
136 }
137 const [branchNameRaw, upstreamBranchRaw = ""] = trimmedLine.split("\t");
138 const branchName = branchNameRaw?.trim() ?? "";
139 const upstreamBranch = upstreamBranchRaw.trim();
140 if (branchName.length === 0 || upstreamBranch.length === 0) {
141 continue;
142 }
143 if (upstreamBranch === upstreamRef) {
144 return branchName;
145 }
146 }
147
148 return null;
149}
150
151function deriveLocalBranchNameFromRemoteRef(branchName: string): string | null {
152 const separatorIndex = branchName.indexOf("/");
153 if (separatorIndex <= 0 || separatorIndex === branchName.length - 1) {
154 return null;
155 }
156 const localBranch = branchName.slice(separatorIndex + 1).trim();
157 return localBranch.length > 0 ? localBranch : null;
158}
159
160function commandLabel(args: readonly string[]): string {
161 return `git ${args.join(" ")}`;
162}
163
164function createGitCommandError(
165 operation: string,
166 cwd: string,
167 args: readonly string[],
168 detail: string,
169 cause?: unknown,
170): GitCommandError {
171 return new GitCommandError({
172 operation,
173 command: commandLabel(args),
174 cwd,
175 detail,
176 ...(cause !== undefined ? { cause } : {}),
177 });
178}
179
180const makeGitCore = Effect.gen(function* () {
181 const git = yield* GitService;
182 const fileSystem = yield* FileSystem.FileSystem;
183 const path = yield* Path.Path;
184
185 const executeGit = (
186 operation: string,
187 cwd: string,
188 args: readonly string[],
189 options: ExecuteGitOptions = {},
190 ): Effect.Effect<{ code: number; stdout: string; stderr: string }, GitCommandError> =>
191 git
192 .execute({
193 operation,
194 cwd,
195 args,
196 allowNonZeroExit: true,
197 ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
198 })
199 .pipe(
200 Effect.flatMap((result) => {
201 if (options.allowNonZeroExit || result.code === 0) {
202 return Effect.succeed(result);
203 }
204 const stderr = result.stderr.trim();
205 if (stderr.length > 0) {
206 return Effect.fail(createGitCommandError(operation, cwd, args, stderr));
207 }
208 if (options.fallbackErrorMessage) {
209 return Effect.fail(
210 createGitCommandError(operation, cwd, args, options.fallbackErrorMessage),
211 );
212 }
213 return Effect.fail(
214 createGitCommandError(
215 operation,
216 cwd,
217 args,
218 `${commandLabel(args)} failed: code=${result.code ?? "null"}`,
219 ),
220 );
221 }),
222 );
223
224 const runGit = (
225 operation: string,
226 cwd: string,
227 args: readonly string[],
228 allowNonZeroExit = false,
229 ): Effect.Effect<void, GitCommandError> =>
230 executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(Effect.asVoid);
231
232 const runGitStdout = (
233 operation: string,
234 cwd: string,
235 args: readonly string[],
236 allowNonZeroExit = false,
237 ): Effect.Effect<string, GitCommandError> =>
238 executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(
239 Effect.map((result) => result.stdout),
240 );
241
242 const resolveCurrentUpstream = (
243 cwd: string,
244 ): Effect.Effect<
245 { upstreamRef: string; remoteName: string; upstreamBranch: string } | null,
246 GitCommandError
247 > =>
248 Effect.gen(function* () {
249 const upstreamRef = yield* runGitStdout(
250 "GitCore.resolveCurrentUpstream",
251 cwd,
252 ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"],
253 true,
254 ).pipe(Effect.map((stdout) => stdout.trim()));
255
256 if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") {
257 return null;
258 }
259
260 const separatorIndex = upstreamRef.indexOf("/");
261 if (separatorIndex <= 0) {
262 return null;
263 }
264 const remoteName = upstreamRef.slice(0, separatorIndex);
265 const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
266 if (remoteName.length === 0 || upstreamBranch.length === 0) {
267 return null;
268 }
269
270 return {
271 upstreamRef,
272 remoteName,
273 upstreamBranch,
274 };
275 });
276
277 const fetchUpstreamRef = (
278 cwd: string,
279 upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
280 ): Effect.Effect<void, GitCommandError> => {
281 const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
282 return runGit(
283 "GitCore.fetchUpstreamRef",
284 cwd,
285 ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
286 true,
287 );
288 };
289
290 const fetchUpstreamRefForStatus = (
291 cwd: string,
292 upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
293 ): Effect.Effect<void, GitCommandError> => {
294 const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
295 return executeGit(
296 "GitCore.fetchUpstreamRefForStatus",
297 cwd,
298 ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
299 {
300 allowNonZeroExit: true,
301 timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
302 },
303 ).pipe(Effect.asVoid);
304 };
305
306 const statusUpstreamRefreshCache = yield* Cache.makeWith({
307 capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
308 lookup: (cacheKey: StatusUpstreamRefreshCacheKey) =>
309 Effect.gen(function* () {
310 yield* fetchUpstreamRefForStatus(cacheKey.cwd, {
311 upstreamRef: cacheKey.upstreamRef,
312 remoteName: cacheKey.remoteName,
313 upstreamBranch: cacheKey.upstreamBranch,
314 });
315 return true as const;
316 }),
317 // Keep successful refreshes warm; drop failures immediately so next request can retry.
318 timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_UPSTREAM_REFRESH_INTERVAL : Duration.zero),
319 });
320
321 const refreshStatusUpstreamIfStale = (cwd: string): Effect.Effect<void, GitCommandError> =>
322 Effect.gen(function* () {
323 const upstream = yield* resolveCurrentUpstream(cwd);
324 if (!upstream) return;
325 yield* Cache.get(
326 statusUpstreamRefreshCache,
327 new StatusUpstreamRefreshCacheKey({
328 cwd,
329 upstreamRef: upstream.upstreamRef,
330 remoteName: upstream.remoteName,
331 upstreamBranch: upstream.upstreamBranch,
332 }),
333 );
334 });
335
336 const refreshCheckedOutBranchUpstream = (cwd: string): Effect.Effect<void, GitCommandError> =>
337 Effect.gen(function* () {
338 const upstream = yield* resolveCurrentUpstream(cwd);
339 if (!upstream) return;
340 yield* fetchUpstreamRef(cwd, upstream);
341 });
342
343 const readBranchRecency = (cwd: string): Effect.Effect<Map<string, number>, GitCommandError> =>
344 Effect.gen(function* () {
345 const branchRecency = yield* executeGit(
346 "GitCore.readBranchRecency",
347 cwd,
348 [
349 "for-each-ref",
350 "--format=%(refname:short)%09%(committerdate:unix)",
351 "refs/heads",
352 "refs/remotes",
353 ],
354 {
355 timeoutMs: 15_000,
356 allowNonZeroExit: true,
357 },
358 );
359
360 const branchLastCommit = new Map<string, number>();
361 if (branchRecency.code !== 0) {
362 return branchLastCommit;
363 }
364
365 for (const line of branchRecency.stdout.split("\n")) {
366 if (line.length === 0) {
367 continue;
368 }
369 const [name, lastCommitRaw] = line.split("\t");
370 if (!name) {
371 continue;
372 }
373 const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10);
374 branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0);
375 }
376
377 return branchLastCommit;
378 });
379
380 const statusDetails: GitCoreShape["statusDetails"] = (cwd) =>
381 Effect.gen(function* () {
382 yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.catch(() => Effect.void));
383
384 const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all(
385 [
386 runGitStdout("GitCore.statusDetails.status", cwd, [
387 "status",
388 "--porcelain=2",
389 "--branch",
390 ]),
391 runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]),
392 runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, [
393 "diff",
394 "--cached",
395 "--numstat",
396 ]),
397 ],
398 { concurrency: "unbounded" },
399 );
400
401 let branch: string | null = null;
402 let upstreamRef: string | null = null;
403 let aheadCount = 0;
404 let behindCount = 0;
405 let hasWorkingTreeChanges = false;
406 const changedFilesWithoutNumstat = new Set<string>();
407
408 for (const line of statusStdout.split(/\r?\n/g)) {
409 if (line.startsWith("# branch.head ")) {
410 const value = line.slice("# branch.head ".length).trim();
411 branch = value.startsWith("(") ? null : value;
412 continue;
413 }
414 if (line.startsWith("# branch.upstream ")) {
415 const value = line.slice("# branch.upstream ".length).trim();
416 upstreamRef = value.length > 0 ? value : null;
417 continue;
418 }
419 if (line.startsWith("# branch.ab ")) {
420 const value = line.slice("# branch.ab ".length).trim();
421 const parsed = parseBranchAb(value);
422 aheadCount = parsed.ahead;
423 behindCount = parsed.behind;
424 continue;
425 }
426 if (line.trim().length > 0 && !line.startsWith("#")) {
427 hasWorkingTreeChanges = true;
428 const pathValue = parsePorcelainPath(line);
429 if (pathValue) changedFilesWithoutNumstat.add(pathValue);
430 }
431 }
432 const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
433 const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
434 const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
435 for (const entry of [...stagedEntries, ...unstagedEntries]) {
436 const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };
437 existing.insertions += entry.insertions;
438 existing.deletions += entry.deletions;
439 fileStatMap.set(entry.path, existing);
440 }
441
442 let insertions = 0;
443 let deletions = 0;
444 const files = Array.from(fileStatMap.entries())
445 .map(([filePath, stat]) => {
446 insertions += stat.insertions;
447 deletions += stat.deletions;
448 return { path: filePath, insertions: stat.insertions, deletions: stat.deletions };
449 })
450 .toSorted((a, b) => a.path.localeCompare(b.path));
451
452 for (const filePath of changedFilesWithoutNumstat) {
453 if (fileStatMap.has(filePath)) continue;
454 files.push({ path: filePath, insertions: 0, deletions: 0 });
455 }
456 files.sort((a, b) => a.path.localeCompare(b.path));
457
458 return {
459 branch,
460 upstreamRef,
461 hasWorkingTreeChanges,
462 workingTree: {
463 files,
464 insertions,
465 deletions,
466 },
467 hasUpstream: upstreamRef !== null,
468 aheadCount,
469 behindCount,
470 };
471 });
472
473 const status: GitCoreShape["status"] = (input) =>
474 statusDetails(input.cwd).pipe(
475 Effect.map((details) => ({
476 branch: details.branch,
477 hasWorkingTreeChanges: details.hasWorkingTreeChanges,
478 workingTree: details.workingTree,
479 hasUpstream: details.hasUpstream,
480 aheadCount: details.aheadCount,
481 behindCount: details.behindCount,
482 pr: null,
483 })),
484 );
485
486 const prepareCommitContext: GitCoreShape["prepareCommitContext"] = (cwd) =>
487 Effect.gen(function* () {
488 yield* runGit("GitCore.prepareCommitContext.addAll", cwd, ["add", "-A"]);
489
490 const stagedSummary = yield* runGitStdout("GitCore.prepareCommitContext.stagedSummary", cwd, [
491 "diff",
492 "--cached",
493 "--name-status",
494 ]).pipe(Effect.map((stdout) => stdout.trim()));
495 if (stagedSummary.length === 0) {
496 return null;
497 }
498
499 const stagedPatch = yield* runGitStdout("GitCore.prepareCommitContext.stagedPatch", cwd, [
500 "diff",
501 "--cached",
502 "--patch",
503 "--minimal",
504 ]);
505
506 return {
507 stagedSummary,
508 stagedPatch,
509 };
510 });
511
512 const commit: GitCoreShape["commit"] = (cwd, subject, body) =>
513 Effect.gen(function* () {
514 const args = ["commit", "-m", subject];
515 const trimmedBody = body.trim();
516 if (trimmedBody.length > 0) {
517 args.push("-m", trimmedBody);
518 }
519 yield* runGit("GitCore.commit.commit", cwd, args);
520 const commitSha = yield* runGitStdout("GitCore.commit.revParseHead", cwd, [
521 "rev-parse",
522 "HEAD",
523 ]).pipe(Effect.map((stdout) => stdout.trim()));
524
525 return { commitSha };
526 });
527
528 const pushCurrentBranch: GitCoreShape["pushCurrentBranch"] = (cwd, fallbackBranch) =>
529 Effect.gen(function* () {
530 const details = yield* statusDetails(cwd);
531 const branch = details.branch ?? fallbackBranch;
532 if (!branch) {
533 return yield* createGitCommandError(
534 "GitCore.pushCurrentBranch",
535 cwd,
536 ["push"],
537 "Cannot push from detached HEAD.",
538 );
539 }
540
541 if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {
542 return {
543 status: "skipped_up_to_date" as const,
544 branch,
545 ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
546 };
547 }
548
549 if (!details.hasUpstream) {
550 yield* runGit("GitCore.pushCurrentBranch.pushWithUpstream", cwd, [
551 "push",
552 "-u",
553 "origin",
554 branch,
555 ]);
556 return {
557 status: "pushed" as const,
558 branch,
559 upstreamBranch: `origin/${branch}`,
560 setUpstream: true,
561 };
562 }
563
564 yield* runGit("GitCore.pushCurrentBranch.push", cwd, ["push"]);
565 return {
566 status: "pushed" as const,
567 branch,
568 ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
569 setUpstream: false,
570 };
571 });
572
573 const pullCurrentBranch: GitCoreShape["pullCurrentBranch"] = (cwd) =>
574 Effect.gen(function* () {
575 const details = yield* statusDetails(cwd);
576 const branch = details.branch;
577 if (!branch) {
578 return yield* createGitCommandError(
579 "GitCore.pullCurrentBranch",
580 cwd,
581 ["pull", "--ff-only"],
582 "Cannot pull from detached HEAD.",
583 );
584 }
585 if (!details.hasUpstream) {
586 return yield* createGitCommandError(
587 "GitCore.pullCurrentBranch",
588 cwd,
589 ["pull", "--ff-only"],
590 "Current branch has no upstream configured. Push with upstream first.",
591 );
592 }
593 const beforeSha = yield* runGitStdout(
594 "GitCore.pullCurrentBranch.beforeSha",
595 cwd,
596 ["rev-parse", "HEAD"],
597 true,
598 ).pipe(Effect.map((stdout) => stdout.trim()));
599 yield* executeGit("GitCore.pullCurrentBranch.pull", cwd, ["pull", "--ff-only"], {
600 timeoutMs: 30_000,
601 fallbackErrorMessage: "git pull failed",
602 });
603 const afterSha = yield* runGitStdout(
604 "GitCore.pullCurrentBranch.afterSha",
605 cwd,
606 ["rev-parse", "HEAD"],
607 true,
608 ).pipe(Effect.map((stdout) => stdout.trim()));
609
610 const refreshed = yield* statusDetails(cwd);
611 return {
612 status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
613 branch,
614 upstreamBranch: refreshed.upstreamRef,
615 };
616 });
617
618 const readRangeContext: GitCoreShape["readRangeContext"] = (cwd, baseBranch) =>
619 Effect.gen(function* () {
620 const range = `${baseBranch}..HEAD`;
621 const [commitSummary, diffSummary, diffPatch] = yield* Effect.all(
622 [
623 runGitStdout("GitCore.readRangeContext.log", cwd, ["log", "--oneline", range]),
624 runGitStdout("GitCore.readRangeContext.diffStat", cwd, ["diff", "--stat", range]),
625 runGitStdout("GitCore.readRangeContext.diffPatch", cwd, [
626 "diff",
627 "--patch",
628 "--minimal",
629 range,
630 ]),
631 ],
632 { concurrency: "unbounded" },
633 );
634
635 return {
636 commitSummary,
637 diffSummary,
638 diffPatch,
639 };
640 });
641
642 const readConfigValue: GitCoreShape["readConfigValue"] = (cwd, key) =>
643 runGitStdout("GitCore.readConfigValue", cwd, ["config", "--get", key], true).pipe(
644 Effect.map((stdout) => stdout.trim()),
645 Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),
646 );
647
648 const listBranches: GitCoreShape["listBranches"] = (input) =>
649 Effect.gen(function* () {
650 const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
651 Effect.catch(() => Effect.succeed(new Map<string, number>())),
652 );
653 const localBranchResult = yield* executeGit(
654 "GitCore.listBranches.branchNoColor",
655 input.cwd,
656 ["branch", "--no-color"],
657 {
658 timeoutMs: 10_000,
659 allowNonZeroExit: true,
660 },
661 );
662
663 if (localBranchResult.code !== 0) {
664 const stderr = localBranchResult.stderr.trim();
665 if (stderr.toLowerCase().includes("not a git repository")) {
666 return { branches: [], isRepo: false };
667 }
668 return yield* createGitCommandError(
669 "GitCore.listBranches",
670 input.cwd,
671 ["branch", "--no-color"],
672 stderr || "git branch failed",
673 );
674 }
675
676 const remoteBranchResultEffect = executeGit(
677 "GitCore.listBranches.remoteBranches",
678 input.cwd,
679 ["branch", "--no-color", "--remotes"],
680 {
681 timeoutMs: 10_000,
682 allowNonZeroExit: true,
683 },
684 ).pipe(
685 Effect.catch((error) =>
686 Effect.logWarning(
687 `GitCore.listBranches: remote branch lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote branch list.`,
688 ).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
689 ),
690 );
691
692 const remoteNamesResultEffect = executeGit(
693 "GitCore.listBranches.remoteNames",
694 input.cwd,
695 ["remote"],
696 {
697 timeoutMs: 5_000,
698 allowNonZeroExit: true,
699 },
700 ).pipe(
701 Effect.catch((error) =>
702 Effect.logWarning(
703 `GitCore.listBranches: remote name lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote name list.`,
704 ).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
705 ),
706 );
707
708 const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] =
709 yield* Effect.all(
710 [
711 executeGit(
712 "GitCore.listBranches.defaultRef",
713 input.cwd,
714 ["symbolic-ref", "refs/remotes/origin/HEAD"],
715 {
716 timeoutMs: 5_000,
717 allowNonZeroExit: true,
718 },
719 ),
720 executeGit(
721 "GitCore.listBranches.worktreeList",
722 input.cwd,
723 ["worktree", "list", "--porcelain"],
724 {
725 timeoutMs: 5_000,
726 allowNonZeroExit: true,
727 },
728 ),
729 remoteBranchResultEffect,
730 remoteNamesResultEffect,
731 branchRecencyPromise,
732 ],
733 { concurrency: "unbounded" },
734 );
735
736 const remoteNames = remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : [];
737 if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) {
738 yield* Effect.logWarning(
739 `GitCore.listBranches: remote branch lookup returned code ${remoteBranchResult.code} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote branch list.`,
740 );
741 }
742 if (remoteNamesResult.code !== 0 && remoteNamesResult.stderr.trim().length > 0) {
743 yield* Effect.logWarning(
744 `GitCore.listBranches: remote name lookup returned code ${remoteNamesResult.code} for ${input.cwd}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`,
745 );
746 }
747
748 const defaultBranch =
749 defaultRef.code === 0
750 ? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
751 : null;
752
753 const worktreeMap = new Map<string, string>();
754 if (worktreeList.code === 0) {
755 let currentPath: string | null = null;
756 for (const line of worktreeList.stdout.split("\n")) {
757 if (line.startsWith("worktree ")) {
758 const candidatePath = line.slice("worktree ".length);
759 const exists = yield* fileSystem.stat(candidatePath).pipe(
760 Effect.map(() => true),
761 Effect.catch(() => Effect.succeed(false)),
762 );
763 currentPath = exists ? candidatePath : null;
764 } else if (line.startsWith("branch refs/heads/") && currentPath) {
765 worktreeMap.set(line.slice("branch refs/heads/".length), currentPath);
766 } else if (line === "") {
767 currentPath = null;
768 }
769 }
770 }
771
772 const localBranches = localBranchResult.stdout
773 .split("\n")
774 .map(parseBranchLine)
775 .filter((branch): branch is { name: string; current: boolean } => branch !== null)
776 .map((branch) => ({
777 name: branch.name,
778 current: branch.current,
779 isRemote: false,
780 isDefault: branch.name === defaultBranch,
781 worktreePath: worktreeMap.get(branch.name) ?? null,
782 }))
783 .toSorted((a, b) => {
784 const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
785 const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
786 if (aPriority !== bPriority) return aPriority - bPriority;
787
788 const aLastCommit = branchLastCommit.get(a.name) ?? 0;
789 const bLastCommit = branchLastCommit.get(b.name) ?? 0;
790 if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
791 return a.name.localeCompare(b.name);
792 });
793
794 const remoteBranches =
795 remoteBranchResult.code === 0
796 ? remoteBranchResult.stdout
797 .split("\n")
798 .map(parseBranchLine)
799 .filter((branch): branch is { name: string; current: boolean } => branch !== null)
800 .map((branch) => {
801 const parsedRemoteRef = parseRemoteRefWithRemoteNames(branch.name, remoteNames);
802 const remoteBranch: {
803 name: string;
804 current: boolean;
805 isRemote: boolean;
806 remoteName?: string;
807 isDefault: boolean;
808 worktreePath: string | null;
809 } = {
810 name: branch.name,
811 current: false,
812 isRemote: true,
813 isDefault: false,
814 worktreePath: null,
815 };
816 if (parsedRemoteRef) {
817 remoteBranch.remoteName = parsedRemoteRef.remoteName;
818 }
819 return remoteBranch;
820 })
821 .toSorted((a, b) => {
822 const aLastCommit = branchLastCommit.get(a.name) ?? 0;
823 const bLastCommit = branchLastCommit.get(b.name) ?? 0;
824 if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
825 return a.name.localeCompare(b.name);
826 })
827 : [];
828
829 const branches = [...localBranches, ...remoteBranches];
830
831 return { branches, isRepo: true };
832 });
833
834 const createWorktree: GitCoreShape["createWorktree"] = (input) =>
835 Effect.gen(function* () {
836 const sanitizedBranch = input.newBranch.replace(/\//g, "-");
837 const repoName = path.basename(input.cwd);
838 const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? "/tmp";
839 const worktreePath =
840 input.path ?? path.join(homeDir, ".t3", "worktrees", repoName, sanitizedBranch);
841
842 yield* executeGit(
843 "GitCore.createWorktree",
844 input.cwd,
845 ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch],
846 {
847 fallbackErrorMessage: "git worktree add failed",
848 },
849 );
850
851 return {
852 worktree: {
853 path: worktreePath,
854 branch: input.newBranch,
855 },
856 };
857 });
858
859 const removeWorktree: GitCoreShape["removeWorktree"] = (input) =>
860 Effect.gen(function* () {
861 const args = ["worktree", "remove"];
862 if (input.force) {
863 args.push("--force");
864 }
865 args.push(input.path);
866 yield* executeGit("GitCore.removeWorktree", input.cwd, args, {
867 timeoutMs: 15_000,
868 fallbackErrorMessage: "git worktree remove failed",
869 }).pipe(
870 Effect.mapError((error) =>
871 createGitCommandError(
872 "GitCore.removeWorktree",
873 input.cwd,
874 args,
875 `${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`,
876 error,
877 ),
878 ),
879 );
880 });
881
882 const createBranch: GitCoreShape["createBranch"] = (input) =>
883 executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {
884 timeoutMs: 10_000,
885 fallbackErrorMessage: "git branch create failed",
886 }).pipe(Effect.asVoid);
887
888 const checkoutBranch: GitCoreShape["checkoutBranch"] = (input) =>
889 Effect.gen(function* () {
890 const [localInputExists, remoteExists] = yield* Effect.all(
891 [
892 executeGit(
893 "GitCore.checkoutBranch.localInputExists",
894 input.cwd,
895 ["show-ref", "--verify", "--quiet", `refs/heads/${input.branch}`],
896 {
897 timeoutMs: 5_000,
898 allowNonZeroExit: true,
899 },
900 ).pipe(Effect.map((result) => result.code === 0)),
901 executeGit(
902 "GitCore.checkoutBranch.remoteExists",
903 input.cwd,
904 ["show-ref", "--verify", "--quiet", `refs/remotes/${input.branch}`],
905 {
906 timeoutMs: 5_000,
907 allowNonZeroExit: true,
908 },
909 ).pipe(Effect.map((result) => result.code === 0)),
910 ],
911 { concurrency: "unbounded" },
912 );
913
914 const localTrackingBranch =
915 remoteExists
916 ? yield* executeGit(
917 "GitCore.checkoutBranch.localTrackingBranch",
918 input.cwd,
919 ["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"],
920 {
921 timeoutMs: 5_000,
922 allowNonZeroExit: true,
923 },
924 ).pipe(
925 Effect.map((result) =>
926 result.code === 0
927 ? parseTrackingBranchByUpstreamRef(result.stdout, input.branch)
928 : null,
929 ),
930 )
931 : null;
932
933 const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch);
934 const localTrackedBranchTargetExists =
935 remoteExists && localTrackedBranchCandidate
936 ? yield* executeGit(
937 "GitCore.checkoutBranch.localTrackedBranchTargetExists",
938 input.cwd,
939 ["show-ref", "--verify", "--quiet", `refs/heads/${localTrackedBranchCandidate}`],
940 {
941 timeoutMs: 5_000,
942 allowNonZeroExit: true,
943 },
944 ).pipe(Effect.map((result) => result.code === 0))
945 : false;
946
947 const checkoutArgs =
948 localInputExists
949 ? ["checkout", input.branch]
950 : remoteExists && !localTrackingBranch && localTrackedBranchTargetExists
951 ? ["checkout", input.branch]
952 : remoteExists && !localTrackingBranch
953 ? ["checkout", "--track", input.branch]
954 : remoteExists && localTrackingBranch
955 ? ["checkout", localTrackingBranch]
956 : ["checkout", input.branch];
957
958 yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, {
959 timeoutMs: 10_000,
960 fallbackErrorMessage: "git checkout failed",
961 });
962
963 // Refresh upstream refs in the background so checkout remains responsive.
964 yield* Effect.sync(() => {
965 void Effect.runPromise(
966 refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
967 );
968 });
969 });
970
971 const initRepo: GitCoreShape["initRepo"] = (input) =>
972 executeGit("GitCore.initRepo", input.cwd, ["init"], {
973 timeoutMs: 10_000,
974 fallbackErrorMessage: "git init failed",
975 }).pipe(Effect.asVoid);
976
977 return {
978 status,
979 statusDetails,
980 prepareCommitContext,
981 commit,
982 pushCurrentBranch,
983 pullCurrentBranch,
984 readRangeContext,
985 readConfigValue,
986 listBranches,
987 createWorktree,
988 removeWorktree,
989 createBranch,
990 checkoutBranch,
991 initRepo,
992 } satisfies GitCoreShape;
993});
994
995export const GitCoreLive = Layer.effect(GitCore, makeGitCore);