Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Show path annotation in post-switch hooks when shell integration not active (#376)
Maximilian Roos17d630a628e1
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 0d2774c6b..fa823e92b 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -853,7 +853,13 @@ impl<'a> CommandContext<'a> {/// Spawn post-switch commands in parallel as background processes (non-blocking)////// Runs on every switch, including to existing worktrees and newly created ones.- pub fn spawn_post_switch_commands(&self) -> anyhow::Result<()> {+ ///+ /// `display_path`: When `Some`, shows the path in hook announcements. Pass this when+ /// the user's shell won't be in the worktree (shell integration not active).+ pub fn spawn_post_switch_commands(+ &self,+ display_path: Option<&std::path::Path>,+ ) -> anyhow::Result<()> {let project_config = self.repo.load_project_config()?;let commands = prepare_hook_commands(@@ -865,7 +871,7 @@ impl<'a> CommandContext<'a> {HookType::PostSwitch,&[],None,- None, // No path display - running in expected directory+ display_path,)?;spawn_hook_commands_background(self, commands, HookType::PostSwitch)diff --git a/src/main.rs b/src/main.rsindex 0d4c61a01..760b65dfd 100644--- a/src/main.rs+++ b/src/main.rs@@ -1172,7 +1172,9 @@ fn main() {)?;// Show success message (temporal locality: immediately after worktree operation)- handle_switch_output(&result, &branch_info, execute.as_deref())?;+ // Returns path to display in hooks when user's shell won't be in the worktree+ let hooks_display_path =+ handle_switch_output(&result, &branch_info, execute.as_deref())?;// Offer shell integration if not already installed/active// (only shows prompt/hint when shell integration isn't working)@@ -1185,7 +1187,7 @@ fn main() {}// Spawn background hooks after success message- // - post-switch: runs on ALL switches (Created, Existing, AlreadyAt)+ // - post-switch: runs on ALL switches (shows "@ path" when shell won't be there)// - post-start: runs only when creating a NEW worktreeif !skip_hooks {let repo = Repository::current();@@ -1200,7 +1202,7 @@ fn main() {);// Post-switch runs first (immediate "I'm here" signal)- ctx.spawn_post_switch_commands()?;+ ctx.spawn_post_switch_commands(hooks_display_path.as_deref())?;// Post-start runs only on creation (setup tasks)if matches!(&result, SwitchResult::Created { .. }) {diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex f45cff48b..fcfb1134a 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -599,11 +599,18 @@ fn print_switch_message_if_changed(////// For created worktrees: success message only (creation success trumps the/// shell warning, and post-create hooks provide value even without cd).+///+/// 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)+///+/// 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,execute_command: Option<&str>,-) -> anyhow::Result<()> {+) -> anyhow::Result<Option<std::path::PathBuf>> {// Set target directory for command executionsuper::change_directory(result.path())?;@@ -622,7 +629,12 @@ pub fn handle_switch_output())});- match result {+ // Track whether user's shell will be in the worktree directory.+ // If not, hooks should show "@ path" to clarify where they run.+ // Note: --execute runs commands in the worktree but doesn't move the user's shell there+ let user_will_be_there = is_shell_integration_active;++ let display_path_for_hooks = match result {SwitchResult::AlreadyAt(_) => {super::print(info_message(cformat!("Already on worktree for <bold>{branch}</> @ <bold>{path_display}</>"@@ -630,9 +642,11 @@ pub fn handle_switch_output(if let Some(warning) = path_mismatch_warning {super::print(warning)?;}+ // User is already there - no path annotation needed+ None}SwitchResult::Existing(_) => {- if is_shell_integration_active {+ if user_will_be_there {// Shell integration active — cd will happen automaticallysuper::print(info_message(format_switch_message(branch, path, false, None, None,@@ -640,6 +654,8 @@ pub fn handle_switch_output(if let Some(warning) = path_mismatch_warning {super::print(warning)?;}+ // cd will happen - no path annotation needed+ None} else {// Shell integration not active — warn that shell won't cdlet reason = if Shell::is_integration_configured(&crate::binary_name())@@ -666,6 +682,8 @@ pub fn handle_switch_output(if let Some(warning) = path_mismatch_warning {super::print(warning)?;}+ // User won't be there - show path in hook announcements+ Some(path.clone())}}SwitchResult::Created {@@ -681,11 +699,17 @@ pub fn handle_switch_output(base_branch.as_deref(),from_remote.as_deref(),)))?;+ // If shell integration not active, show path in hook announcements+ if user_will_be_there {+ None+ } else {+ Some(path.clone())+ }}- }+ };super::flush()?;- Ok(())+ Ok(display_path_for_hooks)}/// Execute the --execute command after hooks have run@@ -862,7 +886,8 @@ fn spawn_post_switch_after_remove(&repo_root,false, // force=false for CommandContext);- ctx.spawn_post_switch_commands()+ // No display_path needed - changed_directory is true, so user's shell IS going there+ ctx.spawn_post_switch_commands(None)}/// Handle output for RemovedWorktree removaldiff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex f07a4d1fc..abc20fd84 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -864,6 +864,63 @@ fn test_switch_clobber_error_backup_exists(repo: TestRepo) {assert!(backup_path.exists());}+/// Test that post-switch hooks show "@ path" annotation when shell integration is not active.+///+/// When the user runs `wt` directly (not through shell wrapper), their shell won't+/// cd to the worktree directory. Hooks should show "@ path" to clarify where they run.+#[rstest]+fn test_switch_post_hook_shows_path_without_shell_integration(repo: TestRepo) {+ use std::fs;++ // 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");++ // Run switch WITHOUT directive file (shell integration not active)+ // Use --yes to auto-approve the hook command+ // The hook output should show "@ path" annotation+ snapshot_switch(+ "switch_post_hook_path_annotation",+ &repo,+ &["--create", "post-hook-test", "--yes"],+ );+}++/// Test that post-switch hooks do NOT show "@ path" when shell integration is active.+///+/// When running through the shell wrapper (directive file set), the user's shell will+/// actually cd to the worktree. Hooks don't need the path annotation.+#[rstest]+fn test_switch_post_hook_no_path_with_shell_integration(repo: TestRepo) {+ use std::fs;++ // 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");++ // Run switch WITH directive file (shell integration active)+ // The hook output should NOT show "@ path" annotation+ snapshot_switch_with_directive_file(+ "switch_post_hook_no_path_with_shell_integration",+ &repo,+ &["--create", "post-hook-shell-test", "--yes"],+ );+}+/// Test --clobber handles paths with extensions correctly#[rstest]fn test_switch_clobber_path_with_extension(repo: TestRepo) {diff --git a/tests/snapshots/integration__integration_tests__switch__switch_post_hook_no_path_with_shell_integration.snap b/tests/snapshots/integration__integration_tests__switch__switch_post_hook_no_path_with_shell_integration.snapnew file mode 100644index 000000000..9c2fb69ff--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_post_hook_no_path_with_shell_integration.snap@@ -0,0 +1,39 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - post-hook-shell-test+ - "--yes"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ 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+ PATH: "[PATH]"+ RUST_LOG: warn+ SOURCE_DATE_EPOCH: "1735776000"+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[32m✓[39m [32mCreated new worktree for [1mpost-hook-shell-test[22m from [1mmain[22m @ [1m_REPO_.post-hook-shell-test[22m[39m+[36m◎[39m [36mRunning post-switch project hook:[39m+[107m [0m [2m[0m[2m[34mecho[0m[2m switcheddiff --git a/tests/snapshots/integration__integration_tests__switch__switch_post_hook_path_annotation.snap b/tests/snapshots/integration__integration_tests__switch__switch_post_hook_path_annotation.snapnew file mode 100644index 000000000..5c39d1943--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_post_hook_path_annotation.snap@@ -0,0 +1,39 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - post-hook-test+ - "--yes"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ 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+ PATH: "[PATH]"+ RUST_LOG: warn+ SOURCE_DATE_EPOCH: "1735776000"+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[32m✓[39m [32mCreated new worktree for [1mpost-hook-test[22m from [1mmain[22m @ [1m_REPO_.post-hook-test[22m[39m+[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22m+[36m◎[39m [36mRunning post-switch project hook @ [1m_REPO_.post-hook-test[22m:[39m+[107m [0m [2m[0m[2m[34mecho[0m[2m switched