Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(switch): return `wt switch -` to the worktree it left, not the first checkout of its branch (#4497)

Maximilian Roos55d302dbb2b3
diff --git a/src/cli/config.rs b/src/cli/config.rs
index 903d62c5c..11991bffc 100644
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -1071,7 +1071,7 @@ Enables `wt switch -` to return to the previous worktree, similar to `cd -` or `
## How it works
-Updated automatically on every `wt switch`. Stored in git config as `worktrunk.history`.
+Updated automatically on every `wt switch`. Stored in git config as `worktrunk.history`, with the worktree's path in `worktrunk.history-path`.
Without a subcommand, runs `get`. Use `set` to override or `clear` to reset."#
)]
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rs
index f6dfc9d36..fb5b1a124 100644
--- a/src/commands/config/state.rs
+++ b/src/commands/config/state.rs
@@ -25,7 +25,7 @@
//! (`handle_cache_get`) and dropped by `wt config state cache clear`
//! (`handle_cache_clear`), which needs no prompt:
//!
-//! - Previous branch (git config `worktrunk.history`)
+//! - Previous branch (git config `worktrunk.history`, with `worktrunk.history-path`)
//! - CI status cache (`.git/wt/cache/ci-status/`, plus the PR-number width
//! ratchet in `.git/wt/cache/pr-number/`)
//! - Summary cache (`.git/wt/cache/summary/`)
@@ -915,7 +915,7 @@ pub fn handle_state_set(key: &str, value: String, branch: Option<String>) -> any
);
}
"previous-branch" => {
- repo.set_switch_previous(Some(&value))?;
+ repo.set_switch_previous(&value)?;
eprintln!(
"{}",
success_message(cformat!("Set previous branch to <bold>{value}</>"))
@@ -973,7 +973,7 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho
}
}
"previous-branch" => {
- if repo.unset_config("worktrunk.history")? {
+ if repo.clear_switch_previous()? {
eprintln!("{}", success_message("Cleared previous branch"));
} else {
eprintln!("{}", info_message("No previous branch to clear"));
@@ -1142,7 +1142,7 @@ fn clear_default_branch_reported(repo: &Repository) -> anyhow::Result<bool> {
}
fn clear_previous_branch_reported(repo: &Repository) -> anyhow::Result<bool> {
- if repo.unset_config("worktrunk.history")? {
+ if repo.clear_switch_previous()? {
eprintln!("{}", success_message("Cleared previous branch"));
return Ok(true);
}
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index 1e5ac0565..3de60c112 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -1747,14 +1747,20 @@ pub fn collect(
.and(integration_targets.clone());
options.snapshot = snapshot;
- // Update is_previous on items
- if let Some(prev) = previous_branch.as_deref() {
- for item in &mut all_items {
- if item.branch() == Some(prev)
- && let Some(wt_data) = item.worktree_data_mut()
- {
- wt_data.is_previous = true;
- }
+ // Update is_previous on items: the worktree `wt switch -` returns to,
+ // by its recorded path, or else every worktree of the previous branch.
+ let previous_path = repo
+ .switch_previous_worktree()
+ .ok()
+ .flatten()
+ .map(|(path, _)| path);
+ for item in &mut all_items {
+ let is_previous = match &previous_path {
+ Some(path) => item.worktree_path() == Some(path.as_path()),
+ None => previous_branch.is_some() && item.branch() == previous_branch.as_deref(),
+ };
+ if is_previous && let Some(wt_data) = item.worktree_data_mut() {
+ wt_data.is_previous = true;
}
}
diff --git a/src/commands/list/json_output.rs b/src/commands/list/json_output.rs
index 8b2e0e02c..6ee38db49 100644
--- a/src/commands/list/json_output.rs
+++ b/src/commands/list/json_output.rs
@@ -78,7 +78,7 @@ pub struct JsonItem {
/// This is the current worktree (matches repo discovery path: PWD or `-C`)
pub is_current: bool,
- /// This was the previous worktree (from `worktrunk.history`)
+ /// This was the previous worktree (the `wt switch -` target)
pub is_previous: bool,
/// CI status from PR or branch workflow
diff --git a/src/commands/list/model/item.rs b/src/commands/list/model/item.rs
index 2d6c217d8..13b0cc647 100644
--- a/src/commands/list/model/item.rs
+++ b/src/commands/list/model/item.rs
@@ -79,7 +79,7 @@ pub struct WorktreeData {
pub is_main: bool,
/// Whether this is the current worktree (matches repo discovery path: PWD or `-C`)
pub is_current: bool,
- /// Whether this was the previous worktree (from `worktrunk.history`)
+ /// Whether this was the previous worktree (the `wt switch -` target)
pub is_previous: bool,
/// Whether the worktree is at an unexpected location (branch-worktree mismatch).
/// Only true when: has branch name, not main worktree, and path differs from template.
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 124e3811b..0da55d93a 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -962,8 +962,9 @@ fn plan_switch(
clobber: bool,
config: &UserConfig,
) -> anyhow::Result<SwitchPlan> {
- // Record current branch for `wt switch -` support
- let new_previous = repo.current_worktree().branch().ok().flatten();
+ // Record the worktree being left, for `wt switch -`
+ let current = repo.current_worktree();
+ let new_previous = current.root().ok().zip(current.branch().ok());
if base.is_some() && !create {
eprintln!(
@@ -1123,8 +1124,8 @@ fn execute_switch(
// Only update switch history when actually switching worktrees.
// Updating on AlreadyAt would corrupt `wt switch -` by recording
// the current branch as "previous" even though no switch occurred.
- if !already_at_worktree {
- let _ = repo.set_switch_previous(new_previous.as_deref());
+ if !already_at_worktree && let Some((path, branch)) = &new_previous {
+ let _ = repo.record_switch_source(path, branch.as_deref());
}
let result = if already_at_worktree {
@@ -1395,7 +1396,9 @@ fn execute_switch(
}
// Record successful switch in history
- let _ = repo.set_switch_previous(new_previous.as_deref());
+ if let Some((path, branch)) = &new_previous {
+ let _ = repo.record_switch_source(path, branch.as_deref());
+ }
Ok((
SwitchResult::Created {
diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rs
index fbfabbca7..9f3f2442b 100644
--- a/src/commands/worktree/types.rs
+++ b/src/commands/worktree/types.rs
@@ -122,8 +122,9 @@ pub enum SwitchPlan {
path: PathBuf,
/// The branch at this worktree. `None` for detached HEAD.
branch: Option<String>,
- /// Branch to record as "previous" for `wt switch -`
- new_previous: Option<String>,
+ /// The worktree being left — path, and branch (`None` when detached) —
+ /// to record for `wt switch -`
+ new_previous: Option<(PathBuf, Option<String>)>,
},
/// Need to create a new worktree
Create {
@@ -138,8 +139,8 @@ pub enum SwitchPlan {
/// True when a stale path occupies `worktree_path` and `--clobber` was
/// given — `execute_switch` backs it up before creating the worktree.
needs_clobber_backup: bool,
- /// Branch to record as "previous" for `wt switch -`
- new_previous: Option<String>,
+ /// The worktree being left, to record for `wt switch -`
+ new_previous: Option<(PathBuf, Option<String>)>,
},
}
diff --git a/src/git/repository/config.rs b/src/git/repository/config.rs
index d2d97da6b..760a6e734 100644
--- a/src/git/repository/config.rs
+++ b/src/git/repository/config.rs
@@ -1,6 +1,6 @@
//! Git config, hints, marker, and default branch operations for Repository.
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use std::time::Duration;
use anyhow::Context;
@@ -287,17 +287,58 @@ impl Repository {
Ok(result)
}
- /// Set the previous branch in worktrunk.history for `wt switch -` support.
+ /// Record the worktree `wt switch` is leaving, so `wt switch -` can
+ /// return to it.
///
- /// Stores the branch we're switching FROM, so `wt switch -` can return to it.
- pub fn set_switch_previous(&self, previous: Option<&str>) -> anyhow::Result<()> {
- if let Some(prev) = previous {
- self.set_config_value("worktrunk.history", prev)?;
+ /// The branch goes in `worktrunk.history` and the path in
+ /// `worktrunk.history-path`. The branch alone can't name a detached
+ /// worktree, or the second checkout of a branch checked out twice; the
+ /// path can. A detached worktree clears the branch, so the two keys always
+ /// describe the same worktree, which is what
+ /// [`switch_previous_worktree`](Self::switch_previous_worktree) checks.
+ pub fn record_switch_source(&self, path: &Path, branch: Option<&str>) -> anyhow::Result<()> {
+ match branch {
+ Some(branch) => self.set_config_value("worktrunk.history", branch)?,
+ None => {
+ self.unset_config("worktrunk.history")?;
+ }
}
- // If previous is None (detached HEAD), don't update history
+ self.set_config_value("worktrunk.history-path", &path.to_string_lossy())
+ }
+
+ /// Set the previous branch outright (`wt config state previous-branch
+ /// set`), dropping the path a switch recorded alongside the old one.
+ pub fn set_switch_previous(&self, branch: &str) -> anyhow::Result<()> {
+ self.set_config_value("worktrunk.history", branch)?;
+ self.unset_config("worktrunk.history-path")?;
Ok(())
}
+ /// Forget the previous worktree. Returns whether anything was recorded.
+ pub fn clear_switch_previous(&self) -> anyhow::Result<bool> {
+ let branch = self.unset_config("worktrunk.history")?;
+ let path = self.unset_config("worktrunk.history-path")?;
+ Ok(branch || path)
+ }
+
+ /// The worktree `wt switch` last left, while it is still registered and
+ /// still holds the branch recorded with it.
+ ///
+ /// `None` sends `wt switch -` to [`switch_previous`](Self::switch_previous)
+ /// instead: the worktree is gone, its checkout changed since, or an older
+ /// wt recorded a different branch without a path. An older wt recording
+ /// the same branch leaves the stale path standing, which matters only for
+ /// a branch checked out twice.
+ pub fn switch_previous_worktree(&self) -> anyhow::Result<Option<(PathBuf, Option<String>)>> {
+ let Some(path) = self.config_last("worktrunk.history-path")? else {
+ return Ok(None);
+ };
+ let Some((path, branch)) = self.worktree_at_path(Path::new(&path))? else {
+ return Ok(None);
+ };
+ Ok((branch == self.switch_previous()).then_some((path, branch)))
+ }
+
/// Get the previous branch from worktrunk.history for `wt switch -`.
///
/// Returns the branch we came from, enabling ping-pong switching.
diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rs
index 153525ccb..c0d310723 100644
--- a/src/git/repository/tests.rs
+++ b/src/git/repository/tests.rs
@@ -1871,7 +1871,7 @@ fn path_selector_error_checks_for_a_registered_worktree() {
);
// Reached through the shortcut, which is the route with no prior lookup.
- test.repo.set_switch_previous(Some(selector)).unwrap();
+ test.repo.set_switch_previous(selector).unwrap();
let err = test.repo.require_worktree("-").unwrap_err();
assert!(
!err.to_string().contains("No worktree @"),
@@ -2227,7 +2227,7 @@ fn selector_reports_rewriting_rather_than_inferring_it() {
// The degenerate case string equality gets wrong: history pointing at the
// branch already checked out. Output == input, yet a shortcut fired.
- repo.set_switch_previous(Some(&current)).unwrap();
+ repo.set_switch_previous(&current).unwrap();
let previous = repo.expand_selector("-").unwrap();
assert_eq!(previous.token(), current);
assert!(
diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rs
index dbbeb31a8..4f42b4b9f 100644
--- a/src/git/repository/worktrees.rs
+++ b/src/git/repository/worktrees.rs
@@ -478,11 +478,13 @@ impl Repository {
///
/// Resolution order:
/// 1. `@` — the current worktree, matched by path so detached HEAD resolves
- /// 2. `-` / `^` — the previous / default branch, then as a branch below
- /// 3. a branch with a worktree
- /// 4. a path naming a registered worktree — absolute, `~`-relative, or
+ /// 2. `-` — the worktree `wt switch` last left, by the path it recorded
+ /// (see [`switch_previous_worktree`](Self::switch_previous_worktree))
+ /// 3. `-` / `^` — the previous / default branch, then as a branch below
+ /// 4. a branch with a worktree
+ /// 5. a path naming a registered worktree — absolute, `~`-relative, or
/// relative to `-C` (see [`resolve_input_path`])
- /// 5. otherwise the branch alone, which may or may not exist
+ /// 6. otherwise the branch alone, which may or may not exist
///
/// A path that named no worktree lands in `BranchOnly` or
/// `NoWorktreeAtPath` — [`resolve_selector`](Self::resolve_selector)
@@ -499,9 +501,9 @@ impl Repository {
/// [`usable_worktree_for_branch`](Self::usable_worktree_for_branch)'s job,
/// which the commands that go on to run there call instead.
pub fn resolve_worktree(&self, name: &str) -> anyhow::Result<ResolvedWorktree> {
- // `@` is the only selector that resolves by path rather than by name,
- // which is what lets it answer in a detached worktree — where the
- // branch expansion `expand_selector` would apply has nothing to return.
+ // `@` and `-` resolve by path rather than by name, which is what lets
+ // them answer for a detached worktree — where the branch expansion
+ // `expand_selector` would apply has nothing to return.
let name = normalize_selector(name);
if name == "@" {
// If worktree_root fails (e.g., in bare repo directory), give a clear error
@@ -522,6 +524,11 @@ impl Repository {
.and_then(|wt| wt.branch.clone());
return Ok(ResolvedWorktree::worktree(path, branch));
}
+ if name == "-"
+ && let Some((path, branch)) = self.switch_previous_worktree()?
+ {
+ return Ok(ResolvedWorktree::worktree(path, branch));
+ }
self.resolve_selector(&self.expand_selector(name)?)
}
diff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rs
index 977981fed..fdb877a67 100644
--- a/tests/integration_tests/repository.rs
+++ b/tests/integration_tests/repository.rs
@@ -658,11 +658,11 @@ fn test_switch_previous_roundtrip() {
// Populate the cache first to hit the in-memory update branch.
let _ = r.is_bare();
assert_eq!(r.switch_previous(), None);
- r.set_switch_previous(Some("feature-a")).unwrap();
- assert_eq!(r.switch_previous(), Some("feature-a".to_string()));
- // `None` is a no-op — doesn't clear.
- r.set_switch_previous(None).unwrap();
+ r.set_switch_previous("feature-a").unwrap();
assert_eq!(r.switch_previous(), Some("feature-a".to_string()));
+ assert!(r.clear_switch_previous().unwrap());
+ assert_eq!(r.switch_previous(), None);
+ assert!(!r.clear_switch_previous().unwrap());
}
/// `primary_remote_url` composes `primary_remote` + `remote_url`,
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 67346219b..9a136ae61 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -8617,6 +8617,86 @@ fn test_switch_at_names_the_current_worktree(mut repo: TestRepo, #[case] detache
assert_eq!(path.file_name(), current.file_name());
}
+/// Run `wt switch <args>` from `dir` with `--format=json` and return the
+/// path it lands in.
+fn switch_json_path(repo: &TestRepo, dir: &std::path::Path, args: &[&str]) -> std::path::PathBuf {
+ let output = repo
+ .wt_command()
+ .args(["switch", "--no-cd", "--yes", "--format=json"])
+ .args(args)
+ .current_dir(dir)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "stderr: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ std::path::PathBuf::from(json["path"].as_str().unwrap())
+}
+
+/// `wt switch -` returns to the worktree it left, by path, so it reaches the
+/// checkouts a branch name can't: the second copy of a branch checked out
+/// twice, and a detached worktree.
+#[rstest]
+#[case::second_checkout(false)]
+#[case::detached(true)]
+fn test_switch_previous_returns_to_the_worktree_left(mut repo: TestRepo, #[case] detached: bool) {
+ repo.add_worktree("feature");
+ let left = if detached {
+ repo.detach_head_in_worktree("feature");
+ repo.worktrees["feature"].clone()
+ } else {
+ add_force_duplicate(&repo, "feature", "feature-copy")
+ };
+
+ switch_json_path(&repo, &left, &["main"]);
+ let back = switch_json_path(&repo, repo.root_path(), &["-"]);
+ assert_eq!(back.file_name(), left.file_name());
+}
+
+/// The recorded path stands only while a worktree there still holds the
+/// recorded branch. When an older wt has since recorded a different branch
+/// without a path, `-` names that branch.
+#[rstest]
+fn test_switch_previous_falls_back_to_the_branch(mut repo: TestRepo) {
+ let feature = repo.add_worktree("feature");
+ repo.add_worktree("other");
+
+ switch_json_path(&repo, &feature, &["main"]);
+ // An older wt switching from `other` writes only the branch.
+ repo.run_git(&["config", "worktrunk.history", "other"]);
+
+ let back = switch_json_path(&repo, repo.root_path(), &["-"]);
+ assert_eq!(back.file_name(), repo.worktrees["other"].file_name());
+}
+
+/// When the worktree left has since been removed, `-` names its branch, which
+/// creates a worktree for it again.
+#[rstest]
+fn test_switch_previous_after_its_worktree_is_removed(mut repo: TestRepo) {
+ let feature = repo.add_worktree("feature");
+
+ switch_json_path(&repo, &feature, &["main"]);
+ repo.run_git(&["worktree", "remove", feature.to_str().unwrap()]);
+
+ let output = repo
+ .wt_command()
+ .args(["switch", "-", "--no-cd", "--yes", "--format=json"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "stderr: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(json["action"], "created");
+ assert_eq!(json["branch"], "feature");
+}
+
// -- JSON format tests --
#[rstest]
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_previous_branch.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_previous_branch.snap
index 2530c7d07..1c1c64c78 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_state_previous_branch.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_previous_branch.snap
@@ -79,7 +79,7 @@ Enables wt switch - to return to the previous worktree, similar to c
How it works
-Updated automatically on every wt switch. Stored in git config as worktrunk.history.
+Updated automatically on every wt switch. Stored in git config as worktrunk.history, with the worktree's path in worktrunk.history-path.
Without a subcommand, runs get. Use set to override or clear to reset.