Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: complete template variable redesign follow-ups (#1663)
Maximilian Roosaf8a6022ad88
diff --git a/docs/content/hook.md b/docs/content/hook.mdindex 31af8ab11..f9f8b0994 100644--- a/docs/content/hook.md+++ b/docs/content/hook.md@@ -202,27 +202,37 @@ Hooks can use template variables that expand at runtime:| Variable | Description ||----------|-------------|+| `{{ branch }}` | Active branch name |+| `{{ worktree_path }}` | Active worktree path |+| `{{ worktree_name }}` | Active worktree directory name |+| `{{ commit }}` | Active branch HEAD SHA |+| `{{ short_commit }}` | Active branch HEAD SHA (7 chars) |+| `{{ upstream }}` | Active branch upstream (if tracking a remote) |+| `{{ base }}` | Base branch name |+| `{{ base_worktree_path }}` | Base worktree path |+| `{{ target }}` | Target branch name |+| `{{ target_worktree_path }}` | Target worktree path |+| `{{ cwd }}` | Directory where the hook command runs || `{{ repo }}` | Repository directory name || `{{ repo_path }}` | Absolute path to repository root |-| `{{ branch }}` | Branch name |-| `{{ worktree_name }}` | Worktree directory name |-| `{{ worktree_path }}` | Absolute worktree path |-| `{{ primary_worktree_path }}` | Primary worktree path (main worktree for normal repos; default branch worktree for bare repos) |+| `{{ primary_worktree_path }}` | Primary worktree path || `{{ default_branch }}` | Default branch name |-| `{{ commit }}` | Full HEAD commit SHA |-| `{{ short_commit }}` | Short HEAD commit SHA (7 chars) || `{{ remote }}` | Primary remote name || `{{ remote_url }}` | Remote URL |-| `{{ 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, 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; 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:+Bare variables (`branch`, `worktree_path`, `commit`) refer to the branch the operation acts on: the destination for switch/create, the source for merge/remove. `base` and `target` give the other side:++| Operation | Bare vars | `base` | `target` |+|-----------|-----------|--------|----------|+| switch/create | destination | where you came from | = bare vars |+| merge | feature being merged | = bare vars | merge target |+| remove | branch being removed | = bare vars | where you end up |++Pre and post hooks share the same perspective — `{{ branch | hash_port }}` produces the same port in `post-start` and `post-remove`. `cwd` is the worktree root where the hook command runs. It differs from `worktree_path` in three cases: pre-switch (hook runs in the source, `worktree_path` is the destination), post-remove (active worktree is gone, hook runs in primary), and post-merge with removal (same — active is gone, hook runs in target).++Some variables are conditional: `upstream` requires remote tracking; `base`/`target` are only in two-worktree hooks. Undefined variables error — use conditionals:```toml[post-create]diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.mdindex 00022c8e0..f94c65c4e 100644--- a/skills/worktrunk/reference/hook.md+++ b/skills/worktrunk/reference/hook.md@@ -193,27 +193,37 @@ Hooks can use template variables that expand at runtime:| Variable | Description ||----------|-------------|+| `{{ branch }}` | Active branch name |+| `{{ worktree_path }}` | Active worktree path |+| `{{ worktree_name }}` | Active worktree directory name |+| `{{ commit }}` | Active branch HEAD SHA |+| `{{ short_commit }}` | Active branch HEAD SHA (7 chars) |+| `{{ upstream }}` | Active branch upstream (if tracking a remote) |+| `{{ base }}` | Base branch name |+| `{{ base_worktree_path }}` | Base worktree path |+| `{{ target }}` | Target branch name |+| `{{ target_worktree_path }}` | Target worktree path |+| `{{ cwd }}` | Directory where the hook command runs || `{{ repo }}` | Repository directory name || `{{ repo_path }}` | Absolute path to repository root |-| `{{ branch }}` | Branch name |-| `{{ worktree_name }}` | Worktree directory name |-| `{{ worktree_path }}` | Absolute worktree path |-| `{{ primary_worktree_path }}` | Primary worktree path (main worktree for normal repos; default branch worktree for bare repos) |+| `{{ primary_worktree_path }}` | Primary worktree path || `{{ default_branch }}` | Default branch name |-| `{{ commit }}` | Full HEAD commit SHA |-| `{{ short_commit }}` | Short HEAD commit SHA (7 chars) || `{{ remote }}` | Primary remote name || `{{ remote_url }}` | Remote URL |-| `{{ 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, 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; 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:+Bare variables (`branch`, `worktree_path`, `commit`) refer to the branch the operation acts on: the destination for switch/create, the source for merge/remove. `base` and `target` give the other side:++| Operation | Bare vars | `base` | `target` |+|-----------|-----------|--------|----------|+| switch/create | destination | where you came from | = bare vars |+| merge | feature being merged | = bare vars | merge target |+| remove | branch being removed | = bare vars | where you end up |++Pre and post hooks share the same perspective — `{{ branch | hash_port }}` produces the same port in `post-start` and `post-remove`. `cwd` is the worktree root where the hook command runs. It differs from `worktree_path` in three cases: pre-switch (hook runs in the source, `worktree_path` is the destination), post-remove (active worktree is gone, hook runs in primary), and post-merge with removal (same — active is gone, hook runs in target).++Some variables are conditional: `upstream` requires remote tracking; `base`/`target` are only in two-worktree hooks. Undefined variables error — use conditionals:```toml[post-create]diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 403a289db..e5c06658e 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -1289,27 +1289,37 @@ Hooks can use template variables that expand at runtime:| Variable | Description ||----------|-------------|+| `{{ branch }}` | Active branch name |+| `{{ worktree_path }}` | Active worktree path |+| `{{ worktree_name }}` | Active worktree directory name |+| `{{ commit }}` | Active branch HEAD SHA |+| `{{ short_commit }}` | Active branch HEAD SHA (7 chars) |+| `{{ upstream }}` | Active branch upstream (if tracking a remote) |+| `{{ base }}` | Base branch name |+| `{{ base_worktree_path }}` | Base worktree path |+| `{{ target }}` | Target branch name |+| `{{ target_worktree_path }}` | Target worktree path |+| `{{ cwd }}` | Directory where the hook command runs || `{{ repo }}` | Repository directory name || `{{ repo_path }}` | Absolute path to repository root |-| `{{ branch }}` | Branch name |-| `{{ worktree_name }}` | Worktree directory name |-| `{{ worktree_path }}` | Absolute worktree path |-| `{{ primary_worktree_path }}` | Primary worktree path (main worktree for normal repos; default branch worktree for bare repos) |+| `{{ primary_worktree_path }}` | Primary worktree path || `{{ default_branch }}` | Default branch name |-| `{{ commit }}` | Full HEAD commit SHA |-| `{{ short_commit }}` | Short HEAD commit SHA (7 chars) || `{{ remote }}` | Primary remote name || `{{ remote_url }}` | Remote URL |-| `{{ 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, 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; 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:+Bare variables (`branch`, `worktree_path`, `commit`) refer to the branch the operation acts on: the destination for switch/create, the source for merge/remove. `base` and `target` give the other side:++| Operation | Bare vars | `base` | `target` |+|-----------|-----------|--------|----------|+| switch/create | destination | where you came from | = bare vars |+| merge | feature being merged | = bare vars | merge target |+| remove | branch being removed | = bare vars | where you end up |++Pre and post hooks share the same perspective — `{{ branch | hash_port }}` produces the same port in `post-start` and `post-remove`. `cwd` is the worktree root where the hook command runs. It differs from `worktree_path` in three cases: pre-switch (hook runs in the source, `worktree_path` is the destination), post-remove (active worktree is gone, hook runs in primary), and post-merge with removal (same — active is gone, hook runs in target).++Some variables are conditional: `upstream` requires remote tracking; `base`/`target` are only in two-worktree hooks. Undefined variables error — use conditionals:```toml[post-create]diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex c3d34e60e..6412c5c6d 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -113,7 +113,11 @@ pub fn build_hook_context(map.insert("main_worktree_path".into(), path_str);}- if let Ok(commit) = ctx.repo.run_command(&["rev-parse", "HEAD"]) {+ // Resolve commit from the Active branch, not HEAD at discovery path.+ // This ensures {{ commit }} follows the Active branch even when the+ // CommandContext points to a different worktree than where we're running.+ let commit_ref = ctx.branch.unwrap_or("HEAD");+ if let Ok(commit) = ctx.repo.run_command(&["rev-parse", commit_ref]) {let commit = commit.trim();map.insert("commit".into(), commit.into());if commit.len() >= 7 {diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rsindex d3047ca21..403e6abed 100644--- a/src/commands/handle_switch.rs+++ b/src/commands/handle_switch.rs@@ -269,6 +269,21 @@ pub fn handle_switch(// doesn't leave behind a half-created worktree that blocks re-running.validate_switch_templates(&repo, config, &plan, execute, execute_args, hooks_approved)?;+ // Capture source (base) worktree identity BEFORE the switch, so post-switch+ // hooks can reference where the user came from via {{ base }} / {{ base_worktree_path }}.+ let source_branch = repo+ .current_worktree()+ .branch()+ .ok()+ .flatten()+ .unwrap_or_default();+ let source_path = repo+ .current_worktree()+ .root()+ .ok()+ .map(|p| worktrunk::path::to_posix_path(&p.to_string_lossy()))+ .unwrap_or_default();+// Execute the validated planlet (result, branch_info) = execute_switch(&repo, plan, config, yes, hooks_approved)?;@@ -311,10 +326,22 @@ pub fn handle_switch(let _ = prompt_shell_integration(config, binary_name, skip_prompt);}- // Build extra vars for base branch context (used by both hooks and --execute)- // "base" is the branch we branched from when creating a new worktree.- // For existing worktrees, there's no base concept.- let extra_vars = switch_extra_vars(&result);+ // Build extra vars for base/target context (used by both hooks and --execute).+ // "base" is the source worktree the user switched from (all switches),+ // or the branch they branched from (creates).+ let mut extra_vars = switch_extra_vars(&result);+ // For existing switches, add source worktree as base+ if matches!(+ result,+ SwitchResult::Existing { .. } | SwitchResult::AlreadyAt(_)+ ) {+ if !source_branch.is_empty() {+ extra_vars.push(("base", &source_branch));+ }+ if !source_path.is_empty() {+ extra_vars.push(("base_worktree_path", &source_path));+ }+ }// Spawn background hooks after success message// - post-switch: runs on ALL switches (shows "@ path" when shell won't be there)diff --git a/src/commands/worktree/hooks.rs b/src/commands/worktree/hooks.rsindex a7c0ee3dc..7d696efc6 100644--- a/src/commands/worktree/hooks.rs+++ b/src/commands/worktree/hooks.rs@@ -70,9 +70,17 @@ impl<'a> CommandContext<'a> {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.+ // self.worktree_path is main_path (set by caller). Look up its branch+ // rather than using self.branch (which is the removed branch).let target_path_str = to_posix_path(&self.worktree_path.to_string_lossy());- let target_branch = self.branch_or_head();+ let target_branch_owned = self+ .repo+ .worktree_at(self.worktree_path)+ .branch()+ .ok()+ .flatten()+ .unwrap_or_default();+ let target_branch = target_branch_owned.as_str();let extra_vars: Vec<(&str, &str)> = vec![("branch", removed_branch),diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex 951a1dd2b..e68a45ed9 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -2002,3 +2002,173 @@ fn test_remove_current_worktree_fires_post_switch_hook(mut repo: TestRepo) {"Post-switch hook should run when removing current worktree, got: {content}");}++// ==========================================================================+// Active model: directional template variables+// ==========================================================================++/// Pre-switch to existing worktree: worktree_path = destination (Active),+/// base_worktree_path = source, cwd = source.+#[rstest]+fn test_pre_switch_vars_point_to_destination(mut repo: TestRepo) {+ let feature_path = repo.add_worktree("feature");++ // Hook captures worktree_path, base_worktree_path, and cwd+ repo.write_test_config(+ r#"[pre-switch]+capture = "echo 'wt_path={{ worktree_path }} base={{ base }} base_wt={{ base_worktree_path }} cwd={{ cwd }}' > pre_switch_vars.txt"+"#,+ );++ repo.wt_command()+ .args(["switch", "feature", "--yes"])+ .current_dir(repo.root_path())+ .output()+ .unwrap();++ let vars_file = repo.root_path().join("pre_switch_vars.txt");+ let content = fs::read_to_string(&vars_file).unwrap();++ let feature_name = feature_path.file_name().unwrap().to_string_lossy();+ let main_name = repo+ .root_path()+ .file_name()+ .unwrap()+ .to_string_lossy()+ .to_string();++ // worktree_path should be the destination (Active)+ assert!(+ content.contains(&format!("/{feature_name} "))+ || content.contains(&format!("\\{feature_name} ")),+ "worktree_path should point to destination '{feature_name}', got: {content}"+ );++ // base should be the source branch+ assert!(+ content.contains("base=main"),+ "base should be source branch 'main', got: {content}"+ );++ // cwd should be the source (where the hook actually runs)+ assert!(+ content.contains(&format!("/{main_name}")) || content.contains(&format!("\\{main_name}")),+ "cwd should point to source worktree '{main_name}', got: {content}"+ );+}++/// Post-remove: target/target_worktree_path point to where user ends up.+#[rstest]+fn test_post_remove_has_target_vars(mut repo: TestRepo) {+ repo.add_worktree("feature");++ repo.write_test_config(+ r#"[post-remove]+capture = "echo 'branch={{ branch }} target={{ target }} target_wt={{ target_worktree_path }}' > ../postremove_target.txt"+"#,+ );++ repo.wt_command()+ .args(["remove", "feature", "--force-delete", "--yes"])+ .current_dir(repo.root_path())+ .output()+ .unwrap();++ let vars_file = repo+ .root_path()+ .parent()+ .unwrap()+ .join("postremove_target.txt");+ crate::common::wait_for_file_content(&vars_file);++ let content = fs::read_to_string(&vars_file).unwrap();++ // branch should be the removed branch (Active)+ assert!(+ content.contains("branch=feature"),+ "branch should be removed branch 'feature', got: {content}"+ );++ // target should be the destination branch (where user ends up)+ assert!(+ content.contains("target=main"),+ "target should be destination 'main', got: {content}"+ );++ // target_worktree_path should be the primary worktree+ let main_name = repo+ .root_path()+ .file_name()+ .unwrap()+ .to_string_lossy()+ .to_string();+ assert!(+ content.contains(&main_name),+ "target_worktree_path should contain primary worktree name '{main_name}', got: {content}"+ );+}++/// Post-switch for existing switches: base vars reference the source worktree.+#[rstest]+fn test_post_switch_has_base_vars_for_existing(mut repo: TestRepo) {+ let feature_path = repo.add_worktree("feature");++ // Post-switch hooks run in the DESTINATION worktree (feature), so write+ // to a path relative to the worktree that will exist after switch.+ repo.write_test_config(+ r#"[post-switch]+capture = "echo 'branch={{ branch }} base={{ base }}' > post_switch_base.txt"+"#,+ );++ repo.wt_command()+ .args(["switch", "feature", "--yes"])+ .current_dir(repo.root_path())+ .output()+ .unwrap();++ // File is written in the destination (feature) worktree+ let vars_file = feature_path.join("post_switch_base.txt");+ crate::common::wait_for_file_content(&vars_file);++ let content = fs::read_to_string(&vars_file).unwrap();++ // branch should be the destination (Active)+ assert!(+ content.contains("branch=feature"),+ "branch should be destination 'feature', got: {content}"+ );++ // base should be the source branch we switched from+ assert!(+ content.contains("base=main"),+ "base should be source 'main', got: {content}"+ );+}++/// cwd always exists on disk — even when worktree_path points to a deleted directory.+#[rstest]+fn test_cwd_always_exists_in_post_remove(mut repo: TestRepo) {+ repo.add_worktree("feature");++ repo.write_test_config(+ r#"[post-remove]+check = "test -d {{ cwd }} && echo 'cwd_exists=true' > ../cwd_check.txt || echo 'cwd_exists=false' > ../cwd_check.txt"+"#,+ );++ repo.wt_command()+ .args(["remove", "feature", "--force-delete", "--yes"])+ .current_dir(repo.root_path())+ .output()+ .unwrap();++ let check_file = repo.root_path().parent().unwrap().join("cwd_check.txt");+ crate::common::wait_for_file_content(&check_file);++ let content = fs::read_to_string(&check_file).unwrap();+ assert!(+ content.contains("cwd_exists=true"),+ "cwd should point to an existing directory, got: {content}"+ );+}diff --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 ce4e5c932..5e5a19442 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@@ -39,13 +39,13 @@ info:WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"----success: false-exit_code: 1+success: true+exit_code: 0----- stdout -----+base=main----- stderr -----[33m▲[39m [33mWorktree for [1mexisting[22m @ [1m_REPO_.existing[22m, but cannot change directory — shell integration not installed[39m[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, 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+[36m◎[39m [36mExecuting (--execute) @ [1m_REPO_.existing[22m:[39m+[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'base=main'[0m[2m