Repository navigation
Expand file tree
/
Copy pathmain_test.go
More file actions
3430 lines (3114 loc) · 117 KB
/
Copy pathmain_test.go
File metadata and controls
3430 lines (3114 loc) · 117 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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"testing"
"time"
"unicode/utf8"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
"github.com/muesli/termenv"
)
// key builds a rune KeyMsg (e.g. "y", "R") for driving update handlers in tests.
func key(s string) tea.KeyMsg { return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(s)} }
// deleteMsgs runs every cmd in a deletion batch concurrently — as the tea
// runtime does — and returns the branchDeletedMsgs they produce. The batch is
// one cmd per branch plus the spinner tick, which is dropped: it only animates,
// and waiting on its 120ms timer would slow every caller.
func deleteMsgs(t *testing.T, cmd tea.Cmd) []branchDeletedMsg {
t.Helper()
if cmd == nil {
t.Fatal("want a deletion batch cmd, got nil")
}
msg := cmd()
batch, ok := msg.(tea.BatchMsg)
if !ok {
t.Fatalf("want a tea.BatchMsg, got %T", msg)
}
msgs := make(chan tea.Msg, len(batch))
for _, c := range batch {
go func() { msgs <- c() }()
}
want := len(batch) - 1
timeout := time.NewTimer(30 * time.Second)
defer timeout.Stop()
var out []branchDeletedMsg
for len(out) < want {
select {
case msg := <-msgs:
if dm, ok := msg.(branchDeletedMsg); ok {
out = append(out, dm)
}
case <-timeout.C:
t.Fatalf("timed out after %d of %d deletions reported", len(out), want)
}
}
return out
}
// drainDeletions runs a deletion batch and feeds each result back through
// Update, so tests exercise the path users actually run: the completion logic
// (reload, then force-prompt vs result) decides the end state rather than the
// test asserting it into place.
func drainDeletions(t *testing.T, m model, cmd tea.Cmd) model {
t.Helper()
for _, dm := range deleteMsgs(t, cmd) {
nm, next := m.Update(dm)
m = settle(m, nm.(model), next)
}
return m
}
// startAndDrain deletes m's selected branches and drives the run to completion.
// Starting the batch inside the call keeps m's copy and startDeletions' writes
// to it from being operands of one expression, where Go does not define which
// happens first.
func startAndDrain(t *testing.T, m model, includeRemote bool) model {
t.Helper()
return drainDeletions(t, m, m.startDeletions(includeRemote))
}
// selectAll marks every branch but the current one, arming the remote delete too
// when arm is set.
func selectAll(m *model, arm bool) {
for i := range m.branches {
if m.branches[i].isCurrent {
continue
}
m.branches[i].selected = true
m.branches[i].deleteRemote = arm
}
}
// wantState asserts the state the machine landed in, with why it had to.
func wantState(t *testing.T, m model, want viewState, why string) {
t.Helper()
if m.state != want {
t.Fatalf("%s: state is %v, want %v", why, m.state, want)
}
}
// remoteHasBranch reports whether origin still has the named branch. ls-remote
// matches a short name against the end of every ref, so "old" also finds
// jb/old; pass a full ref such as refs/heads/old to match one branch only.
func remoteHasBranch(t *testing.T, dir, name string) bool {
t.Helper()
return git(t, dir, "ls-remote", "--heads", "origin", name) != ""
}
// git runs a git command in dir, failing the test on error, and returns its
// trimmed output for the callers that read it.
func git(t *testing.T, dir string, args ...string) string {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = dir
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
}
return strings.TrimSpace(string(out))
}
// initRepo creates an empty repository on the named initial branch with a commit
// identity configured. Callers add the commits, remotes and branches they need.
func initRepo(t *testing.T, branch string) string {
t.Helper()
return initRepoIn(t, t.TempDir(), branch)
}
// initRepoIn is initRepo in a folder of the caller's choice, which git makes.
func initRepoIn(t *testing.T, dir, branch string) string {
t.Helper()
git(t, filepath.Dir(dir), "init", "-q", "-b", branch, dir)
git(t, dir, "config", "user.email", "t@t.t")
git(t, dir, "config", "user.name", "t")
return dir
}
// addOrigin gives dir a bare origin remote and pushes trunk to it.
func addOrigin(t *testing.T, dir, trunk string) {
t.Helper()
remote := t.TempDir()
git(t, remote, "init", "--bare", "-q", "-b", trunk)
git(t, dir, "remote", "add", "origin", remote)
git(t, dir, "push", "-q", "-u", "origin", trunk)
}
// setupLocalRepo builds the branch shapes with no remote at all — a scratch
// project, or one that has simply never been pushed.
func setupLocalRepo(t *testing.T) string {
t.Helper()
tmp := initRepo(t, "main")
commitFile(t, tmp, "a", "a")
git(t, tmp, "branch", "feature/merged") // merged into main -> safe delete
git(t, tmp, "checkout", "-q", "-b", "feature/unmerged")
commitFile(t, tmp, "b", "b")
git(t, tmp, "checkout", "-q", "main")
return tmp
}
// setupRepo is setupLocalRepo plus an origin and a branch tracking it.
func setupRepo(t *testing.T) string {
t.Helper()
tmp := setupLocalRepo(t)
addOrigin(t, tmp, "main")
git(t, tmp, "checkout", "-q", "-b", "feature/tracked", "feature/unmerged")
git(t, tmp, "push", "-q", "-u", "origin", "feature/tracked")
git(t, tmp, "checkout", "-q", "main")
return tmp
}
// setupManyTracked builds a repo whose n feature branches each track origin and
// hold a commit of their own, so a prune of the lot fans out widely.
func setupManyTracked(t *testing.T, n int) string {
t.Helper()
tmp := initRepo(t, "main")
commitFile(t, tmp, "a", "a")
addOrigin(t, tmp, "main")
for i := 0; i < n; i++ {
name := fmt.Sprintf("feature/%d", i)
git(t, tmp, "checkout", "-q", "-b", name, "main")
commitFile(t, tmp, fmt.Sprintf("f%d", i), name)
}
git(t, tmp, "checkout", "-q", "main")
git(t, tmp, "push", "-q", "-u", "origin", "--all") // one connection, not n
return tmp
}
func chdir(t *testing.T, dir string) {
t.Helper()
old, _ := os.Getwd()
if err := os.Chdir(dir); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.Chdir(old) })
}
func branchNames(bs []branch) []string {
out := make([]string, len(bs))
for i, b := range bs {
out[i] = b.name
}
return out
}
func find(bs []branch, name string) *branch {
for i := range bs {
if bs[i].name == name {
return &bs[i]
}
}
return nil
}
func TestLoadAndSort(t *testing.T) {
repo := setupRepo(t)
chdir(t, repo)
m, err := initialModel()
if err != nil {
t.Fatalf("initialModel: %v", err)
}
if len(m.branches) != 4 {
t.Fatalf("want 4 branches, got %d", len(m.branches))
}
if b := find(m.branches, "main"); b == nil || !b.isCurrent {
t.Fatalf("main should be current: %+v", b)
}
if b := find(m.branches, "feature/tracked"); b == nil || b.upstream != "origin/feature/tracked" {
t.Fatalf("feature/tracked upstream wrong: %+v", b)
}
if b := find(m.branches, "feature/merged"); b == nil || b.upstream != "" {
t.Fatalf("feature/merged should have no upstream: %+v", b)
}
// default sort is committerdate descending; flip to name asc and verify order.
m.field = sortName
m.ascending = true
m.sortBranches()
got := branchNames(m.branches)
want := []string{"feature/merged", "feature/tracked", "feature/unmerged", "main"}
for i := range want {
if got[i] != want[i] {
t.Fatalf("name sort: got %v want %v", got, want)
}
}
// View should not panic and should render branch names.
out := m.listView()
if !strings.Contains(out, "feature/merged") {
t.Fatalf("listView missing branch name:\n%s", out)
}
}
func TestLoadDiff(t *testing.T) {
repo := setupRepo(t)
chdir(t, repo)
// feature/unmerged adds file "b" relative to main.
diff, _, err := loadDiff("feature/unmerged")
if err != nil {
t.Fatalf("loadDiff: %v", err)
}
if !strings.Contains(diff, "+++ b/b") || !strings.Contains(diff, "+b") {
t.Fatalf("diff should show added file b:\n%s", diff)
}
// main vs the default base should be empty.
if d, _, err := loadDiff("main"); err != nil || strings.TrimSpace(d) != "" {
t.Fatalf("main diff should be empty, err=%v out=%q", err, d)
}
}
func TestPruneGoneBranch(t *testing.T) {
repo := setupRepo(t)
chdir(t, repo)
// Delete the remote branch, then prune so the local tracking ref goes "gone".
git(t, repo, "push", "-q", "origin", "--delete", "feature/tracked")
git(t, repo, "fetch", "-q", "--all", "--prune")
branches, err := loadBranches()
if err != nil {
t.Fatalf("loadBranches: %v", err)
}
tb := find(branches, "feature/tracked")
if tb == nil || !tb.gone {
t.Fatalf("feature/tracked should be gone after remote delete + prune: %+v", tb)
}
// A gone branch must prune even in safe mode (-d would refuse it).
m, err := initialModel()
if err != nil {
t.Fatal(err)
}
find(m.branches, "feature/tracked").selected = true
m.force = false
m = startAndDrain(t, m, true)
if len(m.results) != 1 || !m.results[0].localOK {
t.Fatalf("gone branch should force-delete: %+v", m.results)
}
if find(m.branches, "feature/tracked") != nil {
t.Fatal("feature/tracked should be gone after prune")
}
}
func TestRemoteHelpers(t *testing.T) {
b := branch{name: "feature/tracked", upstream: "origin/feature/tracked"}
if b.remoteName() != "origin" {
t.Fatalf("remoteName: %s", b.remoteName())
}
if b.remoteBranch() != "feature/tracked" {
t.Fatalf("remoteBranch: %s", b.remoteBranch())
}
nb := branch{name: "local-only"}
if nb.remoteName() != "origin" || nb.remoteBranch() != "local-only" {
t.Fatalf("fallbacks wrong: %s %s", nb.remoteName(), nb.remoteBranch())
}
}
func TestSafeDeleteRefusesUnmerged(t *testing.T) {
repo := setupRepo(t)
chdir(t, repo)
m, err := initialModel()
if err != nil {
t.Fatal(err)
}
find(m.branches, "feature/merged").selected = true
find(m.branches, "feature/unmerged").selected = true
m.force = false // safe -d
m = startAndDrain(t, m, true)
var merged, unmerged *deleteResult
for i := range m.results {
switch m.results[i].br.name {
case "feature/merged":
merged = &m.results[i]
case "feature/unmerged":
unmerged = &m.results[i]
}
}
if merged == nil || !merged.localOK {
t.Fatalf("merged branch should delete safely: %+v", merged)
}
if unmerged == nil || unmerged.localOK {
t.Fatalf("unmerged branch should be refused by -d: %+v", unmerged)
}
// after reload, feature/merged gone, feature/unmerged still present
if find(m.branches, "feature/merged") != nil {
t.Fatal("feature/merged should be gone after delete")
}
if find(m.branches, "feature/unmerged") == nil {
t.Fatal("feature/unmerged should remain after refused -d")
}
}
func TestForceDeleteUnmergedRetry(t *testing.T) {
repo := setupRepo(t)
chdir(t, repo)
m, err := initialModel()
if err != nil {
t.Fatal(err)
}
find(m.branches, "feature/unmerged").selected = true
m.force = false // safe -d, which will be refused
m = startAndDrain(t, m, true)
// The refused unmerged branch should be surfaced for a force prompt, with
// its ahead count copied onto the result (0 here: it has no upstream).
wantState(t, m, stateForcePrompt, "a refused -d must raise the force prompt")
failures := m.forceableFailures()
if len(failures) != 1 || failures[0].br.name != "feature/unmerged" {
t.Fatalf("want feature/unmerged in forceableFailures, got %+v", failures)
}
if failures[0].br.ahead != 0 {
t.Fatalf("want ahead=0 captured (no upstream), got %+v", failures[0])
}
if find(m.branches, "feature/unmerged") == nil {
t.Fatal("feature/unmerged should still exist before force retry")
}
// Answering yes at the prompt retries with -D and clears the branch.
nm, _ := m.Update(key("y"))
m = nm.(model)
wantState(t, m, stateResult, "answering the prompt must land on the results screen")
if len(m.forceableFailures()) != 0 {
t.Fatalf("no failures should remain after force retry: %+v", m.results)
}
for _, r := range m.results {
if r.br.name == "feature/unmerged" && (!r.localOK || r.localErr != "") {
t.Fatalf("feature/unmerged should be deleted after force retry: %+v", r)
}
}
if find(m.branches, "feature/unmerged") != nil {
t.Fatal("feature/unmerged should be gone after force retry")
}
}
// A branch that deletes cleanly must NOT be flagged forceable, so the force
// prompt never appears for successful safe deletes.
func TestNoForcePromptForCleanDelete(t *testing.T) {
repo := setupRepo(t)
chdir(t, repo)
m, err := initialModel()
if err != nil {
t.Fatal(err)
}
find(m.branches, "feature/merged").selected = true
m.force = false
m = startAndDrain(t, m, true)
if len(m.results) != 1 || !m.results[0].localOK {
t.Fatalf("merged branch should delete cleanly: %+v", m.results)
}
if m.results[0].forceable {
t.Fatalf("a successful delete must not be forceable: %+v", m.results[0])
}
if got := m.forceableFailures(); len(got) != 0 {
t.Fatalf("no forceable failures expected, got %+v", got)
}
}
// A gone branch is deleted with -D outright, so a failed gone delete is not
// forceable (there is no stronger flag to escalate to).
func TestGoneFailureNotForceable(t *testing.T) {
repo := setupRepo(t)
chdir(t, repo)
git(t, repo, "push", "-q", "origin", "--delete", "feature/tracked")
git(t, repo, "fetch", "-q", "--all", "--prune")
m, err := initialModel()
if err != nil {
t.Fatal(err)
}
tb := find(m.branches, "feature/tracked")
if tb == nil || !tb.gone {
t.Fatalf("feature/tracked should be gone: %+v", tb)
}
tb.selected = true
m.force = false // gone branches still use -D
m = startAndDrain(t, m, true)
if len(m.results) != 1 || !m.results[0].localOK {
t.Fatalf("gone branch should force-delete: %+v", m.results)
}
if m.results[0].forceable {
t.Fatalf("a gone (-D) delete must not be marked forceable: %+v", m.results[0])
}
}
// forceDeleteUnmerged is a no-op when nothing is forceable: results and the
// branch list are left untouched.
func TestForceDeleteUnmergedNoop(t *testing.T) {
repo := setupRepo(t)
chdir(t, repo)
m, err := initialModel()
if err != nil {
t.Fatal(err)
}
find(m.branches, "feature/merged").selected = true
m.force = false
m = startAndDrain(t, m, true)
before := len(m.branches)
wantState(t, m, stateResult, "a clean delete must skip the force prompt")
m.forceDeleteUnmerged() // no forceable failures — should change nothing
if len(m.forceableFailures()) != 0 {
t.Fatalf("still no failures expected: %+v", m.results)
}
if len(m.branches) != before {
t.Fatalf("branch list should be unchanged, was %d now %d", before, len(m.branches))
}
if find(m.branches, "feature/unmerged") == nil {
t.Fatal("untouched unmerged branch should remain")
}
}
func TestForceDeleteAndRemote(t *testing.T) {
repo := setupRepo(t)
chdir(t, repo)
m, err := initialModel()
if err != nil {
t.Fatal(err)
}
tb := find(m.branches, "feature/tracked")
tb.selected = true
tb.deleteRemote = true
m.force = true // -D, also needed since tracked has its own commit
m = startAndDrain(t, m, true)
if len(m.results) != 1 {
t.Fatalf("want 1 result, got %d", len(m.results))
}
r := m.results[0]
if !r.localOK {
t.Fatalf("force local delete failed: %s", r.localErr)
}
if !r.remoteTried || !r.remoteOK {
t.Fatalf("remote delete failed: tried=%v err=%s", r.remoteTried, r.remoteErr)
}
if find(m.branches, "feature/tracked") != nil {
t.Fatal("feature/tracked should be gone locally")
}
}
// #1: the async worker deletes a branch and reports a completed result.
func TestDeleteBranchCmd(t *testing.T) {
repo := setupRepo(t)
chdir(t, repo)
// Local-only safe delete of the merged branch.
msg := deleteBranchCmd(2, branch{name: "feature/merged"}, false, false)()
dm, ok := msg.(branchDeletedMsg)
if !ok {
t.Fatalf("want branchDeletedMsg, got %T", msg)
}
if dm.idx != 2 {
t.Fatalf("idx: got %d want 2", dm.idx)
}
if !dm.res.done || !dm.res.localOK || dm.res.remoteTried {
t.Fatalf("expected done+localOK, no remote: %+v", dm.res)
}
// Force delete + remote push of the tracked branch.
tracked := branch{name: "feature/tracked", upstream: "origin/feature/tracked", ahead: 1}
dm2 := deleteBranchCmd(0, tracked, true, true)().(branchDeletedMsg)
if !dm2.res.localOK {
t.Fatalf("force local delete failed: %s", dm2.res.localErr)
}
if !dm2.res.remoteTried || !dm2.res.remoteOK {
t.Fatalf("remote delete failed: tried=%v err=%s", dm2.res.remoteTried, dm2.res.remoteErr)
}
if remoteHasBranch(t, repo, "feature/tracked") {
t.Fatal("remote feature/tracked should be deleted")
}
}
// runGit is where the cap lives, so callers cannot escape it however many pile
// in at once — and it still runs them in parallel rather than one at a time.
func TestGitCallsAreCapped(t *testing.T) {
chdir(t, setupLocalRepo(t))
const callers = 40
gitProcs.peak.Store(0)
var wg sync.WaitGroup
for i := 0; i < callers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
runGit("rev-parse", "--git-dir")
}()
}
wg.Wait()
peak := gitProcs.peak.Load()
if peak > maxLocalGit {
t.Fatalf("%d callers ran %d git processes at once, cap is %d", callers, peak, maxLocalGit)
}
if peak < 2 {
t.Fatalf("the cap serialized everything: peak %d", peak)
}
if n := gitProcs.inFlight.Load(); n != 0 {
t.Fatalf("every slot should be released, %d still held", n)
}
}
// Pruning a wide selection must not open a connection per branch: remotes
// throttle or refuse a burst, and a failed push is a branch deleted locally
// whose only other copy is still out there.
func TestWideDeleteStaysWithinCaps(t *testing.T) {
const n = 20
repo := setupManyTracked(t, n)
chdir(t, repo)
m, err := initialModel()
if err != nil {
t.Fatal(err)
}
selectAll(&m, true)
m.force = true
gitProcs.peak.Store(0)
netProcs.peak.Store(0)
m = startAndDrain(t, m, true)
// Literal bounds, not the constants under test: raising a cap must break this
// test rather than move the goalposts with it.
const fewConnections, fewProcesses = 4, 12
if maxRemotePush > fewConnections {
t.Fatalf("maxRemotePush is %d; a prune should never ask a remote for more than %d connections", maxRemotePush, fewConnections)
}
if got := netProcs.peak.Load(); got > fewConnections {
t.Fatalf("%d branches opened %d simultaneous connections to the remote", n, got)
}
if got := gitProcs.peak.Load(); got > fewProcesses {
t.Fatalf("%d branches ran %d git processes at once", n, got)
}
if netProcs.peak.Load() == 0 {
t.Fatal("no pushes were observed; the test is not measuring the remote path")
}
// The cap must not cost any of them their deletion.
for _, r := range m.results {
if !r.localOK || !r.remoteOK {
t.Fatalf("throttled delete did not complete: %+v", r)
}
}
if len(m.branches) != 1 {
t.Fatalf("only the current branch should remain, got %v", branchNames(m.branches))
}
}
// Risk is measured concurrently, one goroutine per branch writing its own slice
// element. Each branch must end up with its own count, not a neighbour's.
func TestConcurrentRiskMeasurementKeepsCountsWithBranch(t *testing.T) {
repo := initRepo(t, "main")
chdir(t, repo)
commitFile(t, repo, "a", "a")
// feature/i carries i commits of its own. Branching off one chain costs n
// commits for the n distinct counts; a fresh branch each time costs n(n+1)/2.
const n = 12
git(t, repo, "checkout", "-q", "-b", "chain", "main")
for i := 1; i <= n; i++ {
commitFile(t, repo, fmt.Sprintf("f%d", i), "x")
git(t, repo, "branch", fmt.Sprintf("feature/%d", i))
}
git(t, repo, "checkout", "-q", "main")
git(t, repo, "branch", "-D", "chain")
m, err := initialModel()
if err != nil {
t.Fatal(err)
}
selectAll(&m, false)
m.measureSelectedRisk()
for i := 1; i <= n; i++ {
name := fmt.Sprintf("feature/%d", i)
b := find(m.branches, name)
if b == nil || !b.riskMeasured {
t.Fatalf("%s was not measured: %+v", name, b)
}
if b.riskCommits != i {
t.Fatalf("%s should hold %d commits, measured %d", name, i, b.riskCommits)
}
}
}
// The live path only leaves stateDeleting once every branch has reported, and
// the branch list is not reloaded before then — a mid-run reload would renumber
// the results the outstanding messages are still indexing into.
func TestDeletingWaitsForEveryResult(t *testing.T) {
repo := setupRepo(t)
chdir(t, repo)
m, err := initialModel()
if err != nil {
t.Fatal(err)
}
find(m.branches, "feature/merged").selected = true // -d succeeds
find(m.branches, "feature/unmerged").selected = true // -d is refused
m.force = false
msgs := deleteMsgs(t, m.startDeletions(false))
if len(msgs) != 2 {
t.Fatalf("want 2 results, got %d", len(msgs))
}
for i, dm := range msgs {
nm, _ := m.Update(dm)
m = nm.(model)
if !m.results[dm.idx].done {
t.Fatalf("result %d should be marked done: %+v", dm.idx, m.results[dm.idx])
}
if i == len(msgs)-1 {
break
}
wantState(t, m, stateDeleting, "state must hold at stateDeleting until the last result")
if find(m.branches, "feature/merged") == nil {
t.Fatal("the branch list must not be reloaded mid-run")
}
}
wantState(t, m, stateForcePrompt, "the refused -d should raise the force prompt")
if find(m.branches, "feature/merged") != nil {
t.Fatal("the final result should have reloaded the branch list")
}
}
// A result carrying an index outside the current run must be dropped rather
// than panic: the async cmds outlive nothing here, but the bounds check is the
// only thing standing between a stale message and an out-of-range write.
func TestStrayDeleteResultIsIgnored(t *testing.T) {
repo := setupRepo(t)
chdir(t, repo)
m, err := initialModel()
if err != nil {
t.Fatal(err)
}
find(m.branches, "feature/merged").selected = true
m.startDeletions(false)
nm, _ := m.Update(branchDeletedMsg{idx: 7, res: deleteResult{done: true}})
m = nm.(model)
wantState(t, m, stateDeleting, "a stray result must not complete the run")
if m.deletesDone() != 0 {
t.Fatalf("a stray result must not be counted, got %d", m.deletesDone())
}
}
// Declining the force prompt leaves the refused branch — and its commits — in
// place. This is the escape hatch the -d/-D split exists for.
func TestForcePromptDeclineKeepsBranch(t *testing.T) {
repo := setupRepo(t)
chdir(t, repo)
m, err := initialModel()
if err != nil {
t.Fatal(err)
}
find(m.branches, "feature/unmerged").selected = true
m.force = false
m = startAndDrain(t, m, true)
wantState(t, m, stateForcePrompt, "a refused -d must raise the force prompt")
nm, _ := m.Update(key("n"))
m = nm.(model)
wantState(t, m, stateResult, "declining must land on the results screen")
if find(m.branches, "feature/unmerged") == nil {
t.Fatal("declining the force prompt must keep the branch")
}
if len(m.forceableFailures()) != 1 {
t.Fatalf("the refusal must still be reported: %+v", m.results)
}
}
// While deletions are in flight the keyboard is inert except for ctrl+c, so a
// stray keystroke cannot dismiss a run whose results have not landed yet.
func TestDeletingIgnoresKeysExceptCtrlC(t *testing.T) {
repo := setupRepo(t)
chdir(t, repo)
m, err := initialModel()
if err != nil {
t.Fatal(err)
}
m.state = stateDeleting
for _, k := range []tea.KeyMsg{key("q"), key("y"), key("d")} {
nm, cmd := m.Update(k)
if got := nm.(model).state; got != stateDeleting {
t.Fatalf("%v must not change state, got %v", k, got)
}
if cmd != nil {
t.Fatalf("%v must not issue a cmd", k)
}
}
// Quitting mid-run drops pushes not yet started, so the first ctrl+c only
// warns; the second quits.
nm, cmd := m.Update(tea.KeyMsg{Type: tea.KeyCtrlC})
m = nm.(model)
if cmd != nil || !m.abortArmed {
t.Fatal("the first ctrl+c must warn, not quit")
}
if o := stripANSI(m.deletingView()); !strings.Contains(o, "ctrl+c again to quit anyway") {
t.Fatalf("the warning must be on screen:\n%s", o)
}
_, cmd = m.Update(tea.KeyMsg{Type: tea.KeyCtrlC})
if cmd == nil {
t.Fatal("the second ctrl+c must abort")
}
if _, ok := cmd().(tea.QuitMsg); !ok {
t.Fatalf("ctrl+c should quit, got %T", cmd())
}
}
// The spinner re-arms itself only while deletions are running; once the run has
// landed the tick must die out rather than loop forever.
func TestSpinnerTickStopsAfterDeleting(t *testing.T) {
m := model{state: stateDeleting}
nm, cmd := m.Update(spinnerTickMsg{})
if nm.(model).spinnerFrame != 1 {
t.Fatalf("frame should advance, got %d", nm.(model).spinnerFrame)
}
if cmd == nil {
t.Fatal("the tick must re-arm while deleting")
}
m.state = stateResult
if _, cmd := m.Update(spinnerTickMsg{}); cmd != nil {
t.Fatal("the tick must not re-arm once the run has landed")
}
}
// #4: on the confirm screen, 'y' deletes locals only while 'R' also deletes the
// armed remote.
func TestConfirmRemoteConfirmationSplit(t *testing.T) {
// 'y' spares the remote.
t.Run("y_local_only", func(t *testing.T) {
repo := setupRepo(t)
chdir(t, repo)
m, err := initialModel()
if err != nil {
t.Fatal(err)
}
tb := find(m.branches, "feature/tracked")
tb.selected = true
tb.deleteRemote = true
m.force = true
m.state = stateConfirm
nm, cmd := m.updateConfirm(key("y"))
wantState(t, nm.(model), stateDeleting, "state should be stateDeleting")
m = drainDeletions(t, nm.(model), cmd)
wantState(t, m, stateResult, "a clean -D run should land on the results screen")
if !remoteHasBranch(t, repo, "feature/tracked") {
t.Fatal("'y' must not delete the remote branch")
}
})
// 'R' deletes local + remote.
t.Run("R_local_and_remote", func(t *testing.T) {
repo := setupRepo(t)
chdir(t, repo)
m, err := initialModel()
if err != nil {
t.Fatal(err)
}
tb := find(m.branches, "feature/tracked")
tb.selected = true
tb.deleteRemote = true
m.force = true
m.state = stateConfirm
nm, cmd := m.updateConfirm(key("R"))
wantState(t, nm.(model), stateDeleting, "state should be stateDeleting")
m = drainDeletions(t, nm.(model), cmd)
wantState(t, m, stateResult, "a clean -D run should land on the results screen")
if remoteHasBranch(t, repo, "feature/tracked") {
t.Fatal("'R' should delete the remote branch")
}
})
}
// #5: refreshMergeInfo flags branches whose upstream is merged into the remote
// default, and leaves unmerged / upstream-less branches unflagged.
func TestRemoteMergedIndicator(t *testing.T) {
repo := setupRepo(t)
chdir(t, repo)
// A remote branch identical to origin/main is merged into it.
git(t, repo, "branch", "feature/remote-merged", "main")
git(t, repo, "push", "-q", "-u", "origin", "feature/remote-merged")
m, err := initialModel()
if err != nil {
t.Fatal(err)
}
if m.remoteDefault == "" {
t.Fatal("remoteDefault should resolve to origin/main")
}
if b := find(m.branches, "feature/remote-merged"); b == nil || !b.remoteMerged {
t.Fatalf("feature/remote-merged should be remoteMerged: %+v", b)
}
// feature/tracked carries its own commit → not merged into origin/main.
if b := find(m.branches, "feature/tracked"); b == nil || b.remoteMerged {
t.Fatalf("feature/tracked should not be remoteMerged: %+v", b)
}
// feature/merged has no upstream → never remoteMerged.
if b := find(m.branches, "feature/merged"); b == nil || b.remoteMerged {
t.Fatalf("upstream-less branch must not be remoteMerged: %+v", b)
}
}
// Scrolling the diff view with the wheel must not disturb the list's cursor or
// scroll position (regression: over-scrolling the diff jumped the list to the end).
func TestWheelScrollDoesNotLeakBetweenViews(t *testing.T) {
repo := setupRepo(t)
chdir(t, repo)
m, err := initialModel()
if err != nil {
t.Fatal(err)
}
// Park the list cursor at a non-zero row.
m.cursor = 2
m.clampCursor()
savedCursor, savedTop := m.cursor, m.top
// Enter the diff with scrollable content and scroll it hard past the bottom.
m.state = stateDiff
m.diffLines = make([]string, 200)
m.diffTop = 0
for range 500 {
m.scroll(1)
}
if m.diffTop == 0 {
t.Fatal("diff should have scrolled down")
}
if m.cursor != savedCursor || m.top != savedTop {
t.Fatalf("diff scroll leaked into list: cursor %d->%d, top %d->%d",
savedCursor, m.cursor, savedTop, m.top)
}
// Back in the list, the wheel drives the cursor (routed via Update/MouseMsg).
m.state = stateList
nm, _ := m.Update(tea.MouseMsg{Button: tea.MouseButtonWheelDown, Action: tea.MouseActionPress})
if got := nm.(model).cursor; got != savedCursor+1 {
t.Fatalf("list wheel should move cursor to %d, got %d", savedCursor+1, got)
}
}
var ansiRe = regexp.MustCompile("\x1b\\[[0-9;]*m")
func stripANSI(s string) string { return ansiRe.ReplaceAllString(s, "") }
// truncate measures terminal cells, so multibyte text must never be sliced
// mid-rune (which emitted invalid UTF-8) and wide characters must not overflow.
func TestTruncateDisplayWidth(t *testing.T) {
for _, w := range []int{1, 4, 9, 10, 11, 40} {
for _, s := range []string{"日本語のコミットです", "feat: 🚀 ship it", "feature/café", "plain-ascii"} {
got := truncate(s, w)
if !utf8.ValidString(got) {
t.Fatalf("truncate(%q, %d) = %q: invalid UTF-8", s, w, got)
}
if cells := ansi.StringWidth(got); cells > w {
t.Fatalf("truncate(%q, %d) = %q: %d cells, over budget", s, w, got, cells)
}
}
}
if got := truncate("plain-ascii", 40); got != "plain-ascii" {
t.Fatalf("short strings must pass through unchanged, got %q", got)
}
}
// pad must align on display cells; wide glyphs otherwise push later columns.
func TestPadDisplayWidth(t *testing.T) {
for _, s := range []string{"日本語", "ab", "🚀", ""} {
if got := ansi.StringWidth(pad(s, 10)); got != 10 {
t.Fatalf("pad(%q, 10) is %d cells, want 10", s, got)
}
}
}
// Every track value must occupy the same column width, or the columns after it
// shift on gone rows (regression: "gone" was 8 wide where others were 10).
func TestTrackColumnAlignment(t *testing.T) {
m := model{width: 120}
rows := []branch{
{name: "aaa", upstream: "origin/aaa", ahead: 2, behind: 1},
{name: "bbb", upstream: "origin/bbb", gone: true},
{name: "ccc"},
{name: "ddd", upstream: "origin/ddd", remoteMerged: true},
}
want := -1
for _, br := range rows {
plain := stripANSI(m.renderRow(br, 10, false))
at := strings.Index(plain, "0001-Jan-01") // the column right after track
if at < 0 {
t.Fatalf("date column missing for %q: %q", br.name, plain)
}
// Compare display cells, not the byte offset: the arrows in the track
// column are multibyte, which is the whole point of this alignment.
cells := ansi.StringWidth(plain[:at])
if want == -1 {
want = cells
} else if cells != want {
t.Fatalf("branch %q: date column at cell %d, want %d (track width differs)\n%q",
br.name, cells, want, plain)
}
}
}
// The core safety fix: a gone branch holding commits that are not in the base
// is force-deleted with -D, so it must be measured, warned about on the confirm
// screen, and left out of `p`'s auto-selection.
func TestGoneBranchWithUnpushedCommitsIsGuarded(t *testing.T) {
repo := setupRepo(t)
chdir(t, repo)
// feature/tracked is pushed; add a commit that never reaches the remote,
// then delete the remote branch and prune so it goes "gone".
git(t, repo, "checkout", "-q", "feature/tracked")
commitFile(t, repo, "unpushed", "irreplaceable")
git(t, repo, "checkout", "-q", "main")
git(t, repo, "push", "-q", "origin", "--delete", "feature/tracked")
git(t, repo, "fetch", "-q", "--all", "--prune")
m, err := initialModel()
if err != nil {
t.Fatal(err)