Skip to content

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

feat(switch): add --no-cd flag to skip directory change (#932)

Maximilian Roos4e6956a82fdd
diff --git a/.claude-plugin/skills/worktrunk/reference/switch.md b/.claude-plugin/skills/worktrunk/reference/switch.md
index 4e2312469..7f1b45dd4 100644
--- a/.claude-plugin/skills/worktrunk/reference/switch.md
+++ b/.claude-plugin/skills/worktrunk/reference/switch.md
@@ -190,6 +190,12 @@ Usage: <b><span class=c>wt switch</span></b> <span class=c>[OPTIONS]</span> <spa
<b><span class=c>--clobber</span></b>
Remove stale paths at target
+ <b><span class=c>--no-cd</span></b>
+ Skip directory change after switching
+
+ Hooks still run normally. Useful when hooks handle navigation (e.g.,
+ tmux workflows) or for CI/automation.
+
<b><span class=c>--no-verify</span></b>
Skip hooks
diff --git a/docs/content/switch.md b/docs/content/switch.md
index e439db413..7caf5a29e 100644
--- a/docs/content/switch.md
+++ b/docs/content/switch.md
@@ -219,6 +219,12 @@ Usage: <b><span class=c>wt switch</span></b> <span class=c>[OPTIONS]</span> <spa
<b><span class=c>--clobber</span></b>
Remove stale paths at target
+ <b><span class=c>--no-cd</span></b>
+ Skip directory change after switching
+
+ Hooks still run normally. Useful when hooks handle navigation (e.g.,
+ tmux workflows) or for CI/automation.
+
<b><span class=c>--no-verify</span></b>
Skip hooks
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 276c6d0ce..52ed4e8eb 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -450,6 +450,13 @@ To change which branch a worktree is on, use `git switch` inside that worktree.
#[arg(long, requires = "branch")]
clobber: bool,
+ /// Skip directory change after switching
+ ///
+ /// Hooks still run normally. Useful when hooks handle navigation
+ /// (e.g., tmux workflows) or for CI/automation.
+ #[arg(long)]
+ no_cd: bool,
+
/// Skip hooks
#[arg(long = "no-verify", action = clap::ArgAction::SetFalse, default_value_t = true)]
verify: bool,
diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rs
index 6dfe0e6aa..76a26a03a 100644
--- a/src/commands/handle_switch.rs
+++ b/src/commands/handle_switch.rs
@@ -25,6 +25,8 @@ pub struct SwitchOptions<'a> {
pub execute_args: &'a [String],
pub yes: bool,
pub clobber: bool,
+ /// Whether to change directory after switching (default: true)
+ pub change_dir: bool,
pub verify: bool,
}
@@ -42,6 +44,7 @@ pub fn handle_switch(
execute_args,
yes,
clobber,
+ change_dir,
verify,
} = opts;
@@ -100,7 +103,7 @@ pub fn handle_switch(
// Show success message (temporal locality: immediately after worktree operation)
// Returns path to display in hooks when user's shell won't be in the worktree
// Also shows worktree-path hint on first --create (before shell integration warning)
- let hooks_display_path = handle_switch_output(&result, &branch_info)?;
+ let hooks_display_path = handle_switch_output(&result, &branch_info, change_dir)?;
// Offer shell integration if not already installed/active
// (only shows prompt/hint when shell integration isn't working)
diff --git a/src/commands/select/mod.rs b/src/commands/select/mod.rs
index 4f0595595..76a570235 100644
--- a/src/commands/select/mod.rs
+++ b/src/commands/select/mod.rs
@@ -244,7 +244,8 @@ pub fn handle_select(
execute!(stderr(), crossterm::cursor::MoveTo(0, 0))?;
// Show success message; emit cd directive if shell integration is active
- handle_switch_output(&result, &branch_info)?;
+ // Interactive picker always performs cd (change_dir: true)
+ handle_switch_output(&result, &branch_info, true)?;
}
Ok(())
diff --git a/src/main.rs b/src/main.rs
index 077b1ce1e..c867d0aea 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -732,6 +732,7 @@ fn main() {
execute_args,
yes,
clobber,
+ no_cd,
verify,
} => UserConfig::load()
.context("Failed to load config")
@@ -786,6 +787,7 @@ fn main() {
execute_args: &execute_args,
yes,
clobber,
+ change_dir: !no_cd,
verify,
},
&mut config,
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index c22beb5eb..14051b9d7 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -305,20 +305,28 @@ fn print_switch_message_if_changed(
/// **Message order for Created:** Success message first, then warning. Creation
/// is a real accomplishment, but users still need to know they won't cd there.
///
+/// # Arguments
+///
+/// * `change_dir` — When false, skip the directory change (user requested `--no-cd`)
+///
/// # Return Value
///
/// Returns `Some(path)` when post-switch hooks should show "@ path" in their
/// announcements (because the user's shell won't be in that directory). This happens when:
/// - Shell integration is not active (user's shell stays in original directory)
+/// - `change_dir` is false (user explicitly requested no directory change)
///
/// Returns `None` when the user will be in the worktree directory (shell integration
/// active or already at the worktree), so no path annotation needed.
pub fn handle_switch_output(
result: &SwitchResult,
branch_info: &SwitchBranchInfo,
+ change_dir: bool,
) -> anyhow::Result<Option<std::path::PathBuf>> {
// Set target directory for command execution
- super::change_directory(result.path())?;
+ if change_dir {
+ super::change_directory(result.path())?;
+ }
let path = result.path();
let path_display = format_path_for_display(path);
@@ -329,8 +337,9 @@ pub fn handle_switch_output(
// Compute shell warning reason once (only if we'll need it)
// Git subcommand case is special — needs a hint after the warning
+ // With --no-cd: no warning (user explicitly requested no cd), but hooks still get path
let is_git_subcommand = crate::is_git_subcommand();
- let shell_warning_reason: Option<String> = if is_shell_integration_active {
+ let shell_warning_reason: Option<String> = if !change_dir || is_shell_integration_active {
None
} else if is_git_subcommand {
Some("ran git wt; running through git prevents cd".to_string())
@@ -338,6 +347,10 @@ pub fn handle_switch_output(
Some(compute_shell_warning_reason())
};
+ // When not changing directory, user won't be in the worktree (unless already there)
+ // Used to determine if hooks should show "@ path" annotation
+ let user_wont_be_in_worktree = !change_dir || shell_warning_reason.is_some();
+
// Compute branch-worktree mismatch warning (shown before action messages)
let branch_worktree_mismatch_warning = branch_info
.expected_path
@@ -381,10 +394,8 @@ pub fn handle_switch_output(
} else if should_show_explicit_path_hint() {
eprintln!("{}", hint_message(explicit_path_hint(branch)));
}
- // User won't be there - show path in hook announcements
- Some(path.clone())
} else {
- // Shell integration active — user actually switched
+ // Shell integration active or --no-cd — user switched (or chose not to cd)
// Show path mismatch warning first - discovered while evaluating the switch
if let Some(warning) = branch_worktree_mismatch_warning {
eprintln!("{}", warning);
@@ -397,7 +408,11 @@ pub fn handle_switch_output(
None, None,
))
);
- // cd will happen - no path annotation needed
+ }
+ // Return path for hook annotations if user won't be in the worktree
+ if user_wont_be_in_worktree {
+ Some(path.clone())
+ } else {
None
}
}
@@ -435,7 +450,7 @@ pub fn handle_switch_output(
}
}
- // Warn if shell won't cd to the new worktree
+ // Warn if shell won't cd to the new worktree (but not for --no-cd)
// (--execute command display is handled by execute_user_command)
if let Some(reason) = shell_warning_reason {
// Don't repeat "Created worktree" — success message above already said that
@@ -450,10 +465,11 @@ pub fn handle_switch_output(
} else if should_show_explicit_path_hint() {
eprintln!("{}", hint_message(explicit_path_hint(branch)));
}
- // User won't be there - show path in hook announcements
+ }
+ // Return path for hook annotations if user won't be in the worktree
+ if user_wont_be_in_worktree {
Some(path.clone())
} else {
- // cd will happen - no path annotation needed
None
}
// Note: No branch_worktree_mismatch_warning — created worktrees are always at
diff --git a/tests/integration_tests/directives.rs b/tests/integration_tests/directives.rs
index cb8e4c906..176cc687a 100644
--- a/tests/integration_tests/directives.rs
+++ b/tests/integration_tests/directives.rs
@@ -4,6 +4,7 @@ use crate::common::{
};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
+use std::fs;
// ============================================================================
// Directive File Tests
@@ -93,6 +94,132 @@ fn test_remove_directive_file(#[from(repo_with_remote)] mut repo: TestRepo) {
});
}
+// ============================================================================
+// --no-cd Tests
+// ============================================================================
+// These tests verify that --no-cd suppresses directory changes
+
+#[rstest]
+fn test_switch_no_cd_suppresses_directive(#[from(repo_with_remote)] mut repo: TestRepo) {
+ let _feature_wt = repo.add_worktree("feature");
+ let (directive_path, _guard) = directive_file();
+
+ let settings = setup_snapshot_settings(&repo);
+
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ configure_directive_file(&mut cmd, &directive_path);
+ cmd.args(["switch", "feature", "--no-cd"])
+ .current_dir(repo.root_path());
+
+ assert_cmd_snapshot!(cmd);
+
+ // Verify directive file does NOT contain cd command
+ let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ assert!(
+ !directives.contains("cd '"),
+ "Directive file should NOT contain cd command with --no-cd, got: {}",
+ directives
+ );
+ });
+}
+
+#[rstest]
+fn test_switch_no_cd_create_suppresses_directive(#[from(repo_with_remote)] repo: TestRepo) {
+ let (directive_path, _guard) = directive_file();
+
+ let settings = setup_snapshot_settings(&repo);
+
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ configure_directive_file(&mut cmd, &directive_path);
+ cmd.args(["switch", "--create", "new-feature", "--no-cd"])
+ .current_dir(repo.root_path());
+
+ assert_cmd_snapshot!(cmd);
+
+ // Verify directive file does NOT contain cd command
+ let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ assert!(
+ !directives.contains("cd '"),
+ "Directive file should NOT contain cd command with --no-cd, got: {}",
+ directives
+ );
+ });
+}
+
+#[rstest]
+fn test_switch_no_cd_hooks_show_path_annotation(#[from(repo_with_remote)] repo: TestRepo) {
+ let (directive_path, _guard) = directive_file();
+
+ // Create project config with a post-switch hook
+ let config_dir = repo.root_path().join(".config");
+ fs::create_dir_all(&config_dir).unwrap();
+ fs::write(
+ config_dir.join("wt.toml"),
+ "post-switch = \"echo switched\"\n",
+ )
+ .unwrap();
+
+ repo.commit("Add config");
+
+ let settings = setup_snapshot_settings(&repo);
+
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ configure_directive_file(&mut cmd, &directive_path);
+ // Use --yes to auto-approve the hook command
+ cmd.args(["switch", "--create", "hook-test", "--no-cd", "--yes"])
+ .current_dir(repo.root_path());
+
+ assert_cmd_snapshot!(cmd);
+
+ // Verify directive file does NOT contain cd command
+ let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ assert!(
+ !directives.contains("cd '"),
+ "Directive file should NOT contain cd command with --no-cd, got: {}",
+ directives
+ );
+ });
+}
+
+#[rstest]
+fn test_switch_no_cd_execute_runs_in_target_worktree(#[from(repo_with_remote)] repo: TestRepo) {
+ let (directive_path, _guard) = directive_file();
+
+ let settings = setup_snapshot_settings(&repo);
+
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ configure_directive_file(&mut cmd, &directive_path);
+ // pwd should print the target worktree path, even with --no-cd
+ cmd.args([
+ "switch",
+ "--create",
+ "exec-test",
+ "--no-cd",
+ "--execute",
+ "pwd",
+ ])
+ .current_dir(repo.root_path());
+
+ assert_cmd_snapshot!(cmd);
+
+ // Verify directive file does NOT contain cd command
+ let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ assert!(
+ !directives.contains("cd '"),
+ "Directive file should NOT contain cd command with --no-cd, got: {}",
+ directives
+ );
+ });
+}
+
// ============================================================================
// Non-Directive Mode Tests (no WORKTRUNK_DIRECTIVE_FILE)
// ============================================================================
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_create_suppresses_directive.snap b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_create_suppresses_directive.snap
new file mode 100644
index 000000000..47380f803
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_create_suppresses_directive.snap
@@ -0,0 +1,45 @@
+---
+source: tests/integration_tests/directives.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - new-feature
+ - "--no-cd"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Created branch new-feature from main and worktree @ _REPO_.new-feature
+↳ To customize worktree locations, run wt config create
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_runs_in_target_worktree.snap b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_runs_in_target_worktree.snap
new file mode 100644
index 000000000..b97371191
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_runs_in_target_worktree.snap
@@ -0,0 +1,49 @@
+---
+source: tests/integration_tests/directives.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - exec-test
+ - "--no-cd"
+ - "--execute"
+ - pwd
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Created branch exec-test from main and worktree @ _REPO_.exec-test
+↳ To customize worktree locations, run wt config create
+◎ Executing (--execute) @ _REPO_.exec-test:
+  pwd
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_hooks_show_path_annotation.snap b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_hooks_show_path_annotation.snap
new file mode 100644
index 000000000..d918038bc
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_hooks_show_path_annotation.snap
@@ -0,0 +1,47 @@
+---
+source: tests/integration_tests/directives.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - hook-test
+ - "--no-cd"
+ - "--yes"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Created branch hook-test from main and worktree @ _REPO_.hook-test
+↳ To customize worktree locations, run wt config create
+◎ Running post-switch: project @ _REPO_.hook-test
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_suppresses_directive.snap b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_suppresses_directive.snap
new file mode 100644
index 000000000..84a837052
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_suppresses_directive.snap
@@ -0,0 +1,43 @@
+---
+source: tests/integration_tests/directives.rs
+info:
+ program: wt
+ args:
+ - switch
+ - feature
+ - "--no-cd"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+○ Switched to worktree for feature @ _REPO_.feature
diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
index 6d1e5cc18..8c39e5012 100644
--- a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
@@ -81,6 +81,11 @@ Usage: wt switch [OPTIONS] [BRANCH] [--
--clobber
Remove stale paths at target
+ --no-cd
+ Skip directory change after switching
+
+ Hooks still run normally. Useful when hooks handle navigation (e.g., tmux workflows) or for CI/automation.
+
--no-verify
Skip hooks
diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_short.snap b/tests/snapshots/integration__integration_tests__help__help_switch_short.snap
index 72fcb6e4b..bd944bfec 100644
--- a/tests/snapshots/integration__integration_tests__help__help_switch_short.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_switch_short.snap
@@ -43,6 +43,7 @@ Usage: wt switch [OPTIONS] [BRANCH] [--
-x, --execute <EXECUTE> Command to run after switch
-y, --yes Skip approval prompts
--clobber Remove stale paths at target
+ --no-cd Skip directory change after switching
--no-verify Skip hooks
-h, --help Print help (see more with '--help')