diff --git a/README.md b/README.md index c9591f2..779955e 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ checklist), so the UI stays responsive while remote pushes complete. `ctrl+c` th second press: quitting mid-run can leave a remote branch behind a deleted local one. On the results screen, `u` recreates the deleted local branches at their old commits, with -their upstream config. `enter` returns to the list, and `q` quits. When you quit, git_pruner +their upstream config. `d` waits until a running undo has finished. `enter` returns to the list, and `q` quits. When you quit, git_pruner prints a restore command for every branch it deleted this session, so the way back stays in your scrollback: @@ -86,6 +86,12 @@ git_pruner: to restore a deleted branch, run: git push origin 3e2210a…:refs/heads/feature/foo ``` +The `git push` line names the commit the remote branch was at, which is not the local tip when +the local branch was behind it. + +If a fetch, a checkout or an undo finishes while the confirmation screen is open, the screen +closes and the status line says the list changed. Press `d` to review the new list. + In the diff view: `↑`/`↓` scroll, `space`/`ctrl+d` page down, `ctrl+u`/`pgup` page up, `g`/`G` jump to top/bottom, and `q`/`esc`/`v` return to the list. @@ -178,7 +184,10 @@ claiming the work is unrecoverable. with `git switch -c feat origin/main` tracks `main`. So `r` refuses when the upstream is the default branch or protected, when the upstream is a local branch (`--track main`), and when it is not a branch at all (a pull request head such as `refs/pull/1/head`). None of these - has a remote branch to delete. Because this affects shared history, remote deletion + has a remote branch to delete. The push carries a lease (`--force-with-lease`) on the commit + your last fetch saw, so the remote refuses the delete when a teammate pushed to the branch + after that fetch; fetch with `p` and review it again. A remote branch that someone else + already deleted counts as deleted. Because this affects shared history, remote deletion requires the explicit `R` key on the confirmation screen — plain `y` deletes locals only. The confirmation screen also shows, per branch, whether the upstream is merged into the remote default (`✓ merged` / `⚠ not merged`) to help you judge whether the remote is safe to delete. @@ -266,7 +275,7 @@ default branch. It prints restore commands for what it deleted, and exits 1 if a ## Network calls -`git fetch` and `git push --delete` run with `GIT_TERMINAL_PROMPT=0` and without a terminal, and +`git fetch`, `git push --delete` and `git ls-remote` (the check after a refused lease) run with `GIT_TERMINAL_PROMPT=0` and without a terminal, and stop after 60 seconds. A remote that asks for a password or does not answer fails with a message, instead of freezing the screen. Use a credential helper or an ssh agent for remotes that need a login. diff --git a/bugs.md b/bugs.md index 26708f1..11a6706 100644 --- a/bugs.md +++ b/bugs.md @@ -20,3 +20,11 @@ - [x] Partial clones: `git switch` could show an ssh prompt over the screen - [x] Partial clones: commit counts ran 3 at a time (the push cap), not 8 - [x] Commit counts ran inside the screen's update loop, so a slow partial clone froze the screen + +### November 11 +- [x] A remote delete removed commits a teammate pushed after the last fetch +- [x] A fetch, checkout or undo that landed on the confirm screen removed its warnings and added branches +- [x] The remote result and the `git push` restore command named the local tip, not the remote's commit +- [x] `y` on the force prompt ran deletes and pushes inside the screen's update loop +- [x] An undo followed by a fast new delete crashed with an index out of range +- [x] `m` during the load selected nothing instead of waiting for the merge status diff --git a/cli.go b/cli.go index e5e1155..0a96e8a 100644 --- a/cli.go +++ b/cli.go @@ -108,8 +108,8 @@ func restoreSummary(results []deleteResult) string { if r.restorable() { lines = append(lines, fmt.Sprintf(" git branch %s %s", r.br.name, r.br.sha)) } - if r.remoteOK && r.br.sha != "" { - lines = append(lines, fmt.Sprintf(" git push %s %s:refs/heads/%s", r.br.remoteName(), r.br.sha, r.br.remoteBranch())) + if r.remoteOK && r.br.upSha != "" { + lines = append(lines, fmt.Sprintf(" git push %s %s:refs/heads/%s", r.br.remoteName(), r.br.upSha, r.br.remoteBranch())) } } if len(lines) == 0 { diff --git a/docs/test-coverage-gaps.md b/docs/test-coverage-gaps.md index 1086a46..cf8c1f5 100644 --- a/docs/test-coverage-gaps.md +++ b/docs/test-coverage-gaps.md @@ -363,10 +363,23 @@ confirm screen shows a failed count as clean, and fails the test. ### Found while fixing **34. A forced retry runs deletes and pushes inside `Update`** — `model.go` -`forceDeleteUnmerged` — **TODO**. `y` on the force prompt runs `git branch -D` and +`forceDeleteUnmerged` — **DONE** (2026-11-11). `y` on the force prompt ran `git branch -D` and `pushRemoteDelete` for each refused branch inside `Update`. A push can wait out the 60 s -timeout, so a slow remote freezes the screen, as in 32. Fix: run the retry as a `tea.Cmd`, like -`startDeletions`, and apply the results from a message. +timeout, so a slow remote froze the screen, as in 32. Fixed: the retry runs as one +`forceDeleteCmd` per branch on the deleting screen, and `branchDeletedMsg` lands each result. +*(`TestForceRetryRunsOffTheUpdateLoop`)* + +### 2026-11-11 analysis + +Six fixes from `~/dev/docs/git_pruner/2026-11-11-analysis-findings.md`, each with a test in +`review_test.go` that fails against the old code: + +- A remote delete carries `--force-with-lease` on the tracking ref's commit (`branch.upSha`). + *(`TestRemoteDeleteRefusesMovedBranch`)* +- The remote result and restore command use `upSha`. *(`TestRemoteRestoreNamesRemoteCommit`)* +- A reload closes the confirm screen. *(`TestReloadClosesConfirmScreen`)* +- `d` and `u` wait while an undo runs. *(`TestUndoHoldsNewDeleteRun`)* +- `m` waits for the merge status. *(`TestMergedOldWaitsForMergeStatus`)* ## Ref handling — the rule this work established @@ -391,7 +404,7 @@ open in `localDefaultBranch`. It has been deleted. ## Status -Tiers 1 to 5 are done. One new item, 34, is open. +Tiers 1 to 5 and item 34 are done. The suite has **99 tests** (81 in `main_test.go`, 18 in `features_test.go`), passing under `-race`, with `gofmt` and `go vet` clean (2026-10-10). Tiers 1 to 3 ended at 43; Tier 4 added 4; diff --git a/git.go b/git.go index 6750184..9104922 100644 --- a/git.go +++ b/git.go @@ -30,6 +30,10 @@ type branch struct { upstream string // e.g. "origin/feature"; "" when no upstream is configured upRemote string // branch..remote, kept so undo can restore tracking upMerge string // branch..merge, e.g. "refs/heads/feature" + // upSha is the commit the tracking ref was at when the list was read: what a + // remote delete expects to remove, and what its restore command pushes back. + // The local tip is not it when the branch is behind or has diverged. + upSha string ahead int behind int gone bool // upstream was configured but no longer exists @@ -116,6 +120,14 @@ func (b branch) remoteName() string { // The remote's name can hold a slash, so it is trimmed whole. func (b branch) shownBranch() string { return strings.TrimPrefix(b.upstream, b.remoteName()+"/") } +// remoteHash is upSha shortened for display. +func (b branch) remoteHash() string { + if b.upSha == b.sha { + return b.hash + } + return b.upSha[:min(7, len(b.upSha))] +} + func (b branch) remoteBranch() string { if s, ok := strings.CutPrefix(b.upMerge, "refs/heads/"); ok { return s @@ -184,7 +196,7 @@ func networkUse(args []string) gitNet { } lazy := lazyFetch.Load() switch args[0] { - case "push", "fetch": + case "push", "fetch", "ls-remote": return gitNet{connects: true, timeout: true, noTTY: true} case "cherry", "diff": // Both read file contents, which a partial clone fetches on demand. @@ -408,6 +420,7 @@ type remoteRefs struct { names []string // remote names, "origin" first exists map[string]bool // fully qualified ref -> present symref map[string]string // fully qualified symbolic ref -> the ref it names + sha map[string]string // fully qualified ref -> its commit rows []branch // every non-symbolic remote branch; only when asked for } @@ -417,10 +430,12 @@ type remoteRefs struct { // withRows also reads each ref's commit for the remote view. That costs a commit // read per ref, so it is only paid once the user has opened that view. func loadRemoteRefs(withRows bool) remoteRefs { - rr := remoteRefs{exists: map[string]bool{}, symref: map[string]string{}} - format := "%(symref)%00%(refname)" + rr := remoteRefs{exists: map[string]bool{}, symref: map[string]string{}, sha: map[string]string{}} + // The full commit ID is free: it sits in the ref itself. The short one is + // not, since git must search the object store for a unique prefix. + format, shaAt := "%(symref)%00%(refname)%00%(objectname)", 2 if withRows { - format = "%(symref)%00" + commitFormat + format, shaAt = "%(symref)%00"+commitFormat, 3 } out, err := runGit("for-each-ref", "--format="+format, "refs/remotes") if err != nil { @@ -434,6 +449,9 @@ func loadRemoteRefs(withRows bool) remoteRefs { } ref, target := f[1], f[0] rr.exists[ref] = true + if len(f) > shaAt { + rr.sha[ref] = f[shaAt] + } if target != "" { rr.symref[ref] = target } else if withRows && len(f) >= 7 { @@ -442,6 +460,7 @@ func loadRemoteRefs(withRows bool) remoteRefs { // The row is its own upstream, which lets the merge query and the // push --delete path treat it like a local branch's remote copy. b.upstream = b.name + b.upSha = b.sha rr.rows = append(rr.rows, b) } // The first segment after the namespace is the remote's name. @@ -728,6 +747,10 @@ func loadRepo(withRemote bool) ([]branch, repoReads, error) { b := &branches[i] b.mainWorktree = mainWT != "" && b.worktree == mainWT b.heldBy = held[b.ref()] + // An upstream that is a local branch finds nothing here; r refuses it. + if b.upstream != "" { + b.upSha = reads.remotes.sha["refs/remotes/"+b.upstream] + } } return branches, reads, err } @@ -933,13 +956,65 @@ func removeWorktree(res *deleteResult) bool { func pushRemoteDelete(res *deleteResult) { res.remoteSkipped = false res.remoteTried = true + if res.br.upSha == "" { + // A gone upstream has no tracking ref. A delete with no expected commit + // would remove whatever someone pushed there since. + res.remoteErr = "no tracking ref says what the remote branch holds — fetch (p), then try again" + return + } // Qualify the remote branch: a remote carrying both a branch and a tag of that // name rejects a bare refspec as matching more than one ref, deleting nothing. - if _, err := runGit("push", res.br.remoteName(), "--delete", branchRef(res.br.remoteBranch())); err != nil { + ref := branchRef(res.br.remoteBranch()) + // The lease makes the remote refuse when its branch is not at the commit the + // user reviewed. The ✓ and the commit count describe the last fetch; a plain + // --delete would also remove what a teammate pushed after it. + lease := "--force-with-lease=" + ref + ":" + res.br.upSha + _, err := runGit("push", lease, res.br.remoteName(), "--delete", ref) + switch { + case err == nil: + res.remoteOK = true + case !strings.Contains(err.Error(), "stale info"): res.remoteErr = err.Error() - } else { + case remoteBranchAbsent(res.br.remoteName(), ref): + // Someone else deleted the branch first, which is the outcome the user + // asked for. A push --delete drops the tracking ref; do the same here, or + // the branch comes back as a remote-only row until the next fetch. res.remoteOK = true + runGit("update-ref", "-d", "refs/remotes/"+res.br.upstream, res.br.upSha) + default: + res.remoteErr = "the remote branch moved since the last fetch — fetch (p), then review it again" + } +} + +// remoteBranchAbsent asks the remote whether ref is gone from it. A lease +// refusal alone cannot tell a deleted branch from a moved one. +func remoteBranchAbsent(remote, ref string) bool { + out, err := runGit("ls-remote", remote, ref) + return err == nil && strings.TrimSpace(out) == "" +} + +// forceDelete retries with -D a delete that -d refused, and runs the remote +// delete that was waiting on it. It is the worker forceDeleteCmd runs off the +// update loop. The result is never forceable again: a second prompt could only +// offer the same -D. +func forceDelete(r deleteResult) deleteResult { + r.done, r.forceable = true, false + // deleteBranch kept the worktree while -d was going to refuse the branch; + // the user has now agreed to the delete, so free it. + if r.worktreePending() && !removeWorktree(&r) { + return r + } + if _, err := runGit("branch", "-D", r.br.name); err != nil { + r.localErr = err.Error() + return r + } + r.localOK, r.localErr = true, "" + // The armed remote delete was deferred while the local branch survived; + // now that it is gone, honour what the user confirmed. + if r.remoteSkipped { + pushRemoteDelete(&r) } + return r } // restoreBranch recreates a deleted local branch at its old commit and puts its diff --git a/main_test.go b/main_test.go index 4c0204d..99144a4 100644 --- a/main_test.go +++ b/main_test.go @@ -384,8 +384,8 @@ func TestForceDeleteUnmergedRetry(t *testing.T) { } // Answering yes at the prompt retries with -D and clears the branch. - nm, _ := m.Update(key("y")) - m = nm.(model) + nm, cmd := m.Update(key("y")) + m = drainDeletions(t, nm.(model), cmd) 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) @@ -530,7 +530,8 @@ func TestDeleteBranchCmd(t *testing.T) { } // Force delete + remote push of the tracked branch. - tracked := branch{name: "feature/tracked", upstream: "origin/feature/tracked", ahead: 1} + tracked := branch{name: "feature/tracked", upstream: "origin/feature/tracked", ahead: 1, + upSha: git(t, repo, "rev-parse", "refs/remotes/origin/feature/tracked")} dm2 := deleteBranchCmd(0, tracked, true, true)().(branchDeletedMsg) if !dm2.res.localOK { t.Fatalf("force local delete failed: %s", dm2.res.localErr) @@ -1376,8 +1377,8 @@ func TestRemoteDeleteDeferredUntilLocalSucceeds(t *testing.T) { // The force retry clears the branch, so the arming is finally honoured. wantState(t, m, stateForcePrompt, "a refused -d must raise the force prompt") - nm, _ := m.Update(key("y")) - m = nm.(model) + nm, cmd := m.Update(key("y")) + m = drainDeletions(t, nm.(model), cmd) r = m.results[0] if !r.localOK || !r.remoteTried || !r.remoteOK || r.remoteSkipped { t.Fatalf("force retry should complete both deletes: %+v", r) @@ -3033,7 +3034,8 @@ func TestUnmergedWorktreeKeptUntilForce(t *testing.T) { t.Fatalf("the force prompt must name the worktree it removes:\n%s", strings.Join(body, "\n")) } - m = press(t, m, key("y")) + nm, cmd := m.Update(key("y")) + m = drainDeletions(t, nm.(model), cmd) if r := result(t, m, "feature/unmerged"); !r.localOK || !r.worktreeRemoved { t.Fatalf("the force retry should remove the worktree and the branch: %+v", r) } diff --git a/model.go b/model.go index fd25bc4..cbe4b33 100644 --- a/model.go +++ b/model.go @@ -147,6 +147,7 @@ type model struct { 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 + undoing bool // a background undo is in flight (see confirmAfterRisk) } // fetchDoneMsg reports completion of an async `git fetch --all --prune`. @@ -321,6 +322,11 @@ func deleteBranchCmd(idx int, b branch, force, wantRemote bool) tea.Cmd { } } +// forceDeleteCmd is deleteBranchCmd for the force retry of one refused result. +func forceDeleteCmd(idx int, r deleteResult) tea.Cmd { + return func() tea.Msg { return branchDeletedMsg{idx: idx, res: forceDelete(r)} } +} + // spinnerTickCmd schedules the next spinner frame. func spinnerTickCmd() tea.Cmd { return tea.Tick(spinnerInterval, func(time.Time) tea.Msg { return spinnerTickMsg{} }) @@ -807,7 +813,10 @@ func (m model) updateList(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case "/": m.state = stateFilter case "m": - m.state, m.ageInput = stateAge, strconv.Itoa(m.config.staleDays) + // Before the merge queries land, no branch reads as merged. + if !m.waitForMerge() { + m.state, m.ageInput = stateAge, strconv.Itoa(m.config.staleDays) + } case "esc": // n already disarms everything; esc only lifts the filter. m.filter = "" @@ -945,10 +954,7 @@ func (m *model) startDeletions(includeRemote bool) tea.Cmd { } 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()} + cmds := []tea.Cmd{m.showDeleting()} for i, b := range sel { m.results[i] = deleteResult{br: b} wantRemote := includeRemote && b.remoteArmed() @@ -983,9 +989,7 @@ func (m model) forceableFailures() []deleteResult { 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 + return m, m.forceDeleteUnmerged() case "n", "N", "esc", "q", "enter": m.state, m.bodyTop = stateResult, 0 case "ctrl+c": @@ -1063,6 +1067,12 @@ func (m *model) applyBranches(branches []branch, reads repoReads) tea.Cmd { // applyKeepMarks is applyBranches for a reload that deleted nothing, so the // user's pending marks carry over by ref. func (m *model) applyKeepMarks(branches []branch, reads repoReads) tea.Cmd { + if m.state == stateConfirm { + // The screen described the old list. The new one has no commit counts yet, + // and a fetch selects more branches, so y would answer a changed question. + m.state = stateList + m.status = "the branch list changed — check the selection and press d again" + } return m.applyBranches(carryMarks(m.branches, branches), reads) } @@ -1333,6 +1343,13 @@ func (m *model) measureSelectedRisk() { // update loop. Their riskMsg comes back here: the selection may have grown // while they ran. func (m *model) confirmAfterRisk() tea.Cmd { + if m.undoing { + // The undo's answer names rows of m.results by index. Both ways into the + // confirm screen pass here, so no new run can replace that list first. + m.measuring = false + m.status = "still restoring — try again in a moment" + return nil + } refs := m.riskTodo() if len(refs) == 0 { m.measuring = false @@ -1363,32 +1380,31 @@ func (m model) landRisk(msg riskMsg) (tea.Model, tea.Cmd) { } // forceDeleteUnmerged re-runs the deletions that a safe (-d) delete refused, -// this time with -D. It updates the matching result in place so the results -// screen reflects the retry outcome. +// this time with -D. It runs them like the first pass, as cmds on the deleting +// screen: each retry can push, and a push can wait out netTimeout. The results +// land in place through branchDeletedMsg, which then opens the results screen. func (m *model) forceDeleteUnmerged() tea.Cmd { - for i := range m.results { - r := &m.results[i] + var cmds []tea.Cmd + for i, r := range m.results { if r.localOK || !r.forceable { continue } - // deleteBranch kept the worktree while -d was going to refuse the - // branch; the user has now agreed to the delete, so free it. - if r.worktreePending() && !removeWorktree(r) { - continue - } - if _, err := runGit("branch", "-D", r.br.name); err != nil { - r.localErr = err.Error() - continue - } - r.localOK = true - r.localErr = "" - // The armed remote delete was deferred while the local branch survived; - // now that it is gone, honour what the user confirmed. - if r.remoteSkipped { - pushRemoteDelete(r) - } + m.results[i].done = false + cmds = append(cmds, forceDeleteCmd(i, r)) + } + if len(cmds) == 0 { + m.state, m.bodyTop = stateResult, 0 + return nil } - return m.reloadBranches() + return tea.Batch(append(cmds, m.showDeleting())...) +} + +// showDeleting opens the deleting screen for a run about to start and returns +// the cmd that animates its spinner. +func (m *model) showDeleting() tea.Cmd { + m.spinnerFrame, m.abortArmed = 0, false + m.state, m.bodyTop = stateDeleting, 0 + return spinnerTickCmd() } // undoDoneMsg carries a background undo and the reload after it. @@ -1407,6 +1423,9 @@ type undoDoneMsg struct { // .git/config.lock. A remote branch cannot come back this way: that would be a // push, so the exit summary prints the command instead. func (m *model) undo() tea.Cmd { + if m.undoing { + return nil // a second run would recreate branches the first already made + } var todo []int for i, r := range m.results { if r.restorable() { @@ -1418,6 +1437,7 @@ func (m *model) undo() tea.Cmd { m.status = "nothing to undo" return nil } + m.undoing = true m.status = "restoring…" results, withRemote := slices.Clone(m.results), m.remoteLoaded return func() tea.Msg { @@ -1436,6 +1456,7 @@ func (m *model) undo() tea.Cmd { // applyUndo records a finished undo and installs the reload that came with it. func (m *model) applyUndo(msg undoDoneMsg) tea.Cmd { + m.undoing = false remote := 0 for _, i := range msg.restored { m.results[i].restored = true diff --git a/review_test.go b/review_test.go new file mode 100644 index 0000000..8dd9b2b --- /dev/null +++ b/review_test.go @@ -0,0 +1,194 @@ +package main + +import ( + "path/filepath" + "strings" + "testing" +) + +// A teammate pushes to the branch after our last fetch. The ✓ and the commit +// count on screen describe the old commit, so the delete must not go through. +func TestRemoteDeleteRefusesMovedBranch(t *testing.T) { + repo := setupRepo(t) + chdir(t, repo) + url := git(t, repo, "remote", "get-url", "origin") + mate := filepath.Join(t.TempDir(), "mate") + git(t, filepath.Dir(mate), "clone", "-q", url, mate) + git(t, mate, "config", "user.email", "m@m.m") + git(t, mate, "config", "user.name", "m") + git(t, mate, "checkout", "-q", "feature/tracked") + commitFile(t, mate, "new", "teammate work") + git(t, mate, "push", "-q", "origin", "feature/tracked") + pushed := git(t, mate, "rev-parse", "HEAD") + + m, err := initialModel() + if err != nil { + t.Fatal(err) + } + tb := find(m.branches, "feature/tracked") + tb.selected, tb.deleteRemote = true, true + m = startAndDrain(t, m, true) + + r := m.results[0] + if r.remoteOK || !strings.Contains(r.remoteErr, "moved since the last fetch") { + t.Fatalf("the delete of a moved remote branch must be refused: %+v", r) + } + if got := git(t, url, "rev-parse", "refs/heads/feature/tracked"); got != pushed { + t.Fatalf("the remote branch must keep the teammate's commit %s, got %s", pushed, got) + } +} + +// The local branch is behind its remote branch. The remote result and the +// restore command must name the remote's commit, not the local tip. +func TestRemoteRestoreNamesRemoteCommit(t *testing.T) { + repo := setupRepo(t) + setupDeleteShapes(t, repo) + chdir(t, repo) + remoteTip := git(t, repo, "rev-parse", "refs/remotes/origin/shape/behind") + localTip := git(t, repo, "rev-parse", "refs/heads/shape/behind") + if remoteTip == localTip { + t.Fatal("precondition: the branch must be behind its upstream") + } + m, err := initialModel() + if err != nil { + t.Fatal(err) + } + b := find(m.branches, "shape/behind") + b.selected, b.deleteRemote = true, true + m = startAndDrain(t, m, true) + + summary := restoreSummary(m.results) + if !strings.Contains(summary, "git push origin "+remoteTip+":refs/heads/shape/behind") { + t.Fatalf("the push restore must name the remote's commit %s:\n%s", remoteTip, summary) + } + if !strings.Contains(summary, "git branch shape/behind "+localTip) { + t.Fatalf("the local restore must name the local tip %s:\n%s", localTip, summary) + } + if o := stripANSI(m.resultView()); !strings.Contains(o, "deleted remote origin/shape/behind (was "+remoteTip[:7]+")") { + t.Fatalf("the result must show the remote's commit:\n%s", o) + } +} + +// A fetch that lands on the confirm screen brings a list with no commit counts +// and selects more branches. The screen must not stay open over that. +func TestReloadClosesConfirmScreen(t *testing.T) { + repo := setupRepo(t) + git(t, repo, "checkout", "-q", "-b", "gone/clean", "main") + git(t, repo, "push", "-q", "-u", "origin", "gone/clean") + git(t, repo, "checkout", "-q", "main") + chdir(t, repo) + m, err := initialModel() + if err != nil { + t.Fatal(err) + } + m = press(t, m, key("f")) + cursorTo(t, &m, "feature/unmerged") + m = press(t, m, key(" "), key("d")) + wantState(t, m, stateConfirm, "d opens the confirm screen") + if !strings.Contains(stripANSI(m.View()), "will discard") { + t.Fatal("precondition: the confirm screen warns about the unmerged branch") + } + + git(t, repo, "push", "-q", "origin", "--delete", "gone/clean") + git(t, repo, "fetch", "-q", "--prune") + nm, cmd := m.Update(fetchDoneMsg{}) + m = nm.(model) + wantState(t, m, stateList, "a reload must close the confirm screen") + nm, _ = m.Update(cmd()) + m = nm.(model) + wantState(t, m, stateList, "the merge queries must not reopen it") + + // d measures the new list, so the warning is back with the new selection. + m = press(t, m, key("d")) + wantState(t, m, stateConfirm, "d opens the confirm screen again") + if o := stripANSI(m.View()); !strings.Contains(o, "will discard") || !strings.Contains(o, "gone/clean") { + t.Fatalf("the new confirm screen must show the warning and the new branch:\n%s", o) + } +} + +// y on the force prompt can push, and a push can wait out netTimeout, so none +// of it may run inside Update. +func TestForceRetryRunsOffTheUpdateLoop(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 = startAndDrain(t, m, false) + wantState(t, m, stateForcePrompt, "a refused -d raises the force prompt") + + before := gitProcs.total.Load() + nm, cmd := m.Update(key("y")) + m = nm.(model) + if n := gitProcs.total.Load() - before; n != 0 || cmd == nil { + t.Fatalf("the force retry must run off the update loop: %d git processes ran inside Update", n) + } + wantState(t, m, stateDeleting, "the retry shows the deleting screen") + if m.deletesDone() != 0 { + t.Fatal("the retried result must read as in progress") + } + m = drainDeletions(t, m, cmd) + wantState(t, m, stateResult, "the retry ends on the results screen") + if r := m.results[0]; !r.localOK || r.forceable { + t.Fatalf("the retry must delete the branch: %+v", r) + } +} + +// An undo answers with indexes into the results of the run it undoes. A new +// run started before it lands would replace that list under it. +func TestUndoHoldsNewDeleteRun(t *testing.T) { + chdir(t, setupManyTracked(t, 3)) + m, err := initialModel() + if err != nil { + t.Fatal(err) + } + m.force = true + find(m.branches, "feature/0").selected = true + find(m.branches, "feature/1").selected = true + m = startAndDrain(t, m, false) + + nm, undo := m.Update(key("u")) + m = nm.(model) + if undo == nil || !m.undoing { + t.Fatal("u must start the restore") + } + find(m.branches, "feature/2").selected = true + nm, cmd := m.Update(key("d")) + m = nm.(model) + if cmd != nil || m.state != stateList || !strings.Contains(m.status, "still restoring") { + t.Fatalf("d must wait for the undo: state %d, status %q", m.state, m.status) + } + if nm, again := m.Update(key("u")); again != nil || !nm.(model).undoing { + t.Fatal("a second u must not start a second restore") + } + + nm, next := m.Update(undo()) + m = settle(m, nm.(model), next) + if m.undoing || !m.results[0].restored || !m.results[1].restored { + t.Fatalf("the undo must land on its own results: %+v", m.results) + } + find(m.branches, "feature/2").selected = true + m = press(t, m, key("d")) + wantState(t, m, stateConfirm, "d works again once the undo has landed") +} + +// Before the merge queries land no branch reads as merged, so m would select +// nothing and say so as if it were the answer. +func TestMergedOldWaitsForMergeStatus(t *testing.T) { + chdir(t, setupRepo(t)) + m, err := startupModel() + if err != nil { + t.Fatal(err) + } + nm, _ := m.Update(key("m")) + m = nm.(model) + if m.state != stateList || !strings.Contains(m.status, "still reading merge status") { + t.Fatalf("m must wait for the merge queries: state %d, status %q", m.state, m.status) + } + nm, _ = m.Update(m.mergeCmd()()) + m = nm.(model) + m = press(t, m, key("m")) + wantState(t, m, stateAge, "m opens its prompt once the merge status is known") +} diff --git a/view.go b/view.go index 96d1f5e..2438b31 100644 --- a/view.go +++ b/view.go @@ -771,7 +771,7 @@ func appendResultLines(dst []string, r deleteResult) []string { // Say why the armed remote survived, or it reads as a silent failure. dst = append(dst, errStyle.Render(" ! ")+"kept remote "+remote+": local delete failed") case r.remoteTried && r.remoteOK: - dst = append(dst, okStyle.Render(" ✓ ")+"deleted remote "+remote+dimStyle.Render(" (was "+r.br.hash+")")) + dst = append(dst, okStyle.Render(" ✓ ")+"deleted remote "+remote+dimStyle.Render(" (was "+r.br.remoteHash()+")")) case r.remoteTried: dst = append(dst, errStyle.Render(" ✗ ")+"remote "+remote+": "+r.remoteErr) }