From f8e2bb549f0f4d2e008e036fa397ec7d39ac4ae3 Mon Sep 17 00:00:00 2001 From: hermes Date: Sun, 22 Nov 2026 22:45:35 +0100 Subject: [PATCH] Add force update key to reset branches to upstream tip Pressing F in the picker targets the highlighted branch, or every branch marked with c, and opens a confirmation screen before running git fetch origin followed by reset --hard (worktree branches) or branch -f (plain branches). Detached worktrees are skipped and dirty targets are flagged. --- README.md | 4 +- SPEC.md | 17 +++++- cmd/wt/main.go | 13 ++++ integration_test.go | 105 ++++++++++++++++++++++++++++++++ internal/action/action.go | 41 +++++++++++++ internal/action/action_test.go | 69 +++++++++++++++++++++ internal/ui/ui.go | 67 +++++++++++++++++++- internal/ui/ui_test.go | 108 +++++++++++++++++++++++++++++++++ 8 files changed, 418 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 12a5f71..7a7c002 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,8 @@ Once at least one item is marked, a hint line appears below the list telling you If any marked branch has unmerged changes, any marked worktree has modified or untracked files, or any marked worktree is locked, confirming does not delete anything yet — `git branch -d` and `git worktree remove` would refuse them anyway. Instead a second screen lists the unmerged branch(es), dirty worktree(s), and/or locked worktree(s) and requires you to type `delete` and press `Enter` before the whole batch is deleted: merged branches via `git branch -d` and unmerged ones via `git branch -D`, clean and unlocked worktrees via `git worktree remove`, dirty ones via `git worktree remove --force`, and locked ones via `git worktree remove --force --force` (git requires `--force` twice to remove a locked worktree). `Esc`/`Ctrl-C` cancels the entire batch and returns to the list without touching Git state. +Highlight a branch — or mark several with `c` — and press `F` to force update them. A confirmation screen lists the target branch(es); `Enter` runs `git fetch origin`, then resets each branch to `origin/` (`git reset --hard` in its worktree, `git branch -f` for a plain branch with no worktree). This discards local commits and, in worktrees, uncommitted changes; the confirmation screen warns when a target worktree is dirty. Detached worktrees have no branch and are skipped. `Esc`/`Ctrl-C`/`q` cancels without touching Git state or clearing marks. + The picker uses color to distinguish the selected row, current worktree, marked items, worktree tags, locked worktrees, and filter prompt. Pass `--no-color` to disable all ANSI styling. Selecting a worktree changes your shell's directory to it. Selecting a plain branch with no worktree prompts you to either switch to it in place or create a new worktree for it: @@ -98,7 +100,7 @@ keymap = "vim" # vim | emacs | arrows-only `wt` is written in Go and compiles to a single static binary, so there is no interpreter or runtime to install alongside it. The interactive list is built with the `bubbletea` terminal UI framework, which handles raw terminal mode, key events, and resizing consistently across Linux, macOS, and Windows. -`wt` never reimplements Git logic. It shells out to the real `git` binary for every read (`git branch`, including its merged-branch query, `git worktree list --porcelain`, and `git status --porcelain`) and every write (`git switch`, `git worktree add`, `git worktree remove`, confirmed `git worktree remove --force`, confirmed `git worktree remove --force --force`, `git branch -d`, and confirmed `git branch -D`), so behavior always matches what you would get running those commands yourself, including your existing hooks and credential helpers. A small collector step parses those outputs and merges them into one list, tagging each branch with its merge status, whether it already has a worktree, whether that worktree is dirty, and whether it is locked. That merged view is what makes the "already checked out elsewhere" case visible instead of being an error you hit after the fact. +`wt` never reimplements Git logic. It shells out to the real `git` binary for every read (`git branch`, including its merged-branch query, `git worktree list --porcelain`, and `git status --porcelain`) and every write (`git switch`, `git worktree add`, `git worktree remove`, confirmed `git worktree remove --force`, confirmed `git worktree remove --force --force`, `git branch -d`, confirmed `git branch -D`, and confirmed `git fetch origin` + `git reset --hard` / `git branch -f`), so behavior always matches what you would get running those commands yourself, including your existing hooks and credential helpers. A small collector step parses those outputs and merges them into one list, tagging each branch with its merge status, whether it already has a worktree, whether that worktree is dirty, and whether it is locked. That merged view is what makes the "already checked out elsewhere" case visible instead of being an error you hit after the fact. Because a subprocess cannot change its parent shell's working directory, `wt` prints the destination path and relies on a thin shell function, installed once via `wt init `, to perform the actual `cd`. This keeps your working directory untouched unless a switch actually happens. diff --git a/SPEC.md b/SPEC.md index e63d54d..2a31401 100644 --- a/SPEC.md +++ b/SPEC.md @@ -2,7 +2,7 @@ ## 1. Overview -`wt` is a single-binary CLI tool that presents a unified, interactively navigable list of local branches and Git worktrees, and switches the user's shell context to whichever one they select — either by `cd`-ing into an existing worktree or by checking out a branch in the current repository. It can also delete one or more branches (and their worktrees, where present) in bulk, via a mark-then-confirm flow. It never mutates Git state on its own; every write (checkout, `worktree add`, `worktree remove`, explicitly confirmed `worktree remove --force` or `worktree remove --force --force`, `branch -d`, or explicitly confirmed `branch -D`) happens only after user confirmation, and only via standard `git` invocations. +`wt` is a single-binary CLI tool that presents a unified, interactively navigable list of local branches and Git worktrees, and switches the user's shell context to whichever one they select — either by `cd`-ing into an existing worktree or by checking out a branch in the current repository. It can also delete one or more branches (and their worktrees, where present) in bulk, via a mark-then-confirm flow, and force-update one or more branches to their upstream tip via a similar confirmation flow. It never mutates Git state on its own; every write (checkout, `worktree add`, `worktree remove`, explicitly confirmed `worktree remove --force` or `worktree remove --force --force`, `branch -d`, explicitly confirmed `branch -D`, and confirmed `fetch` + `reset --hard` / `branch -f`) happens only after user confirmation, and only via standard `git` invocations. ## 2. Technology Choice @@ -52,13 +52,14 @@ No `fzf` dependency is required, but the design deliberately keeps the same *int │ - worktree path → emit cd path to wrapper (no git mutation) │ - existing path → return it to the shell wrapper │ - marked set → git worktree remove (forced if dirty/locked) + git branch -d/-D, per item +│ - F target set → git fetch origin, then reset --hard / branch -f to origin/ └──────────────────────┘ ``` **Data flow:** 1. `gitdata` runs `git branch --list --format='%(refname:short)'`, `git branch --format='%(refname:short)' --merged`, `git worktree list --porcelain -z`, and `git status --porcelain` scoped to each worktree's path, parses their output, and produces a single normalized list of items, cross-referencing merge status, dirty (modified/untracked) status, and which branches are already checked out in a worktree (the exact information `git switch` uses to produce its "already checked out" error — surfacing it up front removes the dead end). 2. `ui` renders the list, handles keystrokes purely as state transitions (no side effects) until the user confirms. -3. `action` executes exactly one of: `git switch`, `git worktree add`, a directory change (for worktrees), or — after the mark-then-`D`-then-confirm flow — `git worktree remove` (only for marked items that have a worktree; `--force` for dirty worktrees and `--force --force` for locked worktrees, after phrase-typed confirmation) followed by `git branch -d` for merged branches or, after phrase-typed confirmation, `git branch -D` for unmerged branches. +3. `action` executes exactly one of: `git switch`, `git worktree add`, a directory change (for worktrees), the mark-then-`D`-then-confirm deletion flow, or the `F`-then-confirm force-update flow: one `git fetch origin`, then `git reset --hard origin/` for each target branch with a worktree and `git branch -f origin/` for each target branch without one. Detached worktrees have no branch and are skipped. **Directory-change trick:** a subprocess cannot change its parent shell's `cwd`. `wt` handles this the same way `zoxide`/`fzf`-based `cd` wrappers do — see §5. @@ -136,6 +137,16 @@ Type "delete" and press Enter to proceed, or Esc to cancel: screen on their own, though they can still trigger it via the dirty check if they have modified or untracked files. +**Force-updating branches:** highlighting a row (or marking several with +`c`) and pressing `F` opens a confirmation screen listing the target +branch(es) and their worktree paths (or `(no worktree)`). `Enter` runs one +`git fetch origin`, then `git reset --hard origin/` for each target +with a worktree and `git branch -f origin/` for each plain +target. This discards local commits and, in worktrees, uncommitted changes; +the confirmation screen warns when a target worktree is dirty. Detached +worktrees are skipped. `Esc`/`Ctrl-C`/`q` cancels without touching Git state +or clearing marks. The hint line and `?` overlay document the binding. + ## 5. Implementation Details **Command-line arguments:** @@ -170,7 +181,7 @@ The authoritative collector and action implementations are in **Integration tests** (real repositories): - Use `t.TempDir()` to create scratch repositories via actual `git init`, `git commit --allow-empty`, and `git worktree add` commands. - Drive the action and collection layers against the scratch repository and assert the resulting paths and Git repository state. -- Cover switching a plain branch, resolving an existing worktree, creating a worktree, and deleting marked branches, both with and without a worktree. +- Cover switching a plain branch, resolving an existing worktree, creating a worktree, deleting marked branches (with and without a worktree), and force-updating both a plain branch and a worktree branch to a remote tip that has advanced locally. ## 7. Building diff --git a/cmd/wt/main.go b/cmd/wt/main.go index 4117903..5e47be6 100644 --- a/cmd/wt/main.go +++ b/cmd/wt/main.go @@ -87,6 +87,9 @@ func run(pathOnly bool, worktreeRootFlag string, noColor bool) error { if len(result.Delete) > 0 { return applyDelete(result.Delete) } + if len(result.ForceUpdate) > 0 { + return applyForceUpdate(result.ForceUpdate) + } dest, err := applyResult(result) if err != nil { @@ -116,6 +119,16 @@ func applyDelete(items []gitdata.Item) error { return nil } +// applyForceUpdate resets each confirmed branch to its upstream tip, +// reporting success to stderr on completion. +func applyForceUpdate(items []gitdata.Item) error { + if err := action.ForceUpdate(items); err != nil { + return err + } + fmt.Fprintf(os.Stderr, "wt: force-updated %d branch(es)\n", len(items)) + return nil +} + func applyResult(result ui.Result) (string, error) { if result.Item.HasWorktree() { return action.Switch(result.Item) diff --git a/integration_test.go b/integration_test.go index 03c0ad1..4305fa3 100644 --- a/integration_test.go +++ b/integration_test.go @@ -92,6 +92,12 @@ func applyResult(t *testing.T, result ui.Result) string { } return "" } + if len(result.ForceUpdate) > 0 { + if err := action.ForceUpdate(result.ForceUpdate); err != nil { + t.Fatalf("action.ForceUpdate: %v", err) + } + return "" + } if result.Item.HasWorktree() { dest, err := action.Switch(result.Item) if err != nil { @@ -378,6 +384,105 @@ func TestIntegrationDeleteDirtyWorktreeRequiresForcePhrase(t *testing.T) { } } +// initRepoWithRemote initialises repo and pushes its initial commit to a +// fresh bare origin, returning the origin path. +func initRepoWithRemote(t *testing.T, repo string) string { + t.Helper() + initRepo(t, repo) + tmp := t.TempDir() + remote := filepath.Join(tmp, "origin.git") + runGit(t, tmp, "init", "--bare", "-b", "main", remote) + runGit(t, repo, "remote", "add", "origin", remote) + runGit(t, repo, "push", "-u", "origin", "main") + return remote +} + +// cloneOrigin clones remote into a fresh directory and configures a committer. +func cloneOrigin(t *testing.T, remote string) string { + t.Helper() + parent := t.TempDir() + clone := filepath.Join(parent, "clone") + runGit(t, parent, "clone", remote, clone) + runGit(t, clone, "config", "user.email", "wt-test@example.com") + runGit(t, clone, "config", "user.name", "wt test") + runGit(t, clone, "config", "commit.gpgsign", "false") + return clone +} + +func TestIntegrationForceUpdatePlainBranchToRemoteTip(t *testing.T) { + repo := t.TempDir() + remote := initRepoWithRemote(t, repo) + + // Advance origin/main from a second clone so the local repo is behind. + other := cloneOrigin(t, remote) + runGit(t, other, "commit", "--allow-empty", "-m", "remote commit") + runGit(t, other, "push", "origin", "main") + want := strings.TrimSpace(runGit(t, other, "rev-parse", "main")) + + chdir(t, repo) + items, err := gitdata.Collect() + if err != nil { + t.Fatalf("gitdata.Collect: %v", err) + } + top, err := gitdata.Toplevel() + if err != nil { + t.Fatalf("gitdata.Toplevel: %v", err) + } + + // main is highlighted at cursor 0: F then Enter confirms the force update. + m := ui.New(items, top, "", true) + result := drivePicker(t, m, keyRune('F'), keyEnter) + if len(result.ForceUpdate) != 1 || result.ForceUpdate[0].Branch != "main" { + t.Fatalf("result.ForceUpdate = %+v, want [main]", result.ForceUpdate) + } + applyResult(t, result) + + if got := strings.TrimSpace(runGit(t, repo, "rev-parse", "main")); got != want { + t.Fatalf("main = %s, want remote tip %s", got, want) + } +} + +func TestIntegrationForceUpdateWorktreeBranchToRemoteTip(t *testing.T) { + repo := t.TempDir() + remote := initRepoWithRemote(t, repo) + runGit(t, repo, "branch", "feature/x") + runGit(t, repo, "push", "origin", "feature/x") + + // Advance origin/feature/x from a second clone. + other := cloneOrigin(t, remote) + runGit(t, other, "checkout", "-b", "feature/x", "origin/feature/x") + runGit(t, other, "commit", "--allow-empty", "-m", "remote feature commit") + runGit(t, other, "push", "origin", "feature/x") + want := strings.TrimSpace(runGit(t, other, "rev-parse", "feature/x")) + + // The local worktree diverges with its own commit. + wtDir := filepath.Join(t.TempDir(), "feature-x-checkout") + runGit(t, repo, "worktree", "add", wtDir, "feature/x") + runGit(t, wtDir, "commit", "--allow-empty", "-m", "local divergence") + chdir(t, repo) + + items, err := gitdata.Collect() + if err != nil { + t.Fatalf("gitdata.Collect: %v", err) + } + top, err := gitdata.Toplevel() + if err != nil { + t.Fatalf("gitdata.Toplevel: %v", err) + } + + // order: main (cursor 0, current), feature/x (cursor 1) -> down, mark, F, Enter. + m := ui.New(items, top, "", true) + result := drivePicker(t, m, keyDown, keyRune('c'), keyRune('F'), keyEnter) + if len(result.ForceUpdate) != 1 || result.ForceUpdate[0].Branch != "feature/x" { + t.Fatalf("result.ForceUpdate = %+v, want [feature/x]", result.ForceUpdate) + } + applyResult(t, result) + + if got := strings.TrimSpace(runGit(t, wtDir, "rev-parse", "HEAD")); got != want { + t.Fatalf("feature/x worktree HEAD = %s, want remote tip %s", got, want) + } +} + func worktreePathForBranch(t *testing.T, repo, branch string) string { t.Helper() out := runGit(t, repo, "worktree", "list", "--porcelain") diff --git a/internal/action/action.go b/internal/action/action.go index 7105610..2d9ed47 100644 --- a/internal/action/action.go +++ b/internal/action/action.go @@ -54,6 +54,47 @@ func newWorktreeWith(run runnerFunc, path, branch string) (string, error) { return path, nil } +// ForceUpdate resets each branch to its upstream tip. It runs a single +// `git fetch origin`, then `git reset --hard origin/` for branches +// with a worktree and `git branch -f origin/` for plain +// branches. Callers must only pass items after the user has confirmed the +// action (see internal/ui's modeConfirmForceUpdate) — this function performs +// no confirmation of its own. Detached worktrees have no branch and are +// skipped. Every item is attempted even if earlier ones fail; all failures +// are combined into a single returned error. +func ForceUpdate(items []gitdata.Item) error { + return forceUpdateWith(runGit, items) +} + +func forceUpdateWith(run runnerFunc, items []gitdata.Item) error { + var targets []gitdata.Item + for _, item := range items { + if !item.Detached { + targets = append(targets, item) + } + } + if len(targets) == 0 { + return nil + } + if err := run("fetch", "origin"); err != nil { + return fmt.Errorf("fetch origin: %w", err) + } + var errs []error + for _, item := range targets { + ref := "origin/" + item.Branch + if item.HasWorktree() { + if err := run("-C", item.Path, "reset", "--hard", ref); err != nil { + errs = append(errs, fmt.Errorf("%s: %w", item.Branch, err)) + } + continue + } + if err := run("branch", "-f", item.Branch, ref); err != nil { + errs = append(errs, fmt.Errorf("%s: %w", item.Branch, err)) + } + } + return errors.Join(errs...) +} + // DeleteWorktrees removes each item's worktree, if it has one, via // `git worktree remove`, or `git worktree remove --force` when item.Dirty is // set, or `git worktree remove --force --force` when item.Locked is set (a diff --git a/internal/action/action_test.go b/internal/action/action_test.go index 19c34ce..54e88d2 100644 --- a/internal/action/action_test.go +++ b/internal/action/action_test.go @@ -243,3 +243,72 @@ func TestNewWorktreeWithRunsGitWorktreeAdd(t *testing.T) { t.Fatalf("git calls = %v, want %v", *calls, want) } } + +func TestForceUpdateWithFetchesOnceThenResetsWorktreeAndMovesPlainBranch(t *testing.T) { + run, calls := recordingRunner() + items := []gitdata.Item{ + {Branch: "feature/login", Path: "/repo/proj-login"}, + {Branch: "bugfix/api-timeout"}, + } + + if err := forceUpdateWith(run, items); err != nil { + t.Fatalf("forceUpdateWith() error = %v", err) + } + want := [][]string{ + {"fetch", "origin"}, + {"-C", "/repo/proj-login", "reset", "--hard", "origin/feature/login"}, + {"branch", "-f", "bugfix/api-timeout", "origin/bugfix/api-timeout"}, + } + if !reflect.DeepEqual(*calls, want) { + t.Fatalf("git calls = %v, want %v", *calls, want) + } +} + +func TestForceUpdateWithDetachedOnlyRunsNoGit(t *testing.T) { + run, calls := recordingRunner() + item := gitdata.Item{Branch: "(detached)", Path: "/repo/proj-scratch", Detached: true} + + if err := forceUpdateWith(run, []gitdata.Item{item}); err != nil { + t.Fatalf("forceUpdateWith() error = %v", err) + } + if len(*calls) != 0 { + t.Fatalf("git calls = %v, want none for a detached worktree", *calls) + } +} + +func TestForceUpdateWithFetchFailureStopsBeforeAnyReset(t *testing.T) { + run := func(args ...string) error { + if args[0] == "fetch" { + return fmt.Errorf("no remote") + } + t.Fatalf("unexpected git call after failed fetch: %v", args) + return nil + } + item := gitdata.Item{Branch: "feature/login", Path: "/repo/proj-login"} + + err := forceUpdateWith(run, []gitdata.Item{item}) + if err == nil || !strings.Contains(err.Error(), "fetch origin") { + t.Fatalf("forceUpdateWith() error = %v, want fetch origin error", err) + } +} + +func TestForceUpdateWithContinuesAfterFailureAndCombinesErrors(t *testing.T) { + run := func(args ...string) error { + if args[len(args)-1] == "origin/feature/login" { + return fmt.Errorf("boom") + } + return nil + } + items := []gitdata.Item{ + {Branch: "feature/login", Path: "/repo/proj-login"}, + {Branch: "bugfix/api-timeout"}, + } + + err := forceUpdateWith(run, items) + if err == nil { + t.Fatal("forceUpdateWith() error = nil, want combined error from the failing item") + } + if !strings.Contains(err.Error(), "feature/login") { + t.Fatalf("error = %v, want it to mention feature/login", err) + } +} diff --git a/internal/ui/ui.go b/internal/ui/ui.go index f47e7f5..544b047 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -26,6 +26,7 @@ const ( modeHelp modeConfirmDelete modeConfirmForceDelete + modeConfirmForceUpdate ) // ForceDeleteConfirmPhrase is the exact text a user must type to delete a @@ -42,6 +43,7 @@ type Result struct { Resolution string // config.ActionSwitch or config.ActionWorktree, set only when Item has no worktree NewWorktreePath string // suggested path, set only when Resolution == config.ActionWorktree Delete []gitdata.Item // set when the user confirmed bulk deletion of the marked branches + ForceUpdate []gitdata.Item // set when the user confirmed force-updating branches to their upstream tip } // Model is the bubbletea model for the picker. @@ -59,7 +61,8 @@ type Model struct { keymap string height int - forceConfirmInput string // typed phrase in modeConfirmForceDelete + forceConfirmInput string // typed phrase in modeConfirmForceDelete + forceTargets []gitdata.Item // branches F will force-update, marked set or highlighted item result Result quitting bool @@ -119,6 +122,8 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m.updateConfirmDelete(keyMsg) case modeConfirmForceDelete: return m.updateConfirmForceDelete(keyMsg) + case modeConfirmForceUpdate: + return m.updateConfirmForceUpdate(keyMsg) default: return m.updateList(keyMsg) } @@ -183,6 +188,41 @@ func (m Model) updateConfirmForceDelete(msg tea.KeyMsg) (tea.Model, tea.Cmd) { return m, nil } +// updateConfirmForceUpdate handles the approval step shown after F. Enter +// quits with the target branches in Result.ForceUpdate; any cancel key +// returns to the list without quitting or clearing the marked selection. +func (m Model) updateConfirmForceUpdate(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + if isCancel(msg) { + m.mode = modeList + return m, nil + } + if msg.Type == tea.KeyEnter { + m.result = Result{ForceUpdate: m.forceTargets} + m.quitting = true + return m, tea.Quit + } + return m, nil +} + +// forceUpdateTargets returns the branches F acts on: the marked set when +// non-empty, otherwise the highlighted item. Detached worktrees have no +// branch to update and are skipped. +func (m Model) forceUpdateTargets() []gitdata.Item { + items := m.Marked() + if len(items) == 0 { + if item := m.selected(); item != nil { + items = []gitdata.Item{*item} + } + } + var targets []gitdata.Item + for _, item := range items { + if !item.Detached { + targets = append(targets, item) + } + } + return targets +} + // hasUnmergedBranch reports whether any item has unmerged changes on its // branch. Detached-HEAD entries have no associated branch to delete, so // they are excluded regardless of their zero-value Unmerged field. @@ -356,6 +396,13 @@ func (m Model) updateList(msg tea.KeyMsg) (tea.Model, tea.Cmd) { } return m, nil + case msg.String() == "F": + m.forceTargets = m.forceUpdateTargets() + if len(m.forceTargets) > 0 { + m.mode = modeConfirmForceUpdate + } + return m, nil + case msg.Type == tea.KeyEnter: item := m.selected() if item == nil { @@ -552,6 +599,21 @@ func (m Model) View() string { } b.WriteString("[Enter] confirm [Esc] cancel\n") return b.String() + case modeConfirmForceUpdate: + targets := m.forceTargets + fmt.Fprintf(&b, "Force update %d branch(es) to origin/?\n", len(targets)) + for _, item := range targets { + path := item.Path + if path == "" { + path = "(no worktree)" + } + fmt.Fprintf(&b, " %s %s\n", item.Branch, path) + } + if hasDirtyWorktree(targets) { + b.WriteString("Warning: uncommitted changes in the listed worktrees will be lost.\n") + } + b.WriteString("[Enter] confirm [Esc] cancel\n") + return b.String() case modeConfirmForceDelete: marked := m.Marked() if hasUnmergedBranch(marked) { @@ -658,7 +720,7 @@ func (m Model) View() string { b.WriteString("\n") } if n := len(m.marked); n > 0 { - hint := fmt.Sprintf("%d marked — [D] delete\n", n) + hint := fmt.Sprintf("%d marked — [D] delete, [F] force update\n", n) if !m.noColor { hint = markedStyle.Render(hint) } @@ -697,6 +759,7 @@ func (m Model) helpView() string { " filter : / (Esc clears)", " mark : c (selection)", " delete : D (marked branches, asks to confirm; unmerged branches, dirty worktrees, or locked worktrees require typing a phrase)", + " force update: F (highlighted or marked branches, asks to confirm; resets each to origin/)", " confirm : Enter", " cancel : Esc, Ctrl-C, q", " help : ?", diff --git a/internal/ui/ui_test.go b/internal/ui/ui_test.go index 25e6fb1..1b26872 100644 --- a/internal/ui/ui_test.go +++ b/internal/ui/ui_test.go @@ -703,3 +703,111 @@ func TestSelectedStyleResumesAfterNestedStyleReset(t *testing.T) { t.Fatalf("renderSelected() = %q, want %q", got, want) } } + +func TestFKeyWithNoMarksTargetsHighlightedItem(t *testing.T) { + m := New(testItems(), "/repo/proj", "", true) + m = send(t, m, key('j'), key('F')) + if m.mode != modeConfirmForceUpdate { + t.Fatalf("mode after F = %v, want modeConfirmForceUpdate", m.mode) + } + if len(m.forceTargets) != 1 || m.forceTargets[0].Branch != "feature/login" { + t.Fatalf("forceTargets = %+v, want [feature/login]", m.forceTargets) + } +} + +func TestFKeyWithMarksTargetsWholeMarkedSet(t *testing.T) { + m := New(testItems(), "/repo/proj", "", true) + m = send(t, m, key('j'), key('c'), key('j'), key('j'), key('c'), key('F')) + if m.mode != modeConfirmForceUpdate { + t.Fatalf("mode after F with marks = %v, want modeConfirmForceUpdate", m.mode) + } + if len(m.forceTargets) != 2 || m.forceTargets[0].Branch != "feature/login" || m.forceTargets[1].Branch != "release/2.1" { + t.Fatalf("forceTargets = %+v, want [feature/login, release/2.1]", m.forceTargets) + } +} + +func TestConfirmForceUpdateEnterQuitsWithTargets(t *testing.T) { + m := New(testItems(), "/repo/proj", "", true) + next, cmd := m.Update(key('F')) + m = next.(Model) + if cmd != nil { + t.Fatalf("F should not quit the program, got cmd %v", cmd) + } + m = send(t, m, keyType(tea.KeyEnter)) + if !m.quitting { + t.Fatal("Enter in modeConfirmForceUpdate should quit the program") + } + res := m.Result() + if len(res.ForceUpdate) != 1 || res.ForceUpdate[0].Branch != "main" { + t.Fatalf("Result().ForceUpdate = %+v, want [main]", res.ForceUpdate) + } + if len(res.Delete) != 0 || res.Item.Branch != "" { + t.Fatalf("Result() = %+v, want only ForceUpdate set", res) + } +} + +func TestConfirmForceUpdateCancelReturnsToListWithoutQuitting(t *testing.T) { + for _, k := range []tea.KeyMsg{keyType(tea.KeyEsc), keyType(tea.KeyCtrlC), key('q')} { + m := New(testItems(), "/repo/proj", "", true) + m = send(t, m, key('j'), key('c'), key('F'), k) + if m.mode != modeList { + t.Fatalf("mode after %v in modeConfirmForceUpdate = %v, want modeList", k, m.mode) + } + if m.quitting { + t.Fatalf("%v in modeConfirmForceUpdate should not quit the program", k) + } + if len(m.Marked()) != 1 { + t.Fatalf("Marked() after cancelling force update = %+v, want one marked item", m.Marked()) + } + } +} + +func TestFKeyOnDetachedItemIsIgnored(t *testing.T) { + items := append(testItems(), gitdata.Item{Branch: "(detached)", Path: "/repo/proj-scratch", Detached: true}) + m := New(items, "/repo/proj", "", true) + m = send(t, m, key('G'), key('F')) + if m.mode != modeList { + t.Fatalf("mode after F on a detached worktree = %v, want modeList", m.mode) + } +} + +func TestConfirmForceUpdateViewListsTargetsAndWarnsOnDirty(t *testing.T) { + items := testItems() + items[1].Dirty = true + m := New(items, "/repo/proj", "", true) + m = send(t, m, key('j'), key('F')) + view := m.View() + if !strings.Contains(view, "Force update 1 branch(es)") || !strings.Contains(view, "feature/login") { + t.Fatalf("confirm view missing target details:\n%s", view) + } + if !strings.Contains(view, "uncommitted changes") { + t.Fatalf("confirm view missing dirty-worktree warning:\n%s", view) + } + if !strings.Contains(view, "[Enter] confirm") || !strings.Contains(view, "[Esc] cancel") { + t.Fatalf("confirm view missing key hints:\n%s", view) + } +} + +func TestViewShowsForceUpdateHintOnlyWhenMarked(t *testing.T) { + m := New(testItems(), "/repo/proj", "", true) + if strings.Contains(m.View(), "[F] force update") { + t.Fatalf("View() with nothing marked should not show a force-update hint:\n%s", m.View()) + } + m = send(t, m, key('j'), key('c')) + view := m.View() + if !strings.Contains(view, "1 marked") || !strings.Contains(view, "[F] force update") { + t.Fatalf("View() with a marked item missing force-update hint:\n%s", view) + } +} + +func TestHelpOverlayDocumentsForceUpdateBinding(t *testing.T) { + m := New(testItems(), "/repo/proj", "", true) + m = send(t, m, key('?')) + if m.mode != modeHelp { + t.Fatalf("mode after ? = %v, want modeHelp", m.mode) + } + view := m.View() + if !strings.Contains(view, "force update") || !strings.Contains(view, "origin/") { + t.Fatalf("help view missing force-update binding:\n%s", view) + } +}