Repository navigation
Expand file tree
/
Copy pathmodel.go
More file actions
1538 lines (1431 loc) · 46.1 KB
/
Copy pathmodel.go
File metadata and controls
1538 lines (1431 loc) · 46.1 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/exec"
"path"
"slices"
"sort"
"strconv"
"strings"
"sync"
"time"
tea "github.com/charmbracelet/bubbletea"
)
type sortField int
const (
sortDate sortField = iota
sortName
sortAheadBehind
sortFieldCount // number of sort fields; keep last
)
func (s sortField) String() string {
switch s {
case sortDate:
return "committerdate"
case sortName:
return "name"
case sortAheadBehind:
return "ahead/behind"
}
return "?"
}
type viewState int
const (
stateList viewState = iota
stateConfirm
stateForcePrompt
stateDeleting
stateResult
stateHelp
stateDiff
stateFilter // the list, with the filter line capturing keystrokes
stateAge // the list, with the merged-and-old prompt capturing digits
)
type deleteResult struct {
br branch // the branch this deletion was run for
done bool // the async deletion for this branch has completed
// worktreeRemoved records that the linked worktree holding br was removed
// to free the branch for deletion.
worktreeRemoved bool
localOK bool
localErr string
forceable bool // a safe (-d) delete failed and could be retried with -D
remoteTried bool
remoteOK bool
remoteErr string
// remoteSkipped records that the armed push was deliberately deferred
// because the local delete failed — the one piece of state not derivable
// from br, since arming is the caller's decision.
remoteSkipped bool
restored bool // undo recreated the local branch
}
// worktreePending reports whether a linked worktree still holds r's branch, so
// a force retry has to remove it first.
func (r deleteResult) worktreePending() bool { return r.br.worktree != "" && !r.worktreeRemoved }
// restorable reports whether undo can bring r's local branch back.
func (r deleteResult) restorable() bool {
return r.localOK && !r.restored && r.br.sha != ""
}
type model struct {
branches []branch // local rows and, once loaded, remoteOnly rows
cursor int
top int // index of first visible row (scroll window)
field sortField
ascending bool
force bool
nameW int // cached branch-name column width (see recomputeNameWidth)
filter string // active branch-name filter; "" shows every branch
ageInput string // digits typed into the merged-and-old prompt
showRemote bool // the list shows remoteOnly rows instead of local ones
// remoteLoaded records that the remote rows were asked for once; every
// later reload then keeps them current.
remoteLoaded bool
state viewState
results []deleteResult
history []deleteResult // earlier runs this session, for the exit summary
// abortArmed is set by a first ctrl+c while deletions run. Quitting then
// can strand a remote copy, so a second press is needed.
abortArmed bool
config repoConfig
remoteDefault string // resolved remote default branch, e.g. "origin/main"
remoteDefaultRef string // remoteDefault fully qualified
riskBase string // ref that branch.riskCommits is measured against ("" if unresolved)
riskBaseRef string // riskBase fully qualified, so a same-named tag cannot shadow it
// remoteTrunks holds the ref each <remote>/HEAD names. remoteDefault is only
// the first remote's trunk.
remoteTrunks map[string]bool
// baseMerged holds the local branches whose tip is an ancestor of riskBaseRef.
// Their riskCommits is 0 by definition, so one query here removes a `git
// cherry` subprocess per branch (see measureRisk).
baseMerged map[string]bool
// merging is set while a load's merge queries run in the background (see
// mergeCmd). Until they land, ✓ marks and risk counts are unknown, so the
// keys that select by them wait.
merging bool
loadGen int // bumped per branch load, so a late merge result for an old list is dropped
// selectOnMerge is set by a finished fetch: p selects the gone branches
// once the merge queries have counted what each one holds.
selectOnMerge bool
// measuring is set while d counts what the selected deletes cost (see
// confirmAfterRisk). The confirm screen opens when the counts land.
measuring bool
spinnerFrame int // animation frame for the deleting and diff-loading spinners (deletion counts derive from results)
diffBranch string // branch whose diff is shown in stateDiff
diffBase string // base ref the diff was computed against
diffRaw string // unified diff as git produced it; delta is re-run from it on resize
diffLines []string // display lines of the diff being viewed
diffStyled bool // lines came from delta and carry their own colors
diffTop int // scroll offset within diffLines
diffLoading bool // the diff (or its re-layout) is being made in the background
diffSeq int // bumped per diff request, so a slow answer for an old one is dropped
diffNote string // what the loading line says the load is doing
diffStart time.Time // when v was pressed; the loading line shows the time since
diffCancel context.CancelFunc // stops the running layout (see stopStyle)
bodyTop int // scroll offset within the confirm/force/result body (see page)
width, height int
err string
status string // transient info message (e.g. fetch results)
fetching bool // a background fetch --all --prune is in flight
switching bool // a background git switch is in flight
}
// fetchDoneMsg reports completion of an async `git fetch --all --prune`.
type fetchDoneMsg struct{ err error }
// fetchPruneCmd fetches all remotes and prunes deleted remote-tracking refs so
// that branches whose upstream is gone are detected. Run as a tea.Cmd to keep
// the UI responsive while the (network-bound) fetch runs.
func fetchPruneCmd() tea.Cmd {
return func() tea.Msg {
_, err := runGit("fetch", "--all", "--prune")
return fetchDoneMsg{err: err}
}
}
// switchDoneMsg reports completion of an async `git switch`, carrying the
// reloaded repo so the reads run off the update loop too.
type switchDoneMsg struct {
name string // the local branch now checked out
fromRemote bool // the switch created name from a remoteOnly row
err error // the switch itself failed; the repo is untouched
branches []branch
reads repoReads
loadErr error
}
// switchCmd checks out b and reloads the repo, off the update loop like every
// other mutation (see fetchPruneCmd). `git switch` resolves branch names only,
// so a same-named tag cannot shadow it (see branchRef). A remoteOnly row gets a
// new local branch that tracks it; the start point is the full ref, because a
// bare "origin/x" would lose to a tag of that name.
func switchCmd(b branch, withRemote bool) tea.Cmd {
args := []string{"switch", b.name}
msg := switchDoneMsg{name: b.name}
if b.remoteOnly {
// Name the local copy after the tracking ref, as git's own checkout
// does: a fetch refspec can give the remote's branch another name.
msg.name, msg.fromRemote = b.shownBranch(), true
args = []string{"switch", "-c", msg.name, "--track", b.ref()}
}
return func() tea.Msg {
if _, msg.err = runGit(args...); msg.err != nil {
return msg
}
msg.branches, msg.reads, msg.loadErr = loadRepo(withRemote)
return msg
}
}
// repoLoadedMsg carries a background reload (see reloadCmd).
type repoLoadedMsg struct {
branches []branch
reads repoReads
err error
}
// reloadCmd reloads the repo off the update loop. The first switch to the
// remote view uses it: reading every remote ref's commit can be slow on a big
// remote.
func reloadCmd(withRemote bool) tea.Cmd {
return func() tea.Msg {
b, r, err := loadRepo(withRemote)
return repoLoadedMsg{b, r, err}
}
}
// mergeInfo is the result of the merge queries (see queryMergeInfo).
type mergeInfo struct {
remoteMerged map[string]bool // remote-tracking names merged into the remote default
baseMerged map[string]bool // local branches whose tip is in the risk base
risk map[string]riskCount // commits not in the base, by ref, for gone branches
}
// mergeInfoMsg carries a load's merge queries; gen ties it to one load.
type mergeInfoMsg struct {
gen int
info mergeInfo
}
// riskMsg carries the risk counts d started; gen ties them to one load.
type riskMsg struct {
gen int
refs []string
counts []riskCount
}
// diffReadMsg carries the diff git produced; seq ties it to one request. The
// read and the layout are two steps so the loading line can give the size
// while delta works on it.
type diffReadMsg struct {
seq int
base string
raw string
delta bool // delta is on the PATH, so the layout step is the slow one
err error
}
// diffCmd reads b's diff off the update loop.
func diffCmd(seq int, b branch) tea.Cmd {
return func() tea.Msg {
msg := diffReadMsg{seq: seq}
msg.raw, msg.base, msg.err = loadDiffRef(b.ref(), b.name)
_, err := exec.LookPath("delta")
msg.delta = err == nil
return msg
}
}
// diffLoadedMsg carries a diff laid out in the background; seq ties it to one request.
type diffLoadedMsg struct {
seq int
lines []string
styled bool
}
// styleCmd lays m.diffRaw out off the update loop: a big diff through delta
// takes seconds. An earlier run still at work is stopped first.
func (m *model) styleCmd() tea.Cmd {
m.stopStyle()
ctx, cancel := context.WithCancel(context.Background())
m.diffCancel = cancel
seq, raw, width := m.diffSeq, m.diffRaw, m.width
return func() tea.Msg {
msg := diffLoadedMsg{seq: seq}
msg.lines, msg.styled = styleDiff(ctx, raw, width)
return msg
}
}
// stopStyle kills a running delta. Its answer would be dropped anyway, and on
// a big diff it holds a CPU core for seconds after the user has left.
func (m *model) stopStyle() {
if m.diffCancel != nil {
m.diffCancel()
m.diffCancel = nil
}
}
// restyleTickMsg fires a moment after a resize (see the WindowSizeMsg case).
type restyleTickMsg struct{ seq int }
// diffTickMsg advances the loading-line spinner. seq ties it to one request,
// so a quick v, q, v cannot leave two tick chains running.
type diffTickMsg struct{ seq int }
func diffTickCmd(seq int) tea.Cmd {
return tea.Tick(spinnerInterval, func(time.Time) tea.Msg { return diffTickMsg{seq} })
}
// branchDeletedMsg reports the outcome of one branch's async deletion; idx is
// its position in m.results.
type branchDeletedMsg struct {
idx int
res deleteResult
}
// spinnerTickMsg advances the deleting-view spinner animation.
type spinnerTickMsg struct{}
// spinnerFrames are the braille frames cycled while deletions are in flight
// or a diff loads, one per spinnerInterval.
var spinnerFrames = []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}
const spinnerInterval = 120 * time.Millisecond
// deleteBranchCmd wraps the deleteBranch worker as a tea.Cmd so deletions run off
// the update loop. It captures only a branch value (never the model), so each runs
// independently and concurrently under tea.Batch.
func deleteBranchCmd(idx int, b branch, force, wantRemote bool) tea.Cmd {
return func() tea.Msg {
return branchDeletedMsg{idx: idx, res: deleteBranch(b, force, wantRemote)}
}
}
// spinnerTickCmd schedules the next spinner frame.
func spinnerTickCmd() tea.Cmd {
return tea.Tick(spinnerInterval, func(time.Time) tea.Msg { return spinnerTickMsg{} })
}
// loadFirst runs the startup reads. The repo check runs beside them rather than
// ahead of them. It is here to give a clearer message than git's own, not to
// gate the work, and a serial subprocess start is most of what startup costs.
func loadFirst() ([]branch, repoReads, error) {
var repoErr error
checked := make(chan struct{})
go func() {
_, repoErr = runGit("rev-parse", "--is-inside-work-tree")
close(checked)
}()
branches, reads, err := loadRepo(false)
<-checked
if repoErr != nil {
return nil, reads, fmt.Errorf("not a git repository (or git is unavailable)")
}
return branches, reads, err
}
// initialModel loads the repo with every merge query answered before it
// returns. Script mode and the tests use it; the TUI uses startupModel.
func initialModel() (model, error) {
m, err := startupModel()
if err == nil {
m.applyMergeInfo(m.mergeQuery()())
}
return m, err
}
// startupModel is initialModel without the wait for the merge queries: the list
// paints after one round of git, and Init fills the ✓ and risk columns in.
func startupModel() (model, error) {
branches, reads, err := loadFirst()
if err != nil {
return model{}, err
}
m := model{field: sortDate, ascending: false, height: 24, width: 100}
loadSettings(&m) // a no-op unless main set settingsPath
m.installBranches(branches, reads)
return m, nil
}
// sortBranches re-sorts and keeps the cursor on the branch it was on.
func (m *model) sortBranches() {
current := ""
if b := m.cur(); b != nil {
current = b.name
}
m.sortRows()
m.focusBranch(current)
m.clampCursor()
}
func (m *model) sortRows() {
less := func(i, j int) bool {
a, b := m.branches[i], m.branches[j]
var r bool
switch m.field {
case sortName:
r = a.name < b.name
case sortAheadBehind:
r = (a.ahead - a.behind) < (b.ahead - b.behind)
default:
r = a.committed.Before(b.committed)
}
if !m.ascending {
return !r
}
return r
}
sort.SliceStable(m.branches, less)
}
// focusBranch puts the cursor on the named branch's view row. A filtered-out
// or unknown name leaves the cursor where it is. The cursor is a view
// position, not a branch index — this is the one place that mapping is done.
func (m *model) focusBranch(name string) {
for p, i := range m.viewIdx() {
if m.branches[i].name == name {
m.cursor = p
m.adjustScroll()
return
}
}
}
func (m *model) clampCursor() {
m.cursor = max(0, min(m.cursor, len(m.viewIdx())-1))
m.adjustScroll()
}
// scroll applies a mouse-wheel step (delta of -1 up / +1 down) to whichever
// scrollable view is active; other states ignore the wheel.
func (m *model) scroll(delta int) {
switch m.state {
case stateList, stateFilter, stateAge:
m.cursor += delta
m.clampCursor()
case stateDiff:
m.diffTop += delta * 3 // 3 lines per wheel notch, like a pager
m.clampDiff()
case stateConfirm, stateForcePrompt, stateDeleting, stateResult:
m.bodyTop += delta * 3
m.clampBody()
}
}
// visibleRows is how many branch rows fit: the header line and a blank above,
// a blank and the help line below, and one line each for a status and an error.
func (m model) visibleRows() int {
used := 4
if m.status != "" {
used++
}
if m.err != "" {
used++
}
return max(1, m.height-used)
}
// diffRows is how many diff lines fit between the title (2) and position (2) lines.
func (m model) diffRows() int { return max(1, m.height-4) }
func (m *model) adjustScroll() {
vis := m.visibleRows()
if m.cursor < m.top {
m.top = m.cursor
}
if m.cursor >= m.top+vis {
m.top = m.cursor - vis + 1
}
m.top = max(0, m.top)
}
// viewIdx returns the indices of the branches the list shows, in display
// order. The cursor and scroll offsets are positions in this view, not in
// m.branches: marks live on the branches, so hiding a row must not move them.
// The local and remote views are two filters over the one slice, for the same
// reason.
func (m model) viewIdx() []int {
idx := make([]int, 0, len(m.branches))
f := strings.ToLower(m.filter)
for i, b := range m.branches {
if !m.inView(b) {
continue
}
if f == "" || strings.Contains(strings.ToLower(b.name), f) {
idx = append(idx, i)
}
}
return idx
}
// inView reports whether b belongs to the view on screen, local or remote.
func (m model) inView(b branch) bool { return b.remoteOnly == m.showRemote }
func (m *model) cur() *branch {
if idx := m.viewIdx(); m.cursor >= 0 && m.cursor < len(idx) {
return &m.branches[idx[m.cursor]]
}
return nil
}
// selectedBranches returns the marked branches. Locked ones are dropped here
// too, so a mark that slipped past the keys still cannot reach a delete.
func (m model) selectedBranches() []branch {
var out []branch
for _, b := range m.branches {
if b.selected && !b.locked() {
out = append(out, b)
}
}
return out
}
// Init starts the merge queries startupModel left out.
func (m model) Init() tea.Cmd {
if !m.merging {
return nil
}
return m.mergeCmd()
}
// mergeCmd runs the merge queries for the loaded list off the update loop. Their
// risk counts can reach the network in a partial clone (see networkUse), and
// the screen must keep drawing while they wait.
func (m model) mergeCmd() tea.Cmd {
gen, query := m.loadGen, m.mergeQuery()
return func() tea.Msg { return mergeInfoMsg{gen: gen, info: query()} }
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width, m.height = msg.Width, msg.Height
m.adjustScroll()
if m.state == stateDiff && m.diffStyled {
// delta laid its columns out for the old width. A window drag sends
// dozens of sizes; wait for them to stop, so delta runs once, not
// once per size.
m.diffSeq++
seq := m.diffSeq
return m, tea.Tick(100*time.Millisecond, func(time.Time) tea.Msg { return restyleTickMsg{seq} })
}
return m, nil
case restyleTickMsg:
if msg.seq != m.diffSeq || m.state != stateDiff {
return m, nil // a later resize took over, or the user left
}
m.diffLoading = true
return m, m.styleCmd()
case mergeInfoMsg:
if msg.gen == m.loadGen {
m.applyMergeInfo(msg.info)
m.selectAfterFetch()
}
return m, nil
case riskMsg:
return m.landRisk(msg)
case diffReadMsg:
if msg.seq != m.diffSeq || m.state != stateDiff {
return m, nil // the user asked for another diff, or left
}
if msg.err != nil {
m.diffLoading = false
m.err = msg.err.Error()
m.state = stateList
return m, nil
}
m.diffBase, m.diffRaw = msg.base, msg.raw
if strings.TrimSpace(msg.raw) == "" {
m.diffLoading = false
return m, nil
}
m.diffNote = "styling " + groupDigits(strings.Count(msg.raw, "\n")) + " lines…"
if msg.delta {
m.diffNote = "delta is " + m.diffNote
}
return m, m.styleCmd()
case diffLoadedMsg:
if msg.seq != m.diffSeq || m.state != stateDiff {
return m, nil // the user asked for another diff, or left
}
m.diffLoading = false
m.stopStyle() // the run is over; this only frees its context
m.diffLines, m.diffStyled = msg.lines, msg.styled
m.clampDiff()
return m, nil
case diffTickMsg:
if msg.seq == m.diffSeq && m.state == stateDiff && m.diffLoading {
m.spinnerFrame++
return m, diffTickCmd(msg.seq)
}
return m, nil
case undoDoneMsg:
return m, m.applyUndo(msg)
case repoLoadedMsg:
if msg.err != nil {
m.err = msg.err.Error()
return m, nil
}
m.status = ""
return m, m.applyKeepMarks(msg.branches, msg.reads)
case fetchDoneMsg:
m.fetching = false
if msg.err != nil {
m.err = msg.err.Error()
m.status = ""
return m, nil
}
var cmd tea.Cmd
if branches, reads, err := loadRepo(m.remoteLoaded); err == nil {
// A fetch is non-destructive, so both the cursor (by name, in
// applyBranches) and the user's pending marks survive it.
cmd = m.applyKeepMarks(branches, reads)
}
m.err = ""
m.selectOnMerge = true
m.selectAfterFetch()
return m, cmd
case switchDoneMsg:
m.switching = false
if msg.err != nil {
// A refused switch (dirty worktree, held by another worktree)
// leaves the repo untouched; surface git's reason and stay put.
m.err = msg.err.Error()
m.status = ""
return m, nil
}
m.err = ""
m.status = "switched to " + msg.name
if msg.fromRemote {
m.showRemote = false // the new local branch is where the user is now
}
var cmd tea.Cmd
if msg.loadErr == nil {
// A switch deletes nothing, so pending marks survive it; carryMarks
// drops the ones now on the current branch.
cmd = m.applyKeepMarks(msg.branches, msg.reads)
}
m.focusBranch(msg.name)
return m, cmd
case branchDeletedMsg:
if msg.idx >= 0 && msg.idx < len(m.results) {
m.results[msg.idx] = msg.res
}
if m.deletesDone() < len(m.results) {
return m, nil
}
cmd := m.reloadBranches()
m.bodyTop, m.abortArmed = 0, false
if len(m.forceableFailures()) > 0 {
m.state = stateForcePrompt
} else {
m.state = stateResult
}
return m, cmd
case spinnerTickMsg:
if m.state == stateDeleting {
m.spinnerFrame++
return m, spinnerTickCmd()
}
return m, nil
case tea.MouseMsg:
// Handle the wheel ourselves so it scrolls the active view rather than
// the terminal translating it into arrow-key bursts that leak between views.
switch msg.Button {
case tea.MouseButtonWheelUp:
m.scroll(-1)
case tea.MouseButtonWheelDown:
m.scroll(1)
}
return m, nil
case tea.KeyMsg:
switch m.state {
case stateList:
return m.updateList(msg)
case stateFilter:
return m.updateFilter(msg)
case stateAge:
return m.updateAge(msg)
case stateConfirm:
return m.updateConfirm(msg)
case stateForcePrompt:
return m.updateForcePrompt(msg)
case stateDiff:
return m.updateDiff(msg)
case stateDeleting:
// Deletions are in flight; ignore input except an abort. Quitting
// drops pushes not yet started, which can leave a remote copy
// behind a deleted local branch, so the abort needs a second press.
if msg.String() == "ctrl+c" {
if m.abortArmed {
return m, tea.Quit
}
m.abortArmed = true
}
case stateResult:
switch msg.String() {
case "q", "ctrl+c":
return m, tea.Quit
case "enter", "esc":
m.state = stateList
case "u":
return m, m.undo()
default:
m.scrollKeys(msg.String())
}
case stateHelp:
if msg.String() == "ctrl+c" {
return m, tea.Quit
}
m.state = stateList
}
}
return m, nil
}
// updateFilter handles keys in stateFilter, where the filter line captures
// input: plain letters (q, j, a, …) type into the filter instead of firing
// their list actions.
func (m model) updateFilter(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
switch msg.String() {
case "ctrl+c":
return m, tea.Quit
case "enter":
m.state = stateList
case "esc":
m.filter = ""
m.state = stateList
case "backspace":
if r := []rune(m.filter); len(r) > 0 {
m.filter = string(r[:len(r)-1])
}
default:
if msg.Type == tea.KeyRunes {
m.filter += string(msg.Runes)
m.cursor = 0
}
}
m.clampCursor()
return m, nil
}
// updateAge handles the merged-and-old prompt. Only digits type into it.
func (m model) updateAge(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
switch msg.String() {
case "ctrl+c":
return m, tea.Quit
case "esc":
m.state = stateList
case "enter":
m.state = stateList
if days, err := strconv.Atoi(m.ageInput); err == nil {
m.err = ""
m.status = m.selectMergedOlder(days, time.Now())
}
case "backspace":
if n := len(m.ageInput); n > 0 {
m.ageInput = m.ageInput[:n-1]
}
default:
for _, r := range msg.Runes {
if r >= '0' && r <= '9' && len(m.ageInput) < 5 {
m.ageInput += string(r)
}
}
}
return m, nil
}
// waitForMerge reports whether a key must wait on the startup merge queries,
// and says so on the status line: selecting before they land would act on
// branches whose merge state is not yet known.
func (m *model) waitForMerge() bool {
if m.merging {
m.status = "still reading merge status — try again in a moment"
}
return m.merging
}
func (m model) updateList(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
switch msg.String() {
case "q", "ctrl+c":
return m, tea.Quit
case "up", "k":
m.cursor--
m.clampCursor()
case "down", "j":
m.cursor++
m.clampCursor()
case "g", "home":
m.cursor = 0
m.clampCursor()
case "G", "end":
m.cursor = len(m.branches) // clampCursor lands it on the last visible row
m.clampCursor()
case " ":
if b := m.cur(); b != nil && !b.locked() {
b.selected = !b.selected
}
case "r":
if b := m.cur(); b != nil {
if ok, why := b.remoteDelete(); ok {
b.deleteRemote = !b.deleteRemote
m.status = "" // a refusal shown for another row
} else if why != "" {
m.status = why
}
}
case "tab":
m.showRemote = !m.showRemote
m.cursor, m.top = 0, 0
if m.showRemote && !m.remoteLoaded {
m.remoteLoaded = true
m.status = "loading remote branches…"
return m, reloadCmd(true)
}
case "/":
m.state = stateFilter
case "m":
m.state, m.ageInput = stateAge, strconv.Itoa(m.config.staleDays)
case "esc":
// n already disarms everything; esc only lifts the filter.
m.filter = ""
m.clampCursor()
case "a":
// Select what the list shows: with a filter active, a marks only the
// matching branches, which is what makes filter-then-select useful.
for _, i := range m.viewIdx() {
if !m.branches[i].locked() {
m.branches[i].selected = true
}
}
case "n":
for i := range m.branches {
m.branches[i].selected = false
m.branches[i].deleteRemote = false
}
case "s":
m.field = (m.field + 1) % sortFieldCount
m.sortBranches()
saveSettings(m)
case "o":
m.ascending = !m.ascending
m.sortBranches()
saveSettings(m)
case "f":
m.force = !m.force
case "u":
return m, m.undo()
case "x":
// The same selection `p` makes after its fetch, for a repo whose
// gone marks are already known; no network round trip needed.
if !m.waitForMerge() {
m.err = ""
m.status = m.selectGone()
}
case "p":
if !m.fetching {
m.fetching = true
m.err = ""
m.status = "fetching --all --prune…"
return m, fetchPruneCmd()
}
case "v":
if b := m.cur(); b != nil {
m.err = ""
m.diffSeq++
m.diffBranch, m.diffBase = b.name, ""
m.diffRaw, m.diffLines, m.diffStyled = "", nil, false
m.diffTop, m.diffLoading = 0, true
m.diffNote, m.diffStart = "loading diff…", time.Now()
m.state = stateDiff
return m, tea.Batch(diffCmd(m.diffSeq, *b), diffTickCmd(m.diffSeq))
}
case "c":
if b := m.cur(); b != nil && !b.isCurrent && !m.switching && !m.fetching {
m.switching = true
m.err = ""
m.status = "switching to " + b.name + "…"
return m, switchCmd(*b, m.remoteLoaded)
}
case "?":
m.state = stateHelp
case "d", "enter":
if !m.measuring && len(m.selectedBranches()) > 0 && !m.waitForMerge() {
return m, m.confirmAfterRisk()
}
}
return m, nil
}
func (m model) updateConfirm(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
switch msg.String() {
case "y", "Y":
// Local only: never delete remotes on the same key that deletes locals.
if m.localSelectedCount() > 0 {
return m, m.startDeletions(false)
}
case "R":
// Local + remote — only meaningful when at least one remote is armed.
if m.armedRemoteCount() > 0 {
return m, m.startDeletions(true)
}
case "n", "N", "esc", "q":
m.state = stateList
case "ctrl+c":
return m, tea.Quit
default:
m.scrollKeys(msg.String())
}
return m, nil
}
// countArmedRemotes counts branches whose remote deletion is armed.
func countArmedRemotes(branches []branch) int {
n := 0
for _, b := range branches {
if b.remoteArmed() {
n++
}
}
return n
}
// armedRemoteCount counts selected branches whose remote deletion is armed.
func (m model) armedRemoteCount() int {
return countArmedRemotes(m.selectedBranches())
}
// localSelectedCount counts selected branches that have a local branch to delete.
func (m model) localSelectedCount() int {
n := 0
for _, b := range m.selectedBranches() {
if !b.remoteOnly {
n++
}
}
return n
}
// startDeletions kicks off the asynchronous deletion of the selected branches,
// pre-seeding results, entering stateDeleting, and returning a batch of one cmd
// per branch (which run concurrently) plus the spinner tick. Remote branches are
// pushed --delete only when includeRemote is set (see updateConfirm), so a
// remoteOnly row is left out of a local-only run.
func (m *model) startDeletions(includeRemote bool) tea.Cmd {
// Results carry the cost through to the force prompt. d has counted it
// already; this is for callers that start a run without d.
m.measureSelectedRisk()
var sel []branch
for _, b := range m.selectedBranches() {
if includeRemote || !b.remoteOnly {
sel = append(sel, b)
}
}
m.history = append(m.history, m.results...)
m.results = make([]deleteResult, len(sel))
m.spinnerFrame, m.abortArmed = 0, false
m.state, m.bodyTop = stateDeleting, 0
cmds := []tea.Cmd{spinnerTickCmd()}
for i, b := range sel {
m.results[i] = deleteResult{br: b}
wantRemote := includeRemote && b.remoteArmed()
cmds = append(cmds, deleteBranchCmd(i, b, m.force, wantRemote))
}
return tea.Batch(cmds...)
}
// deletesDone counts how many of the current run's deletions have completed.
func (m model) deletesDone() int {
n := 0
for _, r := range m.results {
if r.done {
n++
}
}
return n
}
// forceableFailures returns the results whose safe (-d) local delete was
// refused — the ones a force (-D) delete could clear.
func (m model) forceableFailures() []deleteResult {
var out []deleteResult
for _, r := range m.results {
if !r.localOK && r.forceable {
out = append(out, r)
}
}
return out
}
func (m model) updateForcePrompt(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
switch msg.String() {
case "y", "Y":
cmd := m.forceDeleteUnmerged()
m.state, m.bodyTop = stateResult, 0
return m, cmd
case "n", "N", "esc", "q", "enter":
m.state, m.bodyTop = stateResult, 0
case "ctrl+c":
return m, tea.Quit
default:
m.scrollKeys(msg.String())
}
return m, nil
}
func (m *model) clampDiff() {
m.diffTop = max(0, min(m.diffTop, len(m.diffLines)-m.diffRows()))