Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: Allow `wt switch -` to go to previous branch
Maximilian Roosdf0cb61e5075
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 278a2ee16..a0e042499 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -157,7 +157,7 @@ pub fn handle_switch() -> Result<(SwitchResult, String), GitError> {let repo = Repository::current();- // Resolve "@" to current branch+ // Resolve special branch names ("@" for current, "-" for previous)let resolved_branch = repo.resolve_worktree_name(branch)?;// Resolve base if provided@@ -214,11 +214,10 @@ pub fn handle_switch(// Build git worktree add commandlet mut args = vec!["worktree", "add", worktree_path.to_str().unwrap()];- // Resolve the base branch if creating a new branch- let resolved_base = if create {- // Default to default branch if no base specified- match base {- Some(b) => Some(b.to_string()),+ // Use the resolved base, or default to default branch if creating without a base+ let base_for_creation = if create {+ match resolved_base {+ Some(b) => Some(b),None => Some(repo.resolve_target_branch(None)?),}} else {@@ -229,7 +228,7 @@ pub fn handle_switch(if create {args.push("-b");args.push(&resolved_branch);- if let Some(ref base_branch) = resolved_base {+ if let Some(ref base_branch) = base_for_creation {args.push(base_branch);}} else {@@ -264,7 +263,7 @@ pub fn handle_switch(SwitchResult::CreatedWorktree {path: worktree_path,created_branch: create,- base_branch: resolved_base,+ base_branch: base_for_creation,},resolved_branch,))diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 4729ca2de..ee98070e9 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -194,20 +194,35 @@ impl Repository {}}- /// Resolve a worktree name, expanding "@" to the current branch.+ /// Resolve a worktree name, expanding "@" to the current branch and "-" to the previous branch.////// # Arguments- /// * `name` - The worktree name to resolve (or "@" for current HEAD)+ /// * `name` - The worktree name to resolve:+ /// - "@" for current HEAD+ /// - "-" for previous branch (via git reflog @{-1})+ /// - any other string is returned as-is////// # Returns- /// - `Ok(name)` if not "@"+ /// - `Ok(name)` if not "@" or "-"/// - `Ok(current_branch)` if "@" and on a branch+ /// - `Ok(previous_branch)` if "-" and reflog has a previous checkout/// - `Err(DetachedHead)` if "@" and in detached HEAD state+ /// - `Err` if "-" but no previous branch in reflogpub fn resolve_worktree_name(&self, name: &str) -> Result<String, GitError> {- if name == "@" {- self.current_branch()?.ok_or(GitError::DetachedHead)- } else {- Ok(name.to_string())+ 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(|_| {+ GitError::CommandFailed(+ "No previous branch found in reflog. Use 'wt list' to see available worktrees.".to_string(),+ )+ })?;+ Ok(output.trim().to_string())+ }+ _ => Ok(name.to_string()),}}diff --git a/src/main.rs b/src/main.rsindex 953db519a..bdfd53b11 100644--- a/src/main.rs+++ b/src/main.rs@@ -273,6 +273,9 @@ Switch to existing worktree:Create new worktree from main:wt switch --create new-feature+Switch to previous worktree:+ wt switch -+Create from specific base:wt switch --create hotfix --base production@@ -282,7 +285,7 @@ Create and run command:Skip hooks during creation:wt switch --create temp --no-verify")]Switch {- /// Branch name, worktree path, or '@' for current HEAD+ /// Branch name, worktree path, '@' for current HEAD, or '-' for previous branchbranch: String,/// Create a new branchdiff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex d45357e22..10f5e0f00 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -417,3 +417,52 @@ fn test_switch_primary_on_different_branch() {&["existing-branch"],);}++#[test]+fn test_switch_previous_branch() {+ use std::process::Command;++ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create two branches and establish checkout history in git's reflog+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["branch", "feature-a"])+ .current_dir(repo.root_path())+ .output()+ .expect("Failed to create feature-a");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["branch", "feature-b"])+ .current_dir(repo.root_path())+ .output()+ .expect("Failed to create feature-b");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["switch", "feature-a"])+ .current_dir(repo.root_path())+ .output()+ .expect("Failed to switch to feature-a");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["switch", "feature-b"])+ .current_dir(repo.root_path())+ .output()+ .expect("Failed to switch to feature-b");++ // Now wt switch - should resolve to feature-a (the previous branch)+ 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, &["-"]);+}diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snapindex 8ba30eabf..b4ce27ed3 100644--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap@@ -16,7 +16,7 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp6NXzVa/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpdie7vF/test-config.toml---success: trueexit_code: 0@@ -172,7 +172,7 @@ if type -q wt; or set -q WORKTRUNK_BINcomplete -c wt -n '__fish_seen_subcommand_from dev; and __fish_seen_subcommand_from squash' -f -a '(__wt_complete)' -d 'Target branch to squash against (defaults to default branch)'complete -c wt -n '__fish_seen_subcommand_from dev; and __fish_seen_subcommand_from push' -f -a '(__wt_complete)' -d 'Target branch (defaults to default branch)'complete -c wt -n '__fish_seen_subcommand_from dev; and __fish_seen_subcommand_from rebase' -f -a '(__wt_complete)' -d 'Target branch to rebase onto (defaults to default branch)'- complete -c wt -n '__fish_seen_subcommand_from switch' -f -a '(__wt_complete)' -d 'Branch name, worktree path, or '@' for current HEAD'+ complete -c wt -n '__fish_seen_subcommand_from switch' -f -a '(__wt_complete)' -d 'Branch name, worktree path, '@' for current HEAD, or '-' for previous branch'complete -c wt -n '__fish_seen_subcommand_from remove' -f -a '(__wt_complete)' -d 'Worktree names or branches to remove (use '@' for current, defaults to current if none specified)'complete -c wt -n '__fish_seen_subcommand_from merge' -f -a '(__wt_complete)' -d 'Target branch to merge into (defaults to default branch)'complete -c wt -n '__fish_seen_subcommand_from completion' -f -a '(__wt_complete)' -d 'Shell to generate completions for'diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snapindex ca9235ac8..25f09aebe 100644--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap@@ -16,7 +16,7 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmptILqJ8/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpF1Pxjb/test-config.toml---success: trueexit_code: 0@@ -335,7 +335,7 @@ _arguments "${_arguments_options[@]}" : \'--verbose[Enable verbose output (show git commands and debug info)]' \'-h[Print help]' \'--help[Print help]' \-':branch -- Branch name, worktree path, or '\''@'\'' for current HEAD:_default' \+':branch -- Branch name, worktree path, '\''@'\'' for current HEAD, or '\''-'\'' for previous branch:_default' \&& ret=0;;(remove)diff --git a/tests/snapshots/integration__integration_tests__switch__switch_previous_branch.snap b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch.snapnew file mode 100644index 000000000..795af7083--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch.snap@@ -0,0 +1,28 @@+---+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/.tmpIWAEF9/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.snapnew file mode 100644index 000000000..397b7f32d--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_no_history.snap@@ -0,0 +1,26 @@+---+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/.tmpRhT5DU/test-config.toml+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+No previous branch found in reflog. Use 'wt list' to see available worktrees.