gunk-dev/the-valley

git_test.go

sourcec14b0e68e9c3main's published tip history
27.4 KiB
1package git
2
3import (
4 "context"
5 "errors"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "strings"
10 "sync"
11 "testing"
12)
13
14// initTestRepo creates a temporary git repo with one commit and returns its path.
15func initTestRepo(t *testing.T) string {
16 t.Helper()
17 dir := t.TempDir()
18
19 cmds := [][]string{
20 {"git", "init", "--initial-branch=main", dir},
21 {"git", "-C", dir, "config", "user.email", "test@test.com"},
22 {"git", "-C", dir, "config", "user.name", "Test"},
23 }
24 for _, args := range cmds {
25 cmd := exec.Command(args[0], args[1:]...)
26 if out, err := cmd.CombinedOutput(); err != nil {
27 t.Fatalf("setup %v: %v\n%s", args, err, out)
28 }
29 }
30
31 // Create a file and initial commit
32 if err := os.WriteFile(filepath.Join(dir, "README.md"), []byte("# test\n"), 0o644); err != nil {
33 t.Fatal(err)
34 }
35 for _, args := range [][]string{
36 {"git", "-C", dir, "add", "README.md"},
37 {"git", "-C", dir, "commit", "-m", "initial"},
38 } {
39 cmd := exec.Command(args[0], args[1:]...)
40 if out, err := cmd.CombinedOutput(); err != nil {
41 t.Fatalf("setup %v: %v\n%s", args, err, out)
42 }
43 }
44
45 return dir
46}
47
48func TestWorktreeAddRemove(t *testing.T) {
49 ctx := context.Background()
50 repo := initTestRepo(t)
51 wtPath := filepath.Join(t.TempDir(), "worktree1")
52
53 if err := WorktreeAdd(ctx, repo, wtPath, "test-branch", "main"); err != nil {
54 t.Fatalf("WorktreeAdd: %v", err)
55 }
56
57 // Verify worktree exists
58 if _, err := os.Stat(filepath.Join(wtPath, "README.md")); err != nil {
59 t.Errorf("worktree should contain README.md: %v", err)
60 }
61
62 if err := WorktreeRemove(ctx, repo, wtPath); err != nil {
63 t.Fatalf("WorktreeRemove: %v", err)
64 }
65
66 // Verify worktree is gone
67 if _, err := os.Stat(wtPath); !os.IsNotExist(err) {
68 t.Error("worktree directory should be removed")
69 }
70}
71
72func TestCommonDirFromWorktree(t *testing.T) {
73 ctx := context.Background()
74 repo := initTestRepo(t)
75 wtPath := filepath.Join(t.TempDir(), "wt")
76
77 if err := WorktreeAdd(ctx, repo, wtPath, "test-branch", "main"); err != nil {
78 t.Fatalf("WorktreeAdd: %v", err)
79 }
80 defer WorktreeRemove(ctx, repo, wtPath)
81
82 // Save original dir and chdir to worktree
83 origDir, err := os.Getwd()
84 if err != nil {
85 t.Fatal(err)
86 }
87 defer os.Chdir(origDir)
88 os.Chdir(wtPath)
89
90 // RepoRoot from a worktree returns the worktree path, NOT the main repo
91 root, err := RepoRoot()
92 if err != nil {
93 t.Fatalf("RepoRoot: %v", err)
94 }
95 if root != wtPath {
96 t.Errorf("RepoRoot() = %q, expected worktree path %q", root, wtPath)
97 }
98
99 // CommonDir from a worktree returns the main repo's .git dir
100 common, err := CommonDir(ctx)
101 if err != nil {
102 t.Fatalf("CommonDir: %v", err)
103 }
104 mainRoot := filepath.Dir(common)
105 if mainRoot != repo {
106 t.Errorf("filepath.Dir(CommonDir()) = %q, expected main repo %q", mainRoot, repo)
107 }
108
109 // The main repo root survives worktree removal.
110 if err := WorktreeRemove(ctx, repo, wtPath); err != nil {
111 t.Fatalf("WorktreeRemove: %v", err)
112 }
113 if _, err := os.Stat(mainRoot); err != nil {
114 t.Errorf("main repo root should still exist after worktree removal: %v", err)
115 }
116 if _, err := os.Stat(wtPath); !os.IsNotExist(err) {
117 t.Error("worktree should be gone after removal")
118 }
119}
120
121func TestEnsureDataRef(t *testing.T) {
122 ctx := context.Background()
123 repo := initTestRepo(t)
124 ref := "refs/klaus/data"
125
126 // First call creates the ref
127 if err := EnsureDataRef(ctx, repo, ref); err != nil {
128 t.Fatalf("EnsureDataRef (create): %v", err)
129 }
130
131 // Verify ref exists
132 out, err := runGit(ctx, repo, "rev-parse", "--verify", ref)
133 if err != nil {
134 t.Fatalf("ref should exist: %v", err)
135 }
136 if out == "" {
137 t.Error("ref should resolve to a commit")
138 }
139
140 // Second call is idempotent
141 if err := EnsureDataRef(ctx, repo, ref); err != nil {
142 t.Fatalf("EnsureDataRef (idempotent): %v", err)
143 }
144}
145
146func TestSyncToDataRef(t *testing.T) {
147 ctx := context.Background()
148 repo := initTestRepo(t)
149 ref := "refs/klaus/data"
150
151 // Create a temp file to sync
152 tmpFile := filepath.Join(t.TempDir(), "state.json")
153 if err := os.WriteFile(tmpFile, []byte(`{"id":"test-123"}`), 0o644); err != nil {
154 t.Fatal(err)
155 }
156
157 files := map[string]string{
158 "runs/test-123.json": tmpFile,
159 }
160
161 commit, err := SyncToDataRef(ctx, repo, ref, "Run test-123", files)
162 if err != nil {
163 t.Fatalf("SyncToDataRef: %v", err)
164 }
165 if tip, _ := runGit(ctx, repo, "rev-parse", ref); commit != tip {
166 t.Errorf("SyncToDataRef returned %q, want the ref's tip %q", commit, tip)
167 }
168
169 // Verify the file is in the data ref tree
170 out, err := runGit(ctx, repo, "ls-tree", "-r", "--name-only", ref)
171 if err != nil {
172 t.Fatalf("ls-tree: %v", err)
173 }
174 if out != "runs/test-123.json" {
175 t.Errorf("ls-tree = %q, want 'runs/test-123.json'", out)
176 }
177
178 // Verify content
179 content, err := runGit(ctx, repo, "show", ref+":runs/test-123.json")
180 if err != nil {
181 t.Fatalf("show: %v", err)
182 }
183 if content != `{"id":"test-123"}` {
184 t.Errorf("content = %q, want '{\"id\":\"test-123\"}'", content)
185 }
186}
187
188func TestSyncToDataRefMultipleFiles(t *testing.T) {
189 ctx := context.Background()
190 repo := initTestRepo(t)
191 ref := "refs/klaus/data"
192
193 dir := t.TempDir()
194 f1 := filepath.Join(dir, "a.json")
195 f2 := filepath.Join(dir, "b.jsonl")
196 os.WriteFile(f1, []byte("state"), 0o644)
197 os.WriteFile(f2, []byte("log"), 0o644)
198
199 files := map[string]string{
200 "runs/a.json": f1,
201 "logs/a.jsonl": f2,
202 }
203
204 if _, err := SyncToDataRef(ctx, repo, ref, "Run a", files); err != nil {
205 t.Fatalf("SyncToDataRef: %v", err)
206 }
207
208 out, err := runGit(ctx, repo, "ls-tree", "-r", "--name-only", ref)
209 if err != nil {
210 t.Fatalf("ls-tree: %v", err)
211 }
212
213 lines := filepath.SplitList(out)
214 // Just check both files are listed
215 if !containsLine(out, "runs/a.json") || !containsLine(out, "logs/a.jsonl") {
216 t.Errorf("ls-tree = %q, want both runs/a.json and logs/a.jsonl", lines)
217 }
218}
219
220// resetProtocolCache resets the sync.Once so protocol detection runs again.
221func resetProtocolCache() {
222 ghProtocolOnce = sync.Once{}
223 ghProtocolSSH = false
224}
225
226func TestCloneURL(t *testing.T) {
227 defer func() {
228 ResetDetectGHProtocol()
229 resetProtocolCache()
230 }()
231
232 t.Run("https", func(t *testing.T) {
233 resetProtocolCache()
234 SetDetectGHProtocol(func() bool { return false })
235 got := CloneURL("owner", "repo")
236 want := "https://github.com/owner/repo.git"
237 if got != want {
238 t.Errorf("CloneURL() = %q, want %q", got, want)
239 }
240 })
241
242 t.Run("ssh", func(t *testing.T) {
243 resetProtocolCache()
244 SetDetectGHProtocol(func() bool { return true })
245 got := CloneURL("owner", "repo")
246 want := "git@github.com:owner/repo.git"
247 if got != want {
248 t.Errorf("CloneURL() = %q, want %q", got, want)
249 }
250 })
251}
252
253func TestParseRepoRef(t *testing.T) {
254 // Force HTTPS protocol for deterministic test results.
255 defer func() {
256 ResetDetectGHProtocol()
257 resetProtocolCache()
258 }()
259 resetProtocolCache()
260 SetDetectGHProtocol(func() bool { return false })
261
262 tests := []struct {
263 input string
264 wantOwner string
265 wantRepo string
266 wantURL string
267 wantErr bool
268 }{
269 {
270 input: "maintainer/site",
271 wantOwner: "maintainer",
272 wantRepo: "site",
273 wantURL: "https://github.com/maintainer/site.git",
274 },
275 {
276 input: "https://github.com/maintainer/site",
277 wantOwner: "maintainer",
278 wantRepo: "site",
279 wantURL: "https://github.com/maintainer/site.git",
280 },
281 {
282 input: "https://github.com/maintainer/site.git",
283 wantOwner: "maintainer",
284 wantRepo: "site",
285 wantURL: "https://github.com/maintainer/site.git",
286 },
287 {
288 input: "git@github.com:maintainer/site.git",
289 wantOwner: "maintainer",
290 wantRepo: "site",
291 wantURL: "https://github.com/maintainer/site.git",
292 },
293 {
294 input: "https://github.com/maintainer/site/",
295 wantOwner: "maintainer",
296 wantRepo: "site",
297 wantURL: "https://github.com/maintainer/site.git",
298 },
299 {
300 input: "invalid",
301 wantErr: true,
302 },
303 {
304 input: "",
305 wantErr: true,
306 },
307 {
308 input: "/repo",
309 wantErr: true,
310 },
311 {
312 input: "../evil/repo",
313 wantErr: true,
314 },
315 {
316 input: "owner/../etc",
317 wantErr: true,
318 },
319 {
320 input: "https://github.com/../etc/passwd",
321 wantErr: true,
322 },
323 {
324 input: "git@github.com:../evil.git",
325 wantErr: true,
326 },
327 {
328 input: "ssh://git@github.com/maintainer/site.git",
329 wantOwner: "maintainer",
330 wantRepo: "site",
331 wantURL: "https://github.com/maintainer/site.git",
332 },
333 {
334 input: "http://github.com/owner/repo",
335 wantOwner: "owner",
336 wantRepo: "repo",
337 wantURL: "https://github.com/owner/repo.git",
338 },
339 }
340
341 for _, tt := range tests {
342 t.Run(tt.input, func(t *testing.T) {
343 owner, repo, url, err := ParseRepoRef(tt.input)
344 if tt.wantErr {
345 if err == nil {
346 t.Fatalf("expected error for %q", tt.input)
347 }
348 return
349 }
350 if err != nil {
351 t.Fatalf("unexpected error: %v", err)
352 }
353 if owner != tt.wantOwner {
354 t.Errorf("owner = %q, want %q", owner, tt.wantOwner)
355 }
356 if repo != tt.wantRepo {
357 t.Errorf("repo = %q, want %q", repo, tt.wantRepo)
358 }
359 if url != tt.wantURL {
360 t.Errorf("url = %q, want %q", url, tt.wantURL)
361 }
362 })
363 }
364}
365
366func TestParseRepoRefSSH(t *testing.T) {
367 defer func() {
368 ResetDetectGHProtocol()
369 resetProtocolCache()
370 }()
371 resetProtocolCache()
372 SetDetectGHProtocol(func() bool { return true })
373
374 owner, repo, url, err := ParseRepoRef("maintainer/site")
375 if err != nil {
376 t.Fatalf("unexpected error: %v", err)
377 }
378 if owner != "maintainer" || repo != "site" {
379 t.Errorf("owner/repo = %s/%s, want maintainer/site", owner, repo)
380 }
381 want := "git@github.com:maintainer/site.git"
382 if url != want {
383 t.Errorf("url = %q, want %q", url, want)
384 }
385}
386
387func TestInstallHooks_StripsClaudeAttribution(t *testing.T) {
388 ctx := context.Background()
389 repo := initTestRepo(t)
390 wtPath := filepath.Join(t.TempDir(), "wt-hook")
391
392 if err := WorktreeAdd(ctx, repo, wtPath, "hook-test", "main"); err != nil {
393 t.Fatalf("WorktreeAdd: %v", err)
394 }
395 defer WorktreeRemove(ctx, repo, wtPath)
396
397 if err := InstallHooks(ctx, wtPath, Provenance{}, nil); err != nil {
398 t.Fatalf("InstallHooks: %v", err)
399 }
400
401 // Create a file and commit with a Co-Authored-By trailer
402 if err := os.WriteFile(filepath.Join(wtPath, "file.txt"), []byte("hello\n"), 0o644); err != nil {
403 t.Fatal(err)
404 }
405
406 for _, args := range [][]string{
407 {"git", "-C", wtPath, "add", "file.txt"},
408 {"git", "-C", wtPath, "commit", "-m", "add file\n\nCo-Authored-By: Claude Sonnet 4 <noreply@anthropic.com>"},
409 } {
410 cmd := exec.Command(args[0], args[1:]...)
411 if out, err := cmd.CombinedOutput(); err != nil {
412 t.Fatalf("%v: %v\n%s", args, err, out)
413 }
414 }
415
416 // Verify the Co-Authored-By line was stripped
417 msg, err := runGit(ctx, wtPath, "log", "-1", "--format=%B")
418 if err != nil {
419 t.Fatalf("git log: %v", err)
420 }
421 if strings.Contains(msg, "Co-Authored-By") {
422 t.Errorf("commit message should not contain Co-Authored-By, got:\n%s", msg)
423 }
424 if !strings.Contains(msg, "add file") {
425 t.Errorf("commit message should still contain the original message, got:\n%s", msg)
426 }
427}
428
429func TestInstallHooks_PreservesHumanCoAuthor(t *testing.T) {
430 ctx := context.Background()
431 repo := initTestRepo(t)
432 wtPath := filepath.Join(t.TempDir(), "wt-hook-human")
433
434 if err := WorktreeAdd(ctx, repo, wtPath, "hook-human-test", "main"); err != nil {
435 t.Fatalf("WorktreeAdd: %v", err)
436 }
437 defer WorktreeRemove(ctx, repo, wtPath)
438
439 if err := InstallHooks(ctx, wtPath, Provenance{}, nil); err != nil {
440 t.Fatalf("InstallHooks: %v", err)
441 }
442
443 if err := os.WriteFile(filepath.Join(wtPath, "file.txt"), []byte("hello\n"), 0o644); err != nil {
444 t.Fatal(err)
445 }
446
447 for _, args := range [][]string{
448 {"git", "-C", wtPath, "add", "file.txt"},
449 {"git", "-C", wtPath, "commit", "-m", "add file\n\nCo-Authored-By: Alice Smith <alice@example.com>"},
450 } {
451 cmd := exec.Command(args[0], args[1:]...)
452 if out, err := cmd.CombinedOutput(); err != nil {
453 t.Fatalf("%v: %v\n%s", args, err, out)
454 }
455 }
456
457 msg, err := runGit(ctx, wtPath, "log", "-1", "--format=%B")
458 if err != nil {
459 t.Fatalf("git log: %v", err)
460 }
461 if !strings.Contains(msg, "Co-Authored-By: Alice Smith") {
462 t.Errorf("commit message should preserve human Co-Authored-By, got:\n%s", msg)
463 }
464}
465
466func TestInstallHooks_NoTrailerUnchanged(t *testing.T) {
467 ctx := context.Background()
468 repo := initTestRepo(t)
469 wtPath := filepath.Join(t.TempDir(), "wt-hook-clean")
470
471 if err := WorktreeAdd(ctx, repo, wtPath, "hook-clean-test", "main"); err != nil {
472 t.Fatalf("WorktreeAdd: %v", err)
473 }
474 defer WorktreeRemove(ctx, repo, wtPath)
475
476 if err := InstallHooks(ctx, wtPath, Provenance{}, nil); err != nil {
477 t.Fatalf("InstallHooks: %v", err)
478 }
479
480 if err := os.WriteFile(filepath.Join(wtPath, "file.txt"), []byte("hello\n"), 0o644); err != nil {
481 t.Fatal(err)
482 }
483
484 for _, args := range [][]string{
485 {"git", "-C", wtPath, "add", "file.txt"},
486 {"git", "-C", wtPath, "commit", "-m", "just a normal commit message"},
487 } {
488 cmd := exec.Command(args[0], args[1:]...)
489 if out, err := cmd.CombinedOutput(); err != nil {
490 t.Fatalf("%v: %v\n%s", args, err, out)
491 }
492 }
493
494 msg, err := runGit(ctx, wtPath, "log", "-1", "--format=%B")
495 if err != nil {
496 t.Fatalf("git log: %v", err)
497 }
498 if !strings.Contains(msg, "just a normal commit message") {
499 t.Errorf("commit message should be unchanged, got:\n%s", msg)
500 }
501}
502
503func TestInstallHooks_StripsMultiplePatterns(t *testing.T) {
504 ctx := context.Background()
505 repo := initTestRepo(t)
506 wtPath := filepath.Join(t.TempDir(), "wt-hook-multi")
507
508 if err := WorktreeAdd(ctx, repo, wtPath, "hook-multi-test", "main"); err != nil {
509 t.Fatalf("WorktreeAdd: %v", err)
510 }
511 defer WorktreeRemove(ctx, repo, wtPath)
512
513 if err := InstallHooks(ctx, wtPath, Provenance{}, nil); err != nil {
514 t.Fatalf("InstallHooks: %v", err)
515 }
516
517 if err := os.WriteFile(filepath.Join(wtPath, "file.txt"), []byte("hello\n"), 0o644); err != nil {
518 t.Fatal(err)
519 }
520
521 commitMsg := "fix bug\n\nCo-Authored-By: Claude Opus 4 (1M context) <noreply@anthropic.com>\n๐Ÿค– Generated with Claude Code"
522
523 for _, args := range [][]string{
524 {"git", "-C", wtPath, "add", "file.txt"},
525 {"git", "-C", wtPath, "commit", "-m", commitMsg},
526 } {
527 cmd := exec.Command(args[0], args[1:]...)
528 if out, err := cmd.CombinedOutput(); err != nil {
529 t.Fatalf("%v: %v\n%s", args, err, out)
530 }
531 }
532
533 msg, err := runGit(ctx, wtPath, "log", "-1", "--format=%B")
534 if err != nil {
535 t.Fatalf("git log: %v", err)
536 }
537 if strings.Contains(msg, "Co-Authored-By") {
538 t.Errorf("should strip Co-Authored-By, got:\n%s", msg)
539 }
540 if strings.Contains(msg, "Claude") {
541 t.Errorf("should strip Claude references, got:\n%s", msg)
542 }
543 if !strings.Contains(msg, "fix bug") {
544 t.Errorf("should preserve original message, got:\n%s", msg)
545 }
546}
547
548// TestInstallHooks_CoordinatorWorktree mirrors the coordinator session
549// worktree path (see internal/cmd/session.go): after the worktree is created the
550// commit-msg hook is installed, and a real commit with mixed trailers should have
551// the Claude/Anthropic attribution stripped while a human Co-Authored-By is kept.
552func TestInstallHooks_CoordinatorWorktree(t *testing.T) {
553 ctx := context.Background()
554 repo := initTestRepo(t)
555 wtPath := filepath.Join(t.TempDir(), "session-wt")
556
557 if err := WorktreeAdd(ctx, repo, wtPath, "session/test", "main"); err != nil {
558 t.Fatalf("WorktreeAdd: %v", err)
559 }
560 defer WorktreeRemove(ctx, repo, wtPath)
561
562 if err := InstallHooks(ctx, wtPath, Provenance{}, nil); err != nil {
563 t.Fatalf("InstallHooks: %v", err)
564 }
565
566 // The hook must be active: core.hooksPath set and the commit-msg file present.
567 hooksPath, err := runGit(ctx, wtPath, "config", "core.hooksPath")
568 if err != nil {
569 t.Fatalf("git config core.hooksPath: %v", err)
570 }
571 if hooksPath == "" {
572 t.Fatal("core.hooksPath should be set in the coordinator worktree")
573 }
574 if _, err := os.Stat(filepath.Join(hooksPath, "commit-msg")); err != nil {
575 t.Fatalf("commit-msg hook should exist at %s: %v", hooksPath, err)
576 }
577
578 if err := os.WriteFile(filepath.Join(wtPath, "file.txt"), []byte("hello\n"), 0o644); err != nil {
579 t.Fatal(err)
580 }
581
582 commitMsg := "coordinator change\n\n" +
583 "Co-Authored-By: Claude Opus 4 (1M context) <noreply@anthropic.com>\n" +
584 "Co-Authored-By: Bob Human <bob@example.com>\n" +
585 "๐Ÿค– Generated with Claude Code\n" +
586 "Generated with help from Anthropic"
587
588 for _, args := range [][]string{
589 {"git", "-C", wtPath, "add", "file.txt"},
590 {"git", "-C", wtPath, "commit", "-m", commitMsg},
591 } {
592 cmd := exec.CommandContext(ctx, args[0], args[1:]...)
593 if out, err := cmd.CombinedOutput(); err != nil {
594 t.Fatalf("%v: %v\n%s", args, err, out)
595 }
596 }
597
598 msg, err := runGit(ctx, wtPath, "log", "-1", "--format=%B")
599 if err != nil {
600 t.Fatalf("git log: %v", err)
601 }
602 if strings.Contains(msg, "Claude") {
603 t.Errorf("should strip Claude references, got:\n%s", msg)
604 }
605 if strings.Contains(msg, "Anthropic") {
606 t.Errorf("should strip Anthropic references, got:\n%s", msg)
607 }
608 if !strings.Contains(msg, "Co-Authored-By: Bob Human") {
609 t.Errorf("should preserve human Co-Authored-By, got:\n%s", msg)
610 }
611 if !strings.Contains(msg, "coordinator change") {
612 t.Errorf("should preserve original message, got:\n%s", msg)
613 }
614}
615
616func TestWorktreeAdd_PrunesStaleAndRetries(t *testing.T) {
617 ctx := context.Background()
618 repo := initTestRepo(t)
619
620 // Create a worktree, then delete its directory to make it stale
621 stalePath := filepath.Join(t.TempDir(), "stale-wt")
622 if err := WorktreeAdd(ctx, repo, stalePath, "stale-branch", "main"); err != nil {
623 t.Fatalf("WorktreeAdd (setup): %v", err)
624 }
625 // Remove the worktree directory without telling git โ€” makes it stale
626 if err := os.RemoveAll(stalePath); err != nil {
627 t.Fatalf("removing stale worktree dir: %v", err)
628 }
629
630 // Now try to create a new worktree on the same branch โ€” should auto-prune and succeed
631 newPath := filepath.Join(t.TempDir(), "new-wt")
632 if err := WorktreeAdd(ctx, repo, newPath, "stale-branch", "main"); err != nil {
633 t.Fatalf("WorktreeAdd should recover from stale worktree: %v", err)
634 }
635 defer WorktreeRemove(ctx, repo, newPath)
636
637 // Verify the new worktree exists
638 if _, err := os.Stat(filepath.Join(newPath, "README.md")); err != nil {
639 t.Errorf("new worktree should contain README.md: %v", err)
640 }
641}
642
643func TestWorktreeAddTrack_PrunesStaleAndRetries(t *testing.T) {
644 ctx := context.Background()
645 repo := initTestRepo(t)
646
647 // Create a local bare repo as "origin" with a feature branch
648 bareDir := filepath.Join(t.TempDir(), "bare.git")
649 cmd := exec.Command("git", "clone", "--bare", repo, bareDir)
650 if out, err := cmd.CombinedOutput(); err != nil {
651 t.Fatalf("bare clone: %v\n%s", err, out)
652 }
653 if _, err := runGit(ctx, repo, "remote", "add", "origin", bareDir); err != nil {
654 runGit(ctx, repo, "remote", "set-url", "origin", bareDir)
655 }
656
657 // Create and push a feature branch
658 if _, err := runGit(ctx, repo, "branch", "feature-x"); err != nil {
659 t.Fatalf("branch: %v", err)
660 }
661 if _, err := runGit(ctx, repo, "push", "origin", "feature-x"); err != nil {
662 t.Fatalf("push: %v", err)
663 }
664
665 // Create a worktree tracking origin/feature-x, then make it stale
666 stalePath := filepath.Join(t.TempDir(), "stale-track")
667 if err := WorktreeAddTrack(ctx, repo, stalePath, "feature-x", false); err != nil {
668 t.Fatalf("WorktreeAddTrack (setup): %v", err)
669 }
670 if err := os.RemoveAll(stalePath); err != nil {
671 t.Fatalf("removing stale worktree dir: %v", err)
672 }
673
674 // Retry should prune and succeed
675 newPath := filepath.Join(t.TempDir(), "new-track")
676 if err := WorktreeAddTrack(ctx, repo, newPath, "feature-x", false); err != nil {
677 t.Fatalf("WorktreeAddTrack should recover from stale worktree: %v", err)
678 }
679 defer WorktreeRemove(ctx, repo, newPath)
680
681 if _, err := os.Stat(filepath.Join(newPath, "README.md")); err != nil {
682 t.Errorf("new worktree should contain README.md: %v", err)
683 }
684}
685
686// trackingRepo is a repo whose origin, a bare clone, has branch.
687func trackingRepo(t *testing.T, branch string) string {
688 t.Helper()
689 ctx := context.Background()
690 repo := initTestRepo(t)
691 bareDir := filepath.Join(t.TempDir(), "bare.git")
692 if out, err := exec.Command("git", "clone", "--bare", repo, bareDir).CombinedOutput(); err != nil {
693 t.Fatalf("bare clone: %v\n%s", err, out)
694 }
695 if _, err := runGit(ctx, repo, "remote", "add", "origin", bareDir); err != nil {
696 t.Fatalf("remote add: %v", err)
697 }
698 if _, err := runGit(ctx, repo, "branch", branch); err != nil {
699 t.Fatalf("branch: %v", err)
700 }
701 if _, err := runGit(ctx, repo, "push", "-q", "-u", "origin", branch); err != nil {
702 t.Fatalf("push: %v", err)
703 }
704 return repo
705}
706
707// TestWorktreeAddTrack_NeverRemovesAWorktree: a worktree left on the branch
708// is never removed to make way, with or without discard, whatever it holds:
709// WorktreeAddTrack refuses with a WorktreeInUseError naming it and the work
710// there origin lacks, and leaves it, its work and the branch as they were.
711// Once it is gone, the branch is free. A path that already holds anything
712// is refused either way.
713func TestWorktreeAddTrack_NeverRemovesAWorktree(t *testing.T) {
714 ctx := context.Background()
715 for _, tc := range []struct {
716 name string
717 work func(t *testing.T, wt string) // makes the work in the old worktree
718 want string // the work the refusal names
719 }{
720 {"nothing origin lacks", func(*testing.T, string) {}, ""},
721 {"an untracked file", func(t *testing.T, wt string) {
722 if err := os.WriteFile(filepath.Join(wt, "notes.txt"), []byte("wip\n"), 0o644); err != nil {
723 t.Fatal(err)
724 }
725 }, "uncommitted changes"},
726 {"a modified file", func(t *testing.T, wt string) {
727 if err := os.WriteFile(filepath.Join(wt, "README.md"), []byte("# changed\n"), 0o644); err != nil {
728 t.Fatal(err)
729 }
730 }, "uncommitted changes"},
731 {"an unpushed commit", func(t *testing.T, wt string) {
732 if _, err := runGit(ctx, wt, "commit", "-q", "--allow-empty", "-m", "local only"); err != nil {
733 t.Fatal(err)
734 }
735 }, "1 commit(s) not on origin/feature-y"},
736 } {
737 t.Run(tc.name, func(t *testing.T) {
738 repo := trackingRepo(t, "feature-y")
739 oldPath := filepath.Join(t.TempDir(), "old-worktree")
740 if err := WorktreeAddTrack(ctx, repo, oldPath, "feature-y", false); err != nil {
741 t.Fatalf("WorktreeAddTrack (setup): %v", err)
742 }
743 tc.work(t, oldPath)
744 tip, _ := runGit(ctx, repo, "rev-parse", "refs/heads/feature-y")
745 status, _ := runGit(ctx, oldPath, "status", "--porcelain")
746
747 newPath := filepath.Join(t.TempDir(), "new-worktree")
748 for _, discard := range []bool{false, true} {
749 err := WorktreeAddTrack(ctx, repo, newPath, "feature-y", discard)
750 var inUse *WorktreeInUseError
751 if !errors.As(err, &inUse) || inUse.Path != oldPath || inUse.Work != tc.want {
752 t.Fatalf("WorktreeAddTrack(discard %v) = %v, want a WorktreeInUseError naming %s and %q", discard, err, oldPath, tc.want)
753 }
754 if got, _ := runGit(ctx, oldPath, "status", "--porcelain"); got != status {
755 t.Errorf("the old worktree's work should be untouched: %q, was %q", got, status)
756 }
757 if got, _ := runGit(ctx, repo, "rev-parse", "refs/heads/feature-y"); got != tip {
758 t.Errorf("branch moved from %s to %s", tip, got)
759 }
760 if _, err := os.Stat(newPath); !os.IsNotExist(err) {
761 t.Errorf("no new worktree should exist: %v", err)
762 }
763 }
764 if err := WorktreeAddTrack(ctx, repo, t.TempDir(), "feature-y", true); err == nil || !strings.Contains(err.Error(), "already exists") {
765 t.Errorf("an existing path should be refused, even with discard: %v", err)
766 }
767
768 if err := WorktreeRemove(ctx, repo, oldPath); err != nil {
769 t.Fatal(err)
770 }
771 if err := WorktreeAddTrack(ctx, repo, newPath, "feature-y", true); err != nil {
772 t.Fatalf("WorktreeAddTrack once the old worktree is gone: %v", err)
773 }
774 defer WorktreeRemove(ctx, repo, newPath)
775 origin, _ := runGit(ctx, repo, "rev-parse", "refs/remotes/origin/feature-y")
776 if got, _ := runGit(ctx, newPath, "rev-parse", "HEAD"); got != origin {
777 t.Errorf("new worktree at %s, want origin's %s", got, origin)
778 }
779 })
780 }
781}
782
783// TestWorktreeAddTrack_RefusesToDiscardLocalCommits: a local branch no
784// worktree has checked out, with commits origin lacks, is refused with a
785// LocalWorkError and left as it was, unless discard is set: then the new
786// worktree starts at origin's tip.
787func TestWorktreeAddTrack_RefusesToDiscardLocalCommits(t *testing.T) {
788 ctx := context.Background()
789 repo := trackingRepo(t, "feature-z")
790 oldPath := filepath.Join(t.TempDir(), "old-worktree")
791 if err := WorktreeAddTrack(ctx, repo, oldPath, "feature-z", false); err != nil {
792 t.Fatalf("WorktreeAddTrack (setup): %v", err)
793 }
794 if _, err := runGit(ctx, oldPath, "commit", "-q", "--allow-empty", "-m", "local only"); err != nil {
795 t.Fatal(err)
796 }
797 if err := WorktreeRemove(ctx, repo, oldPath); err != nil {
798 t.Fatal(err)
799 }
800 tip, _ := runGit(ctx, repo, "rev-parse", "refs/heads/feature-z")
801
802 newPath := filepath.Join(t.TempDir(), "new-worktree")
803 err := WorktreeAddTrack(ctx, repo, newPath, "feature-z", false)
804 var lw *LocalWorkError
805 if want := `local branch "feature-z" has 1 commit(s) not on origin/feature-z`; !errors.As(err, &lw) || err.Error() != want {
806 t.Fatalf("WorktreeAddTrack = %v, want a LocalWorkError saying %q", err, want)
807 }
808 if _, err := os.Stat(newPath); !os.IsNotExist(err) {
809 t.Error("a refused worktree should not be created")
810 }
811 if got, _ := runGit(ctx, repo, "rev-parse", "refs/heads/feature-z"); got != tip {
812 t.Errorf("branch moved from %s to %s", tip, got)
813 }
814
815 if err := WorktreeAddTrack(ctx, repo, newPath, "feature-z", true); err != nil {
816 t.Fatalf("WorktreeAddTrack with discard: %v", err)
817 }
818 defer WorktreeRemove(ctx, repo, newPath)
819 origin, _ := runGit(ctx, repo, "rev-parse", "refs/remotes/origin/feature-z")
820 if got, _ := runGit(ctx, newPath, "rev-parse", "HEAD"); got != origin {
821 t.Errorf("new worktree at %s, want origin's %s", got, origin)
822 }
823}
824
825func TestWorktreeAdd_LiveWorktreeReturnsError(t *testing.T) {
826 ctx := context.Background()
827 repo := initTestRepo(t)
828
829 // Create a worktree that's still live (directory exists)
830 livePath := filepath.Join(t.TempDir(), "live-wt")
831 if err := WorktreeAdd(ctx, repo, livePath, "live-branch", "main"); err != nil {
832 t.Fatalf("WorktreeAdd (setup): %v", err)
833 }
834 defer WorktreeRemove(ctx, repo, livePath)
835
836 // Try to create another worktree on the same branch โ€” should fail with a clear error
837 otherPath := filepath.Join(t.TempDir(), "other-wt")
838 err := WorktreeAdd(ctx, repo, otherPath, "live-branch", "main")
839 if err == nil {
840 t.Fatal("WorktreeAdd should fail when branch is in a live worktree")
841 }
842 if !strings.Contains(err.Error(), "already checked out in active worktree") {
843 t.Errorf("error should mention active worktree, got: %v", err)
844 }
845 if !strings.Contains(err.Error(), livePath) {
846 t.Errorf("error should mention the conflicting path %q, got: %v", livePath, err)
847 }
848}
849
850func TestWorktreePrune(t *testing.T) {
851 ctx := context.Background()
852 repo := initTestRepo(t)
853
854 // Create a worktree, delete its directory, then prune
855 wtPath := filepath.Join(t.TempDir(), "prune-wt")
856 if err := WorktreeAdd(ctx, repo, wtPath, "prune-branch", "main"); err != nil {
857 t.Fatalf("WorktreeAdd: %v", err)
858 }
859 os.RemoveAll(wtPath)
860
861 if err := WorktreePrune(ctx, repo); err != nil {
862 t.Fatalf("WorktreePrune: %v", err)
863 }
864
865 // After prune, creating a worktree on the same branch should work
866 // (using -B since the branch ref still exists after prune)
867 newPath := filepath.Join(t.TempDir(), "after-prune")
868 _, err := runGit(ctx, repo, "worktree", "add", newPath, "-B", "prune-branch", "main", "--quiet")
869 if err != nil {
870 t.Fatalf("worktree add after prune should succeed: %v", err)
871 }
872}
873
874func containsLine(output, target string) bool {
875 for _, line := range splitLines(output) {
876 if line == target {
877 return true
878 }
879 }
880 return false
881}
882
883func splitLines(s string) []string {
884 var lines []string
885 for _, line := range filepath.SplitList(s) {
886 if line != "" {
887 lines = append(lines, line)
888 }
889 }
890 // filepath.SplitList uses OS path separator, we need newlines
891 result := []string{}
892 start := 0
893 for i, c := range s {
894 if c == '\n' {
895 if i > start {
896 result = append(result, s[start:i])
897 }
898 start = i + 1
899 }
900 }
901 if start < len(s) {
902 result = append(result, s[start:])
903 }
904 return result
905}