Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(switch): expose destination branch in pre-switch hooks (#1497)
worktrunk-bote47778d5b97a
diff --git a/docs/content/hook.md b/docs/content/hook.mdindex 35eacc57f..0a484eca5 100644--- a/docs/content/hook.md+++ b/docs/content/hook.md@@ -36,7 +36,7 @@ The most common starting point is `post-start` — it runs background tasks (dev## pre-switch-Runs before every `wt switch` — before branch validation or worktree creation. Useful for ensuring the repository is up to date before switching. Template variables reflect the current worktree (the source), not the destination. Failure aborts the switch.+Runs before every `wt switch` — before branch resolution or worktree creation. `{{ branch }}` is the destination branch argument as the user typed it (before resolution). Failure aborts the switch.```toml[pre-switch]diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.mdindex 3a3fac877..561b3055e 100644--- a/skills/worktrunk/reference/hook.md+++ b/skills/worktrunk/reference/hook.md@@ -27,7 +27,7 @@ The most common starting point is `post-start` — it runs background tasks (dev## pre-switch-Runs before every `wt switch` — before branch validation or worktree creation. Useful for ensuring the repository is up to date before switching. Template variables reflect the current worktree (the source), not the destination. Failure aborts the switch.+Runs before every `wt switch` — before branch resolution or worktree creation. `{{ branch }}` is the destination branch argument as the user typed it (before resolution). Failure aborts the switch.```toml[pre-switch]diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 3f876a84c..90142d810 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -1120,7 +1120,7 @@ The most common starting point is `post-start` — it runs background tasks (dev## pre-switch-Runs before every `wt switch` — before branch validation or worktree creation. Useful for ensuring the repository is up to date before switching. Template variables reflect the current worktree (the source), not the destination. Failure aborts the switch.+Runs before every `wt switch` — before branch resolution or worktree creation. `{{ branch }}` is the destination branch argument as the user typed it (before resolution). Failure aborts the switch.```toml[pre-switch]diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rsindex 512f76d09..3f081e05e 100644--- a/src/commands/handle_switch.rs+++ b/src/commands/handle_switch.rs@@ -34,20 +34,18 @@ pub struct SwitchOptions<'a> {pub verify: bool,}-/// Run pre-switch hooks before branch validation or worktree creation.+/// Run pre-switch hooks before branch resolution or worktree creation.///-/// Uses current worktree context since the destination is unknown at this point.+/// The hook context uses the **destination** branch argument as `{{ branch }}`,+/// so hooks receive the user's raw input before resolution.pub(crate) fn run_pre_switch_hooks(repo: &Repository,config: &UserConfig,+ target_branch: &str,yes: bool,) -> anyhow::Result<()> {- let current_branch = repo- .current_worktree()- .branch()- .context("Failed to determine current branch")?;let current_path = repo.current_worktree().path().to_path_buf();- let pre_ctx = CommandContext::new(repo, config, current_branch.as_deref(), ¤t_path, yes);+ let pre_ctx = CommandContext::new(repo, config, Some(target_branch), ¤t_path, yes);let pre_switch_approved = approve_hooks(&pre_ctx, &[HookType::PreSwitch])?;if pre_switch_approved {@@ -189,12 +187,6 @@ pub fn handle_switch(!config.resolved(project_id.as_deref()).switch.no_cd()});- // Run pre-switch hooks before anything else (before branch validation, planning, etc.)- // Skip when recovered — the source worktree is gone, nothing to run hooks against.- if verify && !is_recovered {- run_pre_switch_hooks(&repo, config, yes)?;- }-// Build switch suggestion context for enriching error hints with --execute/trailing args.// Without this, errors like "branch already exists" would suggest `wt switch <branch>`// instead of the full `wt switch <branch> --execute=<cmd> -- <args>`.@@ -206,7 +198,14 @@ pub fn handle_switch(}});- // Validate FIRST (before approval) - fails fast if branch doesn't exist, etc.+ // Run pre-switch hooks before branch resolution or worktree creation.+ // {{ branch }} receives the raw user input (before resolution).+ // Skip when recovered — the source worktree is gone, nothing to run hooks against.+ if verify && !is_recovered {+ run_pre_switch_hooks(&repo, config, branch, yes)?;+ }++ // Validate and resolve the target branch.let plan = plan_switch(&repo, branch, create, base, clobber, config).map_err(|err| {match suggestion_ctx {Some(ref ctx) => match err.downcast::<GitError>() {diff --git a/src/commands/select/mod.rs b/src/commands/select/mod.rsindex f7615e9ba..bd09b07cd 100644--- a/src/commands/select/mod.rs+++ b/src/commands/select/mod.rs@@ -387,10 +387,11 @@ pub fn handle_select(};let config = repo.user_config();- // Run pre-switch hooks before anything else (before branch validation, planning, etc.)+ // Run pre-switch hooks before branch resolution or worktree creation.+ // {{ branch }} receives the raw user input (before resolution).// Skip when recovered — the source worktree is gone, nothing to run hooks against.if !is_recovered {- run_pre_switch_hooks(&repo, config, true)?;+ run_pre_switch_hooks(&repo, config, &identifier, true)?;}// Switch to existing worktree or create new onediff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex 09b738836..86e3c9e2b 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -1913,6 +1913,39 @@ check = "echo 'MANUAL_PRE_SWITCH' > pre_switch_marker.txt");}+/// Test that `{{ branch }}` in pre-switch hooks is the destination branch argument, not the source.+#[rstest]+fn test_user_pre_switch_branch_var_is_destination(mut repo: TestRepo) {+ let _feature_wt = repo.add_worktree("feature-dest");++ // Write pre-switch hook that records {{ branch }} into a marker file+ repo.write_test_config(+ r#"[pre-switch]+check = "echo '{{ branch }}' > pre_switch_branch.txt"+"#,+ );++ snapshot_switch(+ "user_pre_switch_branch_destination",+ &repo,+ &["feature-dest"],+ );++ // {{ branch }} should be the destination branch, not the source (main)+ let marker_file = repo.root_path().join("pre_switch_branch.txt");+ assert!(+ marker_file.exists(),+ "Pre-switch hook should have created marker"+ );+ let contents = fs::read_to_string(&marker_file).unwrap();+ assert_eq!(+ contents.trim(),+ "feature-dest",+ "{{{{ branch }}}} should be the destination branch 'feature-dest', got: '{}'",+ contents.trim(),+ );+}+/// When removing the current worktree, post-switch hooks should fire/// because the user is implicitly switched back to the primary worktree./// Regression test for https://github.com/max-sixty/worktrunk/issues/1450diff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_pre_switch_branch_destination.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_switch_branch_destination.snapnew file mode 100644index 000000000..e70246bcb--- /dev/null+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_switch_branch_destination.snap@@ -0,0 +1,48 @@+---+source: tests/integration_tests/user_hooks.rs+info:+ program: wt+ args:+ - switch+ - feature-dest+ 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]"+ NO_COLOR: ""+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[36m◎[39m [36mRunning pre-switch [1muser:check[22m[39m+[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'feature-dest'[0m[2m [0m[2m[36m>[0m[2m pre_switch_branch.txt+[0m[33m▲[39m [33mWorktree for [1mfeature-dest[22m @ [1m_REPO_.feature-dest[22m, but cannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [4mwt config shell install[24m[22m