-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathrefresh_test.go
More file actions
777 lines (652 loc) · 22.2 KB
/
refresh_test.go
File metadata and controls
777 lines (652 loc) · 22.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
package worktree
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// createTestRepoWithRemote creates a test repo with an origin remote
func createTestRepoWithRemote(t *testing.T) (string, func()) {
t.Helper()
// Create temp directory for the "remote" bare repo
remoteDir, err := os.MkdirTemp("", "worktree-remote-*")
if err != nil {
t.Fatalf("Failed to create remote dir: %v", err)
}
// Initialize bare repo as remote with initial branch
cmd := exec.Command("git", "init", "--bare", "--initial-branch=main")
cmd.Dir = remoteDir
if err := cmd.Run(); err != nil {
os.RemoveAll(remoteDir)
t.Fatalf("Failed to init bare repo: %v", err)
}
// Create temp directory for the local repo
localDir, err := os.MkdirTemp("", "worktree-local-*")
if err != nil {
os.RemoveAll(remoteDir)
t.Fatalf("Failed to create local dir: %v", err)
}
// Initialize local repo
cmd = exec.Command("git", "init", "-b", "main")
cmd.Dir = localDir
if err := cmd.Run(); err != nil {
os.RemoveAll(remoteDir)
os.RemoveAll(localDir)
t.Fatalf("Failed to init local repo: %v", err)
}
// Configure git user
cmd = exec.Command("git", "config", "user.name", "Test User")
cmd.Dir = localDir
cmd.Run()
cmd = exec.Command("git", "config", "user.email", "test@example.com")
cmd.Dir = localDir
cmd.Run()
// Create initial commit
testFile := filepath.Join(localDir, "README.md")
if err := os.WriteFile(testFile, []byte("# Test Repo\n"), 0644); err != nil {
os.RemoveAll(remoteDir)
os.RemoveAll(localDir)
t.Fatalf("Failed to create test file: %v", err)
}
cmd = exec.Command("git", "add", "README.md")
cmd.Dir = localDir
if err := cmd.Run(); err != nil {
os.RemoveAll(remoteDir)
os.RemoveAll(localDir)
t.Fatalf("Failed to git add: %v", err)
}
cmd = exec.Command("git", "commit", "-m", "Initial commit")
cmd.Dir = localDir
if err := cmd.Run(); err != nil {
os.RemoveAll(remoteDir)
os.RemoveAll(localDir)
t.Fatalf("Failed to commit: %v", err)
}
// Add remote
cmd = exec.Command("git", "remote", "add", "origin", remoteDir)
cmd.Dir = localDir
if err := cmd.Run(); err != nil {
os.RemoveAll(remoteDir)
os.RemoveAll(localDir)
t.Fatalf("Failed to add remote: %v", err)
}
// Push to remote
cmd = exec.Command("git", "push", "-u", "origin", "main")
cmd.Dir = localDir
if err := cmd.Run(); err != nil {
os.RemoveAll(remoteDir)
os.RemoveAll(localDir)
t.Fatalf("Failed to push: %v", err)
}
cleanup := func() {
os.RemoveAll(remoteDir)
os.RemoveAll(localDir)
}
return localDir, cleanup
}
// addCommitToRemote adds a commit to the remote by creating another clone,
// committing, and pushing
func addCommitToRemote(t *testing.T, localDir string, message string) {
t.Helper()
// Get the remote URL
cmd := exec.Command("git", "remote", "get-url", "origin")
cmd.Dir = localDir
output, err := cmd.Output()
if err != nil {
t.Fatalf("Failed to get remote URL: %v", err)
}
remoteURL := strings.TrimSpace(string(output))
// Create a temp clone to make changes
tempClone, err := os.MkdirTemp("", "temp-clone-*")
if err != nil {
t.Fatalf("Failed to create temp clone dir: %v", err)
}
defer os.RemoveAll(tempClone)
cmd = exec.Command("git", "clone", remoteURL, tempClone)
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to clone for remote commit: %v", err)
}
// Configure git user
cmd = exec.Command("git", "config", "user.name", "Test User")
cmd.Dir = tempClone
cmd.Run()
cmd = exec.Command("git", "config", "user.email", "test@example.com")
cmd.Dir = tempClone
cmd.Run()
// Create a new file and commit
newFile := filepath.Join(tempClone, message+".txt")
if err := os.WriteFile(newFile, []byte(message+"\n"), 0644); err != nil {
t.Fatalf("Failed to create file: %v", err)
}
cmd = exec.Command("git", "add", ".")
cmd.Dir = tempClone
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to git add: %v", err)
}
cmd = exec.Command("git", "commit", "-m", message)
cmd.Dir = tempClone
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to commit: %v", err)
}
cmd = exec.Command("git", "push", "origin", "main")
cmd.Dir = tempClone
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to push: %v", err)
}
}
func TestRefreshWorktree_DetachedHead(t *testing.T) {
repoPath, cleanup := createTestRepo(t)
defer cleanup()
manager := NewManager(repoPath)
// Create a worktree
wtPath := filepath.Join(repoPath, "wt-detached")
if err := manager.CreateNewBranch(wtPath, "feature-branch", "main"); err != nil {
t.Fatalf("Failed to create worktree: %v", err)
}
// Detach HEAD in the worktree
cmd := exec.Command("git", "checkout", "--detach")
cmd.Dir = wtPath
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to detach HEAD: %v", err)
}
// RefreshWorktree should skip detached HEAD
result := RefreshWorktree(wtPath, "origin", "main")
if !result.Skipped {
t.Error("Expected RefreshWorktree to skip detached HEAD")
}
if result.SkipReason == "" || !strings.Contains(result.SkipReason, "detached HEAD") {
t.Errorf("Expected detached HEAD skip reason, got: %s", result.SkipReason)
}
}
func TestRefreshWorktree_OnMainBranch(t *testing.T) {
repoPath, cleanup := createTestRepo(t)
defer cleanup()
// RefreshWorktree should skip if on main branch
result := RefreshWorktree(repoPath, "origin", "main")
if !result.Skipped {
t.Error("Expected RefreshWorktree to skip main branch")
}
if result.SkipReason == "" || !strings.Contains(result.SkipReason, "main branch") {
t.Errorf("Expected main branch skip reason, got: %s", result.SkipReason)
}
}
func TestRefreshWorktree_MidRebase(t *testing.T) {
repoPath, cleanup := createTestRepo(t)
defer cleanup()
manager := NewManager(repoPath)
// Create a worktree
wtPath := filepath.Join(repoPath, "wt-rebase")
if err := manager.CreateNewBranch(wtPath, "feature-branch", "main"); err != nil {
t.Fatalf("Failed to create worktree: %v", err)
}
// Simulate mid-rebase state by creating the rebase-merge directory
gitDir := resolveGitDir(wtPath)
rebaseDir := filepath.Join(gitDir, "rebase-merge")
if err := os.MkdirAll(rebaseDir, 0755); err != nil {
t.Fatalf("Failed to create rebase-merge dir: %v", err)
}
// RefreshWorktree should skip mid-rebase
result := RefreshWorktree(wtPath, "origin", "main")
if !result.Skipped {
t.Error("Expected RefreshWorktree to skip mid-rebase state")
}
if result.SkipReason == "" || !strings.Contains(result.SkipReason, "mid-rebase") {
t.Errorf("Expected mid-rebase skip reason, got: %s", result.SkipReason)
}
}
func TestRefreshWorktree_MidMerge(t *testing.T) {
repoPath, cleanup := createTestRepo(t)
defer cleanup()
manager := NewManager(repoPath)
// Create a worktree
wtPath := filepath.Join(repoPath, "wt-merge")
if err := manager.CreateNewBranch(wtPath, "feature-branch", "main"); err != nil {
t.Fatalf("Failed to create worktree: %v", err)
}
// Simulate mid-merge state by creating MERGE_HEAD file
gitDir := resolveGitDir(wtPath)
mergeHead := filepath.Join(gitDir, "MERGE_HEAD")
if err := os.WriteFile(mergeHead, []byte("abc123"), 0644); err != nil {
t.Fatalf("Failed to create MERGE_HEAD: %v", err)
}
// RefreshWorktree should skip mid-merge
result := RefreshWorktree(wtPath, "origin", "main")
if !result.Skipped {
t.Error("Expected RefreshWorktree to skip mid-merge state")
}
if result.SkipReason == "" || !strings.Contains(result.SkipReason, "mid-merge") {
t.Errorf("Expected mid-merge skip reason, got: %s", result.SkipReason)
}
}
func TestRefreshWorktree_NonExistentPath(t *testing.T) {
// RefreshWorktree should return error for non-existent path
result := RefreshWorktree("/nonexistent/path", "origin", "main")
if result.Error == nil {
t.Error("Expected error for non-existent path")
}
}
func TestGetWorktreeState_UpToDate(t *testing.T) {
repoPath, cleanup := createTestRepoWithRemote(t)
defer cleanup()
manager := NewManager(repoPath)
// Create a worktree on a feature branch
wtPath := filepath.Join(repoPath, "wt-state")
if err := manager.CreateNewBranch(wtPath, "feature-branch", "main"); err != nil {
t.Fatalf("Failed to create worktree: %v", err)
}
// Get worktree state
state, err := GetWorktreeState(wtPath, "origin", "main")
if err != nil {
t.Fatalf("GetWorktreeState() failed: %v", err)
}
// Should be up to date initially
if state.CommitsBehind != 0 {
t.Errorf("Expected 0 commits behind, got %d", state.CommitsBehind)
}
if state.CanRefresh {
t.Error("Should not be able to refresh when up to date")
}
}
func TestGetWorktreeState_DetachedHead(t *testing.T) {
repoPath, cleanup := createTestRepo(t)
defer cleanup()
manager := NewManager(repoPath)
// Create a worktree
wtPath := filepath.Join(repoPath, "wt-detached-state")
if err := manager.CreateNewBranch(wtPath, "feature-branch", "main"); err != nil {
t.Fatalf("Failed to create worktree: %v", err)
}
// Detach HEAD
cmd := exec.Command("git", "checkout", "--detach")
cmd.Dir = wtPath
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to detach HEAD: %v", err)
}
// GetWorktreeState should indicate can't refresh
state, err := GetWorktreeState(wtPath, "origin", "main")
if err != nil {
t.Fatalf("GetWorktreeState() failed: %v", err)
}
if state.CanRefresh {
t.Error("Should not be able to refresh with detached HEAD")
}
if !strings.Contains(state.RefreshReason, "detached") {
t.Errorf("Expected detached HEAD reason, got: %s", state.RefreshReason)
}
}
func TestGetWorktreeState_OnMainBranch(t *testing.T) {
repoPath, cleanup := createTestRepoWithRemote(t)
defer cleanup()
// GetWorktreeState for main branch
state, err := GetWorktreeState(repoPath, "origin", "main")
if err != nil {
t.Fatalf("GetWorktreeState() failed: %v", err)
}
if state.CanRefresh {
t.Error("Should not be able to refresh main branch")
}
if !strings.Contains(state.RefreshReason, "main branch") {
t.Errorf("Expected main branch reason, got: %s", state.RefreshReason)
}
}
func TestGetDefaultBranch_Main(t *testing.T) {
repoPath, cleanup := createTestRepoWithRemote(t)
defer cleanup()
manager := NewManager(repoPath)
// Get default branch
branch, err := manager.GetDefaultBranch("origin")
if err != nil {
t.Fatalf("GetDefaultBranch() failed: %v", err)
}
// Should be main
if branch != "main" {
t.Errorf("Expected 'main', got %q", branch)
}
}
func TestGetDefaultBranch_NoRemote(t *testing.T) {
repoPath, cleanup := createTestRepo(t)
defer cleanup()
manager := NewManager(repoPath)
// Get default branch for non-existent remote
_, err := manager.GetDefaultBranch("nonexistent")
if err == nil {
t.Error("Expected error for non-existent remote")
}
}
func TestGetUpstreamRemote_OnlyOrigin(t *testing.T) {
repoPath, cleanup := createTestRepoWithRemote(t)
defer cleanup()
manager := NewManager(repoPath)
// Should return origin when no upstream
remote, err := manager.GetUpstreamRemote()
if err != nil {
t.Fatalf("GetUpstreamRemote() failed: %v", err)
}
if remote != "origin" {
t.Errorf("Expected 'origin', got %q", remote)
}
}
func TestGetUpstreamRemote_WithUpstream(t *testing.T) {
repoPath, cleanup := createTestRepoWithRemote(t)
defer cleanup()
// Add upstream remote
cmd := exec.Command("git", "remote", "add", "upstream", "https://github.com/test/upstream.git")
cmd.Dir = repoPath
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to add upstream: %v", err)
}
manager := NewManager(repoPath)
// Should return upstream when present
remote, err := manager.GetUpstreamRemote()
if err != nil {
t.Fatalf("GetUpstreamRemote() failed: %v", err)
}
if remote != "upstream" {
t.Errorf("Expected 'upstream', got %q", remote)
}
}
func TestGetUpstreamRemote_NoRemotes(t *testing.T) {
repoPath, cleanup := createTestRepo(t)
defer cleanup()
manager := NewManager(repoPath)
// Should return error when no remotes
_, err := manager.GetUpstreamRemote()
if err == nil {
t.Error("Expected error when no remotes configured")
}
}
func TestIsBehindMain_UpToDate(t *testing.T) {
repoPath, cleanup := createTestRepoWithRemote(t)
defer cleanup()
manager := NewManager(repoPath)
// Create a worktree
wtPath := filepath.Join(repoPath, "wt-behind")
if err := manager.CreateNewBranch(wtPath, "feature-branch", "main"); err != nil {
t.Fatalf("Failed to create worktree: %v", err)
}
// Should not be behind initially
behind, count, err := IsBehindMain(wtPath, "origin", "main")
if err != nil {
t.Fatalf("IsBehindMain() failed: %v", err)
}
if behind {
t.Error("Should not be behind when up to date")
}
if count != 0 {
t.Errorf("Expected 0 commits behind, got %d", count)
}
}
func TestIsBehindMain_ActuallyBehind(t *testing.T) {
repoPath, cleanup := createTestRepoWithRemote(t)
defer cleanup()
manager := NewManager(repoPath)
// Create a worktree on a feature branch
wtPath := filepath.Join(repoPath, "wt-actually-behind")
if err := manager.CreateNewBranch(wtPath, "feature-branch", "main"); err != nil {
t.Fatalf("Failed to create worktree: %v", err)
}
// Add a commit to the remote (simulating other work being merged)
addCommitToRemote(t, repoPath, "remote-change")
// Fetch from remote to update refs
cmd := exec.Command("git", "fetch", "origin")
cmd.Dir = wtPath
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to fetch: %v", err)
}
// Now the worktree should be behind main
behind, count, err := IsBehindMain(wtPath, "origin", "main")
if err != nil {
t.Fatalf("IsBehindMain() failed: %v", err)
}
if !behind {
t.Error("Should be behind after remote commit")
}
if count != 1 {
t.Errorf("Expected 1 commit behind, got %d", count)
}
}
func TestRefreshWorktreeWithDefaults_NoRemote(t *testing.T) {
repoPath, cleanup := createTestRepo(t)
defer cleanup()
manager := NewManager(repoPath)
// Create a worktree
wtPath := filepath.Join(repoPath, "wt-no-remote")
if err := manager.CreateNewBranch(wtPath, "feature-branch", "main"); err != nil {
t.Fatalf("Failed to create worktree: %v", err)
}
// RefreshWorktreeWithDefaults should fail without remote
result := manager.RefreshWorktreeWithDefaults(wtPath)
if result.Error == nil {
t.Error("Expected error when no remote configured")
}
}
func TestRefreshWorktree_WithUncommittedChanges(t *testing.T) {
repoPath, cleanup := createTestRepoWithRemote(t)
defer cleanup()
manager := NewManager(repoPath)
// Create a worktree
wtPath := filepath.Join(repoPath, "wt-uncommitted")
if err := manager.CreateNewBranch(wtPath, "feature-branch", "main"); err != nil {
t.Fatalf("Failed to create worktree: %v", err)
}
// Create uncommitted changes
testFile := filepath.Join(wtPath, "uncommitted.txt")
if err := os.WriteFile(testFile, []byte("uncommitted content"), 0644); err != nil {
t.Fatalf("Failed to create file: %v", err)
}
// RefreshWorktree should handle uncommitted changes (stash and restore)
result := RefreshWorktree(wtPath, "origin", "main")
// Since there's nothing new on main, this might skip or succeed
// The key is it shouldn't lose the uncommitted changes
if result.Error != nil && !strings.Contains(result.Error.Error(), "fetch") {
t.Errorf("Unexpected error: %v", result.Error)
}
// Verify uncommitted file still exists
if _, err := os.Stat(testFile); os.IsNotExist(err) {
t.Error("Uncommitted file should still exist after refresh")
}
}
func TestRefreshResult_Fields(t *testing.T) {
// Test RefreshResult struct
result := RefreshResult{
WorktreePath: "/test/path",
Branch: "feature",
CommitsRebased: 3,
WasStashed: true,
StashRestored: true,
HasConflicts: false,
ConflictFiles: nil,
Error: nil,
Skipped: false,
SkipReason: "",
}
if result.WorktreePath != "/test/path" {
t.Errorf("WorktreePath = %q, want %q", result.WorktreePath, "/test/path")
}
if result.Branch != "feature" {
t.Errorf("Branch = %q, want %q", result.Branch, "feature")
}
if result.CommitsRebased != 3 {
t.Errorf("CommitsRebased = %d, want %d", result.CommitsRebased, 3)
}
if !result.WasStashed {
t.Error("WasStashed should be true")
}
if !result.StashRestored {
t.Error("StashRestored should be true")
}
}
func TestGetWorktreeState_WithMidRebaseApply(t *testing.T) {
repoPath, cleanup := createTestRepo(t)
defer cleanup()
manager := NewManager(repoPath)
// Create a worktree
wtPath := filepath.Join(repoPath, "wt-rebase-apply")
if err := manager.CreateNewBranch(wtPath, "feature-branch", "main"); err != nil {
t.Fatalf("Failed to create worktree: %v", err)
}
// Simulate mid-rebase-apply state
gitDir := resolveGitDir(wtPath)
rebaseApplyDir := filepath.Join(gitDir, "rebase-apply")
if err := os.MkdirAll(rebaseApplyDir, 0755); err != nil {
t.Fatalf("Failed to create rebase-apply dir: %v", err)
}
// GetWorktreeState should detect mid-rebase
state, err := GetWorktreeState(wtPath, "origin", "main")
if err != nil {
t.Fatalf("GetWorktreeState() failed: %v", err)
}
if state.CanRefresh {
t.Error("Should not be able to refresh during rebase-apply")
}
if !strings.Contains(state.RefreshReason, "mid-rebase") {
t.Errorf("Expected mid-rebase reason, got: %s", state.RefreshReason)
}
}
func TestRefreshWorktree_RebaseConflict(t *testing.T) {
repoPath, cleanup := createTestRepoWithRemote(t)
defer cleanup()
manager := NewManager(repoPath)
// Create a worktree with a feature branch
wtPath := filepath.Join(repoPath, "wt-conflict")
if err := manager.CreateNewBranch(wtPath, "feature-conflict", "main"); err != nil {
t.Fatalf("Failed to create worktree: %v", err)
}
// Make a change to README.md in the worktree (will conflict with remote)
conflictFile := filepath.Join(wtPath, "README.md")
if err := os.WriteFile(conflictFile, []byte("# Feature branch change\n"), 0644); err != nil {
t.Fatalf("Failed to write conflict file: %v", err)
}
cmd := exec.Command("git", "add", "README.md")
cmd.Dir = wtPath
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to git add: %v", err)
}
cmd = exec.Command("git", "commit", "-m", "feature change to README")
cmd.Dir = wtPath
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to commit: %v", err)
}
// Push a conflicting change to main via the remote
// We need to modify README.md on main too
remoteURL := ""
cmd = exec.Command("git", "remote", "get-url", "origin")
cmd.Dir = repoPath
if out, err := cmd.Output(); err == nil {
remoteURL = strings.TrimSpace(string(out))
}
tempClone, err := os.MkdirTemp("", "conflict-clone-*")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
defer os.RemoveAll(tempClone)
cmd = exec.Command("git", "clone", remoteURL, tempClone)
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to clone: %v", err)
}
cmd = exec.Command("git", "config", "user.name", "Test User")
cmd.Dir = tempClone
cmd.Run()
cmd = exec.Command("git", "config", "user.email", "test@example.com")
cmd.Dir = tempClone
cmd.Run()
if err := os.WriteFile(filepath.Join(tempClone, "README.md"), []byte("# Conflicting main change\n"), 0644); err != nil {
t.Fatalf("Failed to write: %v", err)
}
cmd = exec.Command("git", "add", "README.md")
cmd.Dir = tempClone
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to add: %v", err)
}
cmd = exec.Command("git", "commit", "-m", "conflicting main change")
cmd.Dir = tempClone
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to commit: %v", err)
}
cmd = exec.Command("git", "push", "origin", "main")
cmd.Dir = tempClone
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to push: %v", err)
}
// Now refresh the worktree - should detect conflict, abort, and return clean state
result := RefreshWorktree(wtPath, "origin", "main")
if result.Error == nil {
t.Fatal("Expected error from conflicting rebase")
}
if !result.HasConflicts {
t.Error("Expected HasConflicts to be true")
}
if len(result.ConflictFiles) == 0 {
t.Error("Expected conflict files to be reported")
}
// Verify worktree is not left in mid-rebase state
gitDir := resolveGitDir(wtPath)
if _, err := os.Stat(filepath.Join(gitDir, "rebase-merge")); err == nil {
t.Error("Worktree should not be in mid-rebase state after abort")
}
if _, err := os.Stat(filepath.Join(gitDir, "rebase-apply")); err == nil {
t.Error("Worktree should not be in mid-rebase-apply state after abort")
}
// Verify the worktree is still on the feature branch
cmd = exec.Command("git", "symbolic-ref", "--short", "HEAD")
cmd.Dir = wtPath
branchOutput, err := cmd.Output()
if err != nil {
t.Fatalf("Failed to get branch: %v", err)
}
if strings.TrimSpace(string(branchOutput)) != "feature-conflict" {
t.Errorf("Expected branch feature-conflict, got %s", strings.TrimSpace(string(branchOutput)))
}
}
func TestRefreshWorktreePreFetched(t *testing.T) {
repoPath, cleanup := createTestRepoWithRemote(t)
defer cleanup()
manager := NewManager(repoPath)
// Create a worktree
wtPath := filepath.Join(repoPath, "wt-prefetched")
if err := manager.CreateNewBranch(wtPath, "feature-prefetched", "main"); err != nil {
t.Fatalf("Failed to create worktree: %v", err)
}
// Add a commit to remote
addCommitToRemote(t, repoPath, "remote-change")
// Manually fetch first (simulating daemon behavior)
cmd := exec.Command("git", "fetch", "origin", "main")
cmd.Dir = wtPath
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to fetch: %v", err)
}
// Use PreFetched variant - should succeed without fetching again
result := RefreshWorktreePreFetched(wtPath, "origin", "main")
if result.Error != nil {
t.Errorf("Unexpected error: %v", result.Error)
}
if result.Skipped {
t.Errorf("Should not have been skipped: %s", result.SkipReason)
}
}
func TestResolveGitDir(t *testing.T) {
repoPath, cleanup := createTestRepo(t)
defer cleanup()
manager := NewManager(repoPath)
// Create a worktree
wtPath := filepath.Join(repoPath, "wt-gitdir")
if err := manager.CreateNewBranch(wtPath, "feature-gitdir", "main"); err != nil {
t.Fatalf("Failed to create worktree: %v", err)
}
// resolveGitDir should return a valid path that exists
gitDir := resolveGitDir(wtPath)
if _, err := os.Stat(gitDir); os.IsNotExist(err) {
t.Errorf("resolveGitDir returned non-existent path: %s", gitDir)
}
// The resolved path should be absolute
if !filepath.IsAbs(gitDir) {
t.Errorf("resolveGitDir should return absolute path, got: %s", gitDir)
}
// For a regular repo (not a worktree), should return .git dir
mainGitDir := resolveGitDir(repoPath)
expectedMainGitDir := filepath.Join(repoPath, ".git")
if mainGitDir != expectedMainGitDir {
t.Errorf("resolveGitDir for main repo = %s, want %s", mainGitDir, expectedMainGitDir)
}
}