Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: Implement `wt switch -` with worktrunk.history
Maximilian Roos381407b943a3
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 7dae6b999..5801d1f34 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -155,9 +155,31 @@ pub fn handle_switch() -> Result<(SwitchResult, String), GitError> {let repo = Repository::current();+ // Get current history (current, previous) before resolving+ let history_before = repo.get_switch_history();+// Resolve special branch names ("@" for current, "-" for previous)let resolved_branch = repo.resolve_worktree_name(branch)?;+ // Calculate what to record in history after the switch+ // History stores (current_location, previous_location) for ping-pong behavior+ let (new_current, new_previous) = if branch == "-" {+ // Switching back: swap current and previous+ // history_before contains (A, B), we're switching from A to B+ // After switch, record (B, A) so we can switch back to A+ if let Some((current, _previous)) = history_before {+ (resolved_branch.clone(), Some(current))+ } else {+ // No history - shouldn't happen since "-" requires history+ // But handle gracefully: just record where we're going+ (resolved_branch.clone(), None)+ }+ } else {+ // Normal switch: record new location as current, old current as previous+ let previous = history_before.map(|(current, _)| current);+ (resolved_branch.clone(), previous)+ };+// Resolve base if providedlet resolved_base = if let Some(base_str) = base {Some(repo.resolve_worktree_name(base_str)?)@@ -182,6 +204,9 @@ pub fn handle_switch(// Check if worktree already exists for this branchmatch repo.worktree_for_branch(&resolved_branch)? {Some(existing_path) if existing_path.exists() => {+ // Record successful switch in history for `wt switch -` support+ let _ = repo.record_switch_history(&new_current, new_previous.as_deref());+// Canonicalize the path for cleaner displaylet canonical_existing_path = existing_path.canonicalize().unwrap_or(existing_path);return Ok((@@ -297,6 +322,9 @@ pub fn handle_switch(// Note: post-start commands are spawned AFTER success message is shown// (see main.rs switch handler for temporal locality)+ // Record successful switch in history for `wt switch -` support+ let _ = repo.record_switch_history(&new_current, new_previous.as_deref());+Ok((SwitchResult::CreatedWorktree {path: worktree_path,diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 9029b4d66..0919d258e 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -222,39 +222,69 @@ impl Repository {branch.and_then(|branch| self.branch_keyed_status(branch))}+ /// Record branch history in worktrunk.history for `wt switch -` support.+ ///+ /// Stores "current,previous" to enable ping-pong switching.+ /// This enables `wt switch -` to work after `wt switch` operations,+ /// which don't create git reflog entries.+ pub fn record_switch_history(+ &self,+ current: &str,+ previous: Option<&str>,+ ) -> Result<(), GitError> {+ let value = if let Some(prev) = previous {+ format!("{},{}", current, prev)+ } else {+ current.to_string()+ };+ self.run_command(&["config", "worktrunk.history", &value])?;+ Ok(())+ }++ /// Get the previous branch from worktrunk.history.+ ///+ /// Returns (current, previous) if history is recorded.+ /// For single-value history (legacy), returns (value, None).+ pub fn get_switch_history(&self) -> Option<(String, Option<String>)> {+ self.run_command(&["config", "--get", "worktrunk.history"])+ .ok()+ .and_then(|output| {+ let trimmed = output.trim();+ if trimmed.is_empty() {+ return None;+ }+ let parts: Vec<&str> = trimmed.splitn(2, ',').collect();+ Some((parts[0].to_string(), parts.get(1).map(|s| s.to_string())))+ })+ }+/// Resolve a worktree name, expanding "@" to the current branch and "-" to the previous branch.////// # Arguments/// * `name` - The worktree name to resolve:/// - "@" for current HEAD- /// - "-" for previous branch (via git reflog @{-1})+ /// - "-" for previous branch (via worktrunk.history)/// - any other string is returned as-is////// # Returns/// - `Ok(name)` if not "@" or "-"/// - `Ok(current_branch)` if "@" and on a branch- /// - `Ok(previous_branch)` if "-" and reflog has a previous checkout+ /// - `Ok(previous_branch)` if "-" and worktrunk.history has a previous branch/// - `Err(DetachedHead)` if "@" and in detached HEAD state- /// - `Err` if "-" but no previous branch in reflog+ /// - `Err` if "-" but no previous branch in historypub fn resolve_worktree_name(&self, name: &str) -> Result<String, GitError> {match name {"@" => self.current_branch()?.ok_or(GitError::DetachedHead),"-" => {- // Use git's reflog to get the previous branch- let output = self- .run_command(&["rev-parse", "--abbrev-ref", "@{-1}"])- .map_err(|_| {+ // Read from worktrunk.history (recorded by wt switch operations)+ // History stores (current, previous), we want previous+ self.get_switch_history()+ .and_then(|(_, prev)| prev)+ .ok_or_else(|| {GitError::message(- "No previous branch found in reflog. Use 'wt list' to see available worktrees."+ "No previous branch found in history. Use 'wt list' to see available worktrees.",)- })?;- let trimmed = output.trim();- if trimmed.is_empty() {- return Err(GitError::message(- "No previous branch found in reflog. Use 'wt list' to see available worktrees.",- ));- }- Ok(trimmed.to_string())+ })}_ => Ok(name.to_string()),}diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 10f5e0f00..dad629b07 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -425,7 +425,7 @@ fn test_switch_previous_branch() {let repo = TestRepo::new();repo.commit("Initial commit");- // Create two branches and establish checkout history in git's reflog+ // Create two brancheslet mut cmd = Command::new("git");repo.configure_git_cmd(&mut cmd);cmd.args(["branch", "feature-a"])@@ -440,29 +440,63 @@ fn test_switch_previous_branch() {.output().expect("Failed to create feature-b");+ // Use wt switch to establish worktrunk.history+ snapshot_switch("switch_previous_branch_first", &repo, &["feature-a"]);+ snapshot_switch("switch_previous_branch_second", &repo, &["feature-b"]);++ // Now wt switch - should resolve to feature-b (the previous wt switch)+ snapshot_switch("switch_previous_branch", &repo, &["-"]);+}++#[test]+fn test_switch_previous_branch_no_history() {+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // No checkout history, so wt switch - should fail with helpful error+ snapshot_switch("switch_previous_branch_no_history", &repo, &["-"]);+}++#[test]+fn test_switch_previous_branch_with_worktrunk_history() {+ use std::process::Command;++ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create two brancheslet mut cmd = Command::new("git");repo.configure_git_cmd(&mut cmd);- cmd.args(["switch", "feature-a"])+ cmd.args(["branch", "feature-x"]).current_dir(repo.root_path()).output()- .expect("Failed to switch to feature-a");+ .expect("Failed to create feature-x");let mut cmd = Command::new("git");repo.configure_git_cmd(&mut cmd);- cmd.args(["switch", "feature-b"])+ cmd.args(["branch", "feature-y"]).current_dir(repo.root_path()).output()- .expect("Failed to switch to feature-b");+ .expect("Failed to create feature-y");- // Now wt switch - should resolve to feature-a (the previous branch)- snapshot_switch("switch_previous_branch", &repo, &["-"]);-}+ // Use wt switch to switch to feature-x (this records history)+ snapshot_switch(+ "switch_previous_branch_with_worktrunk_history_first",+ &repo,+ &["feature-x"],+ );-#[test]-fn test_switch_previous_branch_no_history() {- let repo = TestRepo::new();- repo.commit("Initial commit");+ // Switch to feature-y (this records feature-x in history)+ snapshot_switch(+ "switch_previous_branch_with_worktrunk_history_second",+ &repo,+ &["feature-y"],+ );- // No checkout history, so wt switch - should fail with helpful error- snapshot_switch("switch_previous_branch_no_history", &repo, &["-"]);+ // Now wt switch - should resolve to feature-x (from worktrunk.history)+ snapshot_switch(+ "switch_previous_branch_with_worktrunk_history_back",+ &repo,+ &["-"],+ );}diff --git a/tests/snapshots/integration__integration_tests__switch__switch_previous_branch.snap b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch.snapindex 1743f925e..d6cb35372 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_previous_branch.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch.snap@@ -16,7 +16,7 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpTM7CeS/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpOI5Kmy/test-config.toml---success: trueexit_code: 0diff --git a/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_first.snap b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_first.snapnew file mode 100644index 000000000..32315f404--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_first.snap@@ -0,0 +1,27 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - feature-a+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpwSmoLj/test-config.toml+---+success: true+exit_code: 0+----- stdout -----+β [32mSwitched to worktree for [1m[32mfeature-a[0m[32m at [1m[32m[REPO].feature-a[0m[0m+π‘ [2mTo enable automatic cd, run: wt config shell[0m++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_no_history.snap b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_no_history.snapindex a63287722..a85ae45a5 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_no_history.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_no_history.snap@@ -16,11 +16,11 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpnq1lig/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpIz3CvP/test-config.toml---success: falseexit_code: 1----- stdout ---------- stderr ------β [31mNo previous branch found in reflog. Use 'wt list' to see available worktrees.[0m+β [31mNo previous branch found in history. Use 'wt list' to see available worktrees.[0mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_second.snap b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_second.snapnew file mode 100644index 000000000..8deb1f7ee--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_second.snap@@ -0,0 +1,27 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - feature-b+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpLJYTq7/test-config.toml+---+success: true+exit_code: 0+----- stdout -----+β [32mSwitched to worktree for [1m[32mfeature-b[0m[32m at [1m[32m[REPO].feature-b[0m[0m+π‘ [2mTo enable automatic cd, run: wt config shell[0m++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_with_worktrunk_history_back.snap b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_with_worktrunk_history_back.snapnew file mode 100644index 000000000..a8c466f2b--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_with_worktrunk_history_back.snap@@ -0,0 +1,27 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "-"+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpmnQWzc/test-config.toml+---+success: true+exit_code: 0+----- stdout -----+β [32mSwitched to worktree for [1m[32mfeature-x[0m[32m at [1m[32m[REPO].feature-x[0m[0m+π‘ [2mTo enable automatic cd, run: wt config shell[0m++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_with_worktrunk_history_first.snap b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_with_worktrunk_history_first.snapnew file mode 100644index 000000000..0483237f0--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_with_worktrunk_history_first.snap@@ -0,0 +1,27 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - feature-x+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpRlQyJO/test-config.toml+---+success: true+exit_code: 0+----- stdout -----+β [32mSwitched to worktree for [1m[32mfeature-x[0m[32m at [1m[32m[REPO].feature-x[0m[0m+π‘ [2mTo enable automatic cd, run: wt config shell[0m++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_with_worktrunk_history_second.snap b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_with_worktrunk_history_second.snapnew file mode 100644index 000000000..2419101dc--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_with_worktrunk_history_second.snap@@ -0,0 +1,27 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - feature-y+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpjLrSOH/test-config.toml+---+success: true+exit_code: 0+----- stdout -----+β [32mSwitched to worktree for [1m[32mfeature-y[0m[32m at [1m[32m[REPO].feature-y[0m[0m+π‘ [2mTo enable automatic cd, run: wt config shell[0m++----- stderr -----