@@ -0,0 +1,212 @@
1+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+import { mkdirSync, rmSync, writeFileSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import {
6+ MergeInProgressError,
7+ cleanupBranch,
8+ createWorktree,
9+ hasDirtyWorkingTree,
10+ isGitRepo,
11+ mergeWorktree,
12+ removeWorktree,
13+ syncDirtyStateToWorktree,
14+} from "./worktree.ts";
15+
16+function git(cwd: string, args: string[]): string {
17+ const proc = Bun.spawnSync(["git", ...args], {
18+ cwd,
19+ stdout: "pipe",
20+ stderr: "pipe",
21+ });
22+ if (proc.exitCode !== 0) {
23+ throw new Error(`git ${args.join(" ")} failed: ${proc.stderr.toString()}`);
24+ }
25+ return proc.stdout.toString().trim();
26+}
27+
28+function gitStatusLines(cwd: string): string[] {
29+ const output = git(cwd, ["status", "--porcelain", "-u"]);
30+ if (!output) return [];
31+ return output
32+ .split("\n")
33+ .filter((line) => line.length > 0)
34+ .sort();
35+}
36+
37+function makeRepo(): string {
38+ const dir = join(
39+ tmpdir(),
40+ `mc-worktree-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
41+ );
42+ mkdirSync(dir, { recursive: true });
43+ git(dir, ["init"]);
44+ git(dir, ["config", "user.email", "test@example.com"]);
45+ git(dir, ["config", "user.name", "Test"]);
46+ writeFileSync(join(dir, "README.md"), "hello\n");
47+ git(dir, ["add", "README.md"]);
48+ git(dir, ["commit", "-m", "init"]);
49+ return dir;
50+}
51+
52+describe("worktree helpers", () => {
53+ let repoDir = "";
54+ const extraDirs: string[] = [];
55+
56+ beforeEach(() => {
57+ repoDir = makeRepo();
58+ });
59+
60+ afterEach(() => {
61+ for (const dir of extraDirs.splice(0)) {
62+ rmSync(dir, { recursive: true, force: true });
63+ }
64+ rmSync(repoDir, { recursive: true, force: true });
65+ });
66+
67+ test("detects git and non-git directories", async () => {
68+ expect(await isGitRepo(repoDir)).toBe(true);
69+
70+ const nonGit = join(
71+ tmpdir(),
72+ `mc-worktree-nongit-${Date.now()}-${Math.random().toString(36).slice(2)}`,
73+ );
74+ extraDirs.push(nonGit);
75+ mkdirSync(nonGit, { recursive: true });
76+ expect(await isGitRepo(nonGit)).toBe(false);
77+ });
78+
79+ test("detects dirty working tree state", async () => {
80+ expect(await hasDirtyWorkingTree(repoDir)).toBe(false);
81+
82+ writeFileSync(join(repoDir, "untracked.txt"), "dirty\n");
83+ expect(await hasDirtyWorkingTree(repoDir)).toBe(true);
84+ });
85+
86+ test("syncs dirty tracked, staged, and untracked state into worktree", async () => {
87+ const branch = `mc-sub-dirty-${Date.now()}`;
88+ const wtPath = join(
89+ tmpdir(),
90+ `mc-wt-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
91+ );
92+ extraDirs.push(wtPath);
93+
94+ await createWorktree(repoDir, branch, wtPath);
95+
96+ writeFileSync(join(repoDir, "README.md"), "tracked but unstaged\n");
97+ writeFileSync(join(repoDir, "staged.txt"), "staged file\n");
98+ git(repoDir, ["add", "staged.txt"]);
99+ writeFileSync(join(repoDir, "untracked.txt"), "untracked file\n");
100+
101+ await syncDirtyStateToWorktree(repoDir, wtPath);
102+
103+ expect(await Bun.file(join(wtPath, "README.md")).text()).toBe(
104+ "tracked but unstaged\n",
105+ );
106+ expect(await Bun.file(join(wtPath, "staged.txt")).text()).toBe(
107+ "staged file\n",
108+ );
109+ expect(await Bun.file(join(wtPath, "untracked.txt")).text()).toBe(
110+ "untracked file\n",
111+ );
112+ expect(gitStatusLines(wtPath)).toEqual(gitStatusLines(repoDir));
113+
114+ await removeWorktree(repoDir, wtPath);
115+ await cleanupBranch(repoDir, branch);
116+ });
117+
118+ test("creates a worktree and merges successfully", async () => {
119+ const branch = `mc-sub-1-${Date.now()}`;
120+ const wtPath = join(
121+ tmpdir(),
122+ `mc-wt-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
123+ );
124+ extraDirs.push(wtPath);
125+
126+ await createWorktree(repoDir, branch, wtPath);
127+ writeFileSync(join(wtPath, "feature.txt"), "from branch\n");
128+ git(wtPath, ["add", "feature.txt"]);
129+ git(wtPath, ["commit", "-m", "feature"]);
130+
131+ const merge = await mergeWorktree(repoDir, branch);
132+ expect(merge).toEqual({ success: true });
133+ expect(await Bun.file(join(repoDir, "feature.txt")).text()).toBe(
134+ "from branch\n",
135+ );
136+
137+ await removeWorktree(repoDir, wtPath);
138+ await cleanupBranch(repoDir, branch);
139+ });
140+
141+ test("returns conflict files when merge conflicts", async () => {
142+ const branch = `mc-sub-2-${Date.now()}`;
143+ const wtPath = join(
144+ tmpdir(),
145+ `mc-wt-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
146+ );
147+ extraDirs.push(wtPath);
148+
149+ await createWorktree(repoDir, branch, wtPath);
150+
151+ writeFileSync(join(repoDir, "README.md"), "main change\n");
152+ git(repoDir, ["commit", "-am", "main change"]);
153+
154+ writeFileSync(join(wtPath, "README.md"), "branch change\n");
155+ git(wtPath, ["commit", "-am", "branch change"]);
156+
157+ const merge = await mergeWorktree(repoDir, branch);
158+ expect(merge.success).toBe(false);
159+ if (!merge.success) {
160+ expect(merge.conflictFiles).toContain("README.md");
161+ }
162+
163+ git(repoDir, ["merge", "--abort"]);
164+ await removeWorktree(repoDir, wtPath);
165+ await cleanupBranch(repoDir, branch);
166+ });
167+
168+ test("throws MergeInProgressError when another merge is already in progress", async () => {
169+ const branch1 = `mc-sub-3-${Date.now()}`;
170+ const branch2 = `mc-sub-4-${Date.now()}`;
171+ const wtPath1 = join(
172+ tmpdir(),
173+ `mc-wt-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
174+ );
175+ const wtPath2 = join(
176+ tmpdir(),
177+ `mc-wt-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
178+ );
179+ extraDirs.push(wtPath1, wtPath2);
180+
181+ await createWorktree(repoDir, branch1, wtPath1);
182+ await createWorktree(repoDir, branch2, wtPath2);
183+
184+ writeFileSync(join(repoDir, "README.md"), "main change\n");
185+ git(repoDir, ["commit", "-am", "main change"]);
186+
187+ writeFileSync(join(wtPath1, "README.md"), "branch one\n");
188+ git(wtPath1, ["commit", "-am", "branch one"]);
189+
190+ writeFileSync(join(wtPath2, "README.md"), "branch two\n");
191+ git(wtPath2, ["commit", "-am", "branch two"]);
192+
193+ const firstMerge = await mergeWorktree(repoDir, branch1);
194+ expect(firstMerge.success).toBe(false);
195+
196+ try {
197+ await mergeWorktree(repoDir, branch2);
198+ throw new Error("expected mergeWorktree to throw");
199+ } catch (error) {
200+ expect(error).toBeInstanceOf(MergeInProgressError);
201+ if (error instanceof MergeInProgressError) {
202+ expect(error.conflictFiles).toContain("README.md");
203+ }
204+ }
205+
206+ git(repoDir, ["merge", "--abort"]);
207+ await removeWorktree(repoDir, wtPath1);
208+ await removeWorktree(repoDir, wtPath2);
209+ await cleanupBranch(repoDir, branch1);
210+ await cleanupBranch(repoDir, branch2);
211+ });
212+});