gunk-dev/the-valley

git_test.go

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