Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: add directional template vars to all two-worktree hooks (#1655)
Maximilian Roos113a2dd940d4
diff --git a/docs/content/hook.md b/docs/content/hook.mdindex 7157ebdcc..31af8ab11 100644--- a/docs/content/hook.md+++ b/docs/content/hook.md@@ -216,11 +216,13 @@ Hooks can use template variables that expand at runtime:| `{{ upstream }}` | Upstream tracking branch (if set) || `{{ hook_type }}` | Hook type being run (e.g. `post-create`, `pre-merge`) || `{{ hook_name }}` | Hook command name (if named) |-| `{{ target }}` | Target branch (merge hooks only) |-| `{{ base }}` | Base branch (creation hooks only) |-| `{{ base_worktree_path }}` | Base branch worktree (creation hooks only) |+| `{{ target }}` | Target branch (merge, remove, and switch hooks) |+| `{{ target_worktree_path }}` | Target worktree path (merge, remove, and switch hooks) |+| `{{ base }}` | Base/source branch (creation and switch hooks) |+| `{{ base_worktree_path }}` | Base/source worktree path (creation and switch hooks) |+| `{{ cwd }}` | Hook execution directory (always exists on disk) |-Some variables may not be defined: `upstream` is only set when the branch tracks a remote; `hook_name` is only set for named commands; `target`, `base`, and `base_worktree_path` are hook-specific. Using an undefined variable directly errors — use conditionals for optional behavior:+Some variables may not be defined: `upstream` is only set when the branch tracks a remote; `hook_name` is only set for named commands; directional variables (`target`, `target_worktree_path`, `base`, `base_worktree_path`) are only available in two-worktree hooks. Using an undefined variable directly errors — use conditionals for optional behavior:```toml[post-create]diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.mdindex 199ae81b1..00022c8e0 100644--- a/skills/worktrunk/reference/hook.md+++ b/skills/worktrunk/reference/hook.md@@ -207,11 +207,13 @@ Hooks can use template variables that expand at runtime:| `{{ upstream }}` | Upstream tracking branch (if set) || `{{ hook_type }}` | Hook type being run (e.g. `post-create`, `pre-merge`) || `{{ hook_name }}` | Hook command name (if named) |-| `{{ target }}` | Target branch (merge hooks only) |-| `{{ base }}` | Base branch (creation hooks only) |-| `{{ base_worktree_path }}` | Base branch worktree (creation hooks only) |+| `{{ target }}` | Target branch (merge, remove, and switch hooks) |+| `{{ target_worktree_path }}` | Target worktree path (merge, remove, and switch hooks) |+| `{{ base }}` | Base/source branch (creation and switch hooks) |+| `{{ base_worktree_path }}` | Base/source worktree path (creation and switch hooks) |+| `{{ cwd }}` | Hook execution directory (always exists on disk) |-Some variables may not be defined: `upstream` is only set when the branch tracks a remote; `hook_name` is only set for named commands; `target`, `base`, and `base_worktree_path` are hook-specific. Using an undefined variable directly errors — use conditionals for optional behavior:+Some variables may not be defined: `upstream` is only set when the branch tracks a remote; `hook_name` is only set for named commands; directional variables (`target`, `target_worktree_path`, `base`, `base_worktree_path`) are only available in two-worktree hooks. Using an undefined variable directly errors — use conditionals for optional behavior:```toml[post-create]diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 4530b6b55..48d38ccbe 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -1303,11 +1303,13 @@ Hooks can use template variables that expand at runtime:| `{{ upstream }}` | Upstream tracking branch (if set) || `{{ hook_type }}` | Hook type being run (e.g. `post-create`, `pre-merge`) || `{{ hook_name }}` | Hook command name (if named) |-| `{{ target }}` | Target branch (merge hooks only) |-| `{{ base }}` | Base branch (creation hooks only) |-| `{{ base_worktree_path }}` | Base branch worktree (creation hooks only) |+| `{{ target }}` | Target branch (merge, remove, and switch hooks) |+| `{{ target_worktree_path }}` | Target worktree path (merge, remove, and switch hooks) |+| `{{ base }}` | Base/source branch (creation and switch hooks) |+| `{{ base_worktree_path }}` | Base/source worktree path (creation and switch hooks) |+| `{{ cwd }}` | Hook execution directory (always exists on disk) |-Some variables may not be defined: `upstream` is only set when the branch tracks a remote; `hook_name` is only set for named commands; `target`, `base`, and `base_worktree_path` are hook-specific. Using an undefined variable directly errors — use conditionals for optional behavior:+Some variables may not be defined: `upstream` is only set when the branch tracks a remote; `hook_name` is only set for named commands; directional variables (`target`, `target_worktree_path`, `base`, `base_worktree_path`) are only available in two-worktree hooks. Using an undefined variable directly errors — use conditionals for optional behavior:```toml[post-create]diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex d54bd658a..c3d34e60e 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -134,7 +134,14 @@ pub fn build_hook_context(}}- // Add extra vars (e.g., target branch for merge)+ // Execution directory — always where the hook command runs, even when+ // worktree_path points to an Active identity that doesn't exist on disk.+ map.insert(+ "cwd".into(),+ to_posix_path(&ctx.worktree_path.to_string_lossy()),+ );++ // Add extra vars (e.g., target branch for merge, base for switch)for (k, v) in extra_vars {map.insert((*k).into(), (*v).into());}diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rsindex 0c80c4564..f38adc4b7 100644--- a/src/commands/handle_switch.rs+++ b/src/commands/handle_switch.rs@@ -38,21 +38,43 @@ pub struct SwitchOptions<'a> {////// The hook context uses the **destination** branch argument as `{{ branch }}`,/// so hooks receive the user's raw input before resolution.+///+/// Directional vars:+/// - `base` / `base_worktree_path`: current (source) branch and worktree+/// - `target` / `target_worktree_path`: destination branch and worktree (if it exists)pub(crate) fn run_pre_switch_hooks(repo: &Repository,config: &UserConfig,target_branch: &str,yes: bool,) -> anyhow::Result<()> {- let current_path = repo.current_worktree().path().to_path_buf();+ let current_wt = repo.current_worktree();+ let current_path = current_wt.path().to_path_buf();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 {+ // Base vars: source (where the user currently is)+ let base_branch = current_wt.branch().ok().flatten().unwrap_or_default();+ let base_path_str = worktrunk::path::to_posix_path(¤t_path.to_string_lossy());++ let mut extra_vars: Vec<(&str, &str)> = vec![+ ("base", &base_branch),+ ("base_worktree_path", &base_path_str),+ ];++ // Target vars: destination (if the worktree already exists)+ let dest_path = repo.worktree_for_branch(target_branch).ok().flatten();+ let dest_path_str = dest_path.map(|p| worktrunk::path::to_posix_path(&p.to_string_lossy()));+ if let Some(ref p) = dest_path_str {+ extra_vars.push(("target", target_branch));+ extra_vars.push(("target_worktree_path", p));+ }+execute_hook(&pre_ctx,HookType::PreSwitch,- &[],+ &extra_vars,HookFailureStrategy::FailFast,None,crate::output::pre_hook_display_path(pre_ctx.worktree_path),diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 8e2aeaef4..3878bf262 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -214,14 +214,24 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {false // Already rebased, no rebase occurred};+ // Target worktree path for template variables (pre-merge and post-merge hooks).+ // Computed once here so both hook sites can reference it.+ let target_wt_path_str = target_worktree_path+ .as_deref()+ .map(|p| worktrunk::path::to_posix_path(&p.to_string_lossy()));+// Run pre-merge checks unless --no-verify was specified// Do this after commit/squash/rebase to validate the final state that will be pushedif verify {let ctx = env.context(yes);+ let mut extra: Vec<(&str, &str)> = vec![("target", target_branch.as_str())];+ if let Some(ref p) = target_wt_path_str {+ extra.push(("target_worktree_path", p));+ }execute_hook(&ctx,HookType::PreMerge,- &[("target", target_branch.as_str())],+ &extra,HookFailureStrategy::FailFast,None,crate::output::pre_hook_display_path(ctx.worktree_path),@@ -312,10 +322,14 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {// or worktree preserved so they stay in feature)crate::output::pre_hook_display_path(&destination_path)};+ let mut extra: Vec<(&str, &str)> = vec![("target", target_branch.as_str())];+ if let Some(ref p) = target_wt_path_str {+ extra.push(("target_worktree_path", p));+ }execute_hook(&ctx,HookType::PostMerge,- &[("target", target_branch.as_str())],+ &extra,HookFailureStrategy::Warn,None,display_path,diff --git a/src/commands/worktree/hooks.rs b/src/commands/worktree/hooks.rsindex 08ed8d9f2..a7c0ee3dc 100644--- a/src/commands/worktree/hooks.rs+++ b/src/commands/worktree/hooks.rs@@ -69,6 +69,11 @@ impl<'a> CommandContext<'a> {} else {commit};+ // Target vars: where the user ends up after removal (primary worktree).+ // self.worktree_path is the CommandContext's path, set to main_path by the caller.+ let target_path_str = to_posix_path(&self.worktree_path.to_string_lossy());+ let target_branch = self.branch_or_head();+let extra_vars: Vec<(&str, &str)> = vec![("branch", removed_branch),("worktree_path", &worktree_path_str),@@ -76,6 +81,8 @@ impl<'a> CommandContext<'a> {("worktree_name", worktree_name),("commit", commit),("short_commit", short_commit),+ ("target", target_branch),+ ("target_worktree_path", &target_path_str),];let user_hooks = self.config.hooks(self.project_id().as_deref());diff --git a/src/config/expansion.rs b/src/config/expansion.rsindex 9a89e416b..726213a47 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -41,11 +41,13 @@ pub const TEMPLATE_VARS: &[&str] = &["remote","remote_url","upstream",- "hook_type", // Added by expand_commands / expand_command_template+ "hook_type", // Added by expand_commands / expand_command_template"hook_name", // Added by expand_commands / expand_command_template (named commands only)- "target", // Added by merge/rebase hooks via extra_vars- "base", // Added by creation hooks via extra_vars- "base_worktree_path", // Added by creation hooks via extra_vars+ "target", // Added by merge/remove hooks via extra_vars+ "target_worktree_path", // Added by merge/remove hooks via extra_vars+ "base", // Added by creation/switch hooks via extra_vars+ "base_worktree_path", // Added by creation/switch hooks via extra_vars+ "cwd", // Execution directory (always exists on disk)];/// Deprecated template variable aliases (still valid for backward compatibility).diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex fb8654044..f62b0325a 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -1084,10 +1084,22 @@ fn handle_removed_worktree_output(ctx: RemovedWorktreeOutputContext<'_>) -> anyh} else {Some(worktree_path) // Show path when user is elsewhere};+ // Target vars: where the user will end up after removal+ let target_branch = repo+ .worktree_at(main_path)+ .branch()+ .ok()+ .flatten()+ .unwrap_or_default();+ let target_path_str = worktrunk::path::to_posix_path(&main_path.to_string_lossy());+ let extra_vars: Vec<(&str, &str)> = vec![+ ("target", &target_branch),+ ("target_worktree_path", &target_path_str),+ ];execute_hook(&ctx,worktrunk::HookType::PreRemove,- &[],+ &extra_vars,HookFailureStrategy::FailFast,None,display_path,diff --git a/tests/snapshots/integration__integration_tests__eval__eval_dry_run.snap b/tests/snapshots/integration__integration_tests__eval__eval_dry_run.snapindex 8feb8fc41..15b0f5659 100644--- a/tests/snapshots/integration__integration_tests__eval__eval_dry_run.snap+++ b/tests/snapshots/integration__integration_tests__eval__eval_dry_run.snap@@ -46,6 +46,7 @@ exit_code: 0----- stderr -----branch=maincommit=05a4a45d0b981dad5c27db59dca482836d59f89e+cwd=_REPO_default_branch=mainmain_worktree=repomain_worktree_path=_REPO_diff --git a/tests/snapshots/integration__integration_tests__eval__eval_template_error.snap b/tests/snapshots/integration__integration_tests__eval__eval_template_error.snapindex 598fff190..ea3f3a70f 100644--- a/tests/snapshots/integration__integration_tests__eval__eval_template_error.snap+++ b/tests/snapshots/integration__integration_tests__eval__eval_template_error.snap@@ -45,4 +45,4 @@ exit_code: 1----- stderr -----[31m✗[39m [31mFailed to expand eval: undefined value @ line 1[39m[107m [0m {{ undefined_var }}-[2m↳[22m [2mAvailable variables: [4mbranch, commit, default_branch, main_worktree, main_worktree_path, primary_worktree_path, remote, remote_url, repo, repo_path, repo_root, short_commit, upstream, worktree, worktree_name, worktree_path[24m[22m+[2m↳[22m [2mAvailable variables: [4mbranch, commit, cwd, default_branch, main_worktree, main_worktree_path, primary_worktree_path, remote, remote_url, repo, repo_path, repo_root, short_commit, upstream, worktree, worktree_name, worktree_path[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snapindex 95223bf56..f75c4c618 100644--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snap+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snap@@ -46,4 +46,4 @@ exit_code: 1----- stderr -----[31m✗[39m [31mFailed to expand project post-create hook: undefined value @ line 1[39m[107m [0m echo 'Upstream: {{ upstream }}' > upstream.txt-[2m↳[22m [2mAvailable variables: [4mbase, base_worktree_path, branch, commit, default_branch, hook_type, main_worktree, main_worktree_path, primary_worktree_path, remote, remote_url, repo, repo_path, repo_root, short_commit, worktree, worktree_name, worktree_path[24m[22m+[2m↳[22m [2mAvailable variables: [4mbase, base_worktree_path, branch, commit, cwd, default_branch, hook_type, main_worktree, main_worktree_path, primary_worktree_path, remote, remote_url, repo, repo_path, repo_root, short_commit, worktree, worktree_name, worktree_path[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_template_base_without_create.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_template_base_without_create.snapindex 2a9327f4e..ce4e5c932 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_template_base_without_create.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_template_base_without_create.snap@@ -48,4 +48,4 @@ exit_code: 1[2m↳[22m [2mTo enable automatic cd, run [4mwt config shell install[24m[22m[31m✗[39m [31mFailed to expand --execute command: undefined value @ line 1[39m[107m [0m echo 'base={{ base }}'-[2m↳[22m [2mAvailable variables: [4mbranch, commit, default_branch, main_worktree, main_worktree_path, primary_worktree_path, remote, remote_url, repo, repo_path, repo_root, short_commit, worktree, worktree_name, worktree_path[24m[22m+[2m↳[22m [2mAvailable variables: [4mbranch, commit, cwd, default_branch, main_worktree, main_worktree_path, primary_worktree_path, remote, remote_url, repo, repo_path, repo_root, short_commit, worktree, worktree_name, worktree_path[24m[22m