Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -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.

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
8 changes: 8 additions & 0 deletions bugs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
4 changes: 2 additions & 2 deletions cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
21 changes: 17 additions & 4 deletions docs/test-coverage-gaps.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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;
Expand Down
87 changes: 81 additions & 6 deletions git.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ type branch struct {
upstream string // e.g. "origin/feature"; "" when no upstream is configured
upRemote string // branch.<name>.remote, kept so undo can restore tracking
upMerge string // branch.<name>.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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
}

Expand All @@ -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 {
Expand All @@ -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 {
Expand All @@ -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.
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
Expand Down
14 changes: 8 additions & 6 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
}
Expand Down
Loading
Loading