Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(hooks): add base and base_worktree_path template variables (#463)
Maximilian Roos271b718d9bdc
diff --git a/.claude-plugin/skills/worktrunk/reference/hook-types-reference.md b/.claude-plugin/skills/worktrunk/reference/hook-types-reference.mdindex 79fdc2fe1..fd3601e64 100644--- a/.claude-plugin/skills/worktrunk/reference/hook-types-reference.md+++ b/.claude-plugin/skills/worktrunk/reference/hook-types-reference.md@@ -6,16 +6,17 @@ Detailed behavior and use cases for all seven Worktrunk hook types.| Hook | When | Blocking? | Fail-Fast? | Variables | Execution ||------|------|-----------|------------|-----------|-----------|-| `post-create` | After creating worktree | Yes | No | Basic | Sequential |-| `post-start` | After creating worktree | No (background) | No | Basic | Parallel |-| `post-switch` | After every switch | No (background) | No | Basic | Parallel |+| `post-create` | After creating worktree | Yes | No | Basic + Base | Sequential |+| `post-start` | After creating worktree | No (background) | No | Basic + Base | Parallel |+| `post-switch` | After every switch | No (background) | No | Basic + Base | Parallel || `pre-commit` | Before committing during merge | Yes | Yes | Basic + Merge | Sequential || `pre-merge` | Before merging to target | Yes | Yes | Basic + Merge | Sequential || `post-merge` | After successful merge | Yes | No | Basic + Merge | Sequential || `pre-remove` | Before worktree removed | Yes | Yes | Basic | Sequential |**Basic variables**: `{{ repo }}`, `{{ repo_path }}`, `{{ branch }}`, `{{ worktree_name }}`, `{{ worktree_path }}`, `{{ main_worktree_path }}`, `{{ default_branch }}`, `{{ commit }}`, `{{ short_commit }}`, `{{ remote }}`, `{{ remote_url }}`, `{{ upstream }}`-**Merge variables**: Basic + `{{ target }}`+**Base variables**: `{{ base }}`, `{{ base_worktree_path }}`+**Merge variables**: `{{ target }}`**Filters**: `{{ branch | sanitize }}` (replace `/` `\` with `-`), `{{ branch | hash_port }}` (port 10000-19999)## Detailed Behavior@@ -264,6 +265,18 @@ Available:- `{{ remote_url }}` - Remote URL (e.g., "[email protected]:user/repo.git")- `{{ upstream }}` - Upstream tracking branch (e.g., "origin/feature")+### Base Variables (Creation Hooks)++```toml+post-create = "echo 'Created from {{ base }} at {{ base_worktree_path }}'"+```++Available in: `post-create`, `post-start`, `post-switch` — only when creating a new worktree (not when switching to existing worktrees).++Additional variables:+- `{{ base }}` - Base branch that new worktree was created from (e.g., "main")+- `{{ base_worktree_path }}` - Absolute path to base branch worktree (empty if base has no worktree)+### Merge Variables (Merge Hooks Only)```tomldiff --git a/docs/content/hook.md b/docs/content/hook.mdindex d27cdbf7a..9c210bd87 100644--- a/docs/content/hook.md+++ b/docs/content/hook.md@@ -153,6 +153,8 @@ Hooks can use template variables that expand at runtime:| `{{ remote_url }}` | [email protected]:user/repo.git | Remote URL || `{{ upstream }}` | origin/feature | Upstream tracking branch || `{{ target }}` | main | Target branch (merge hooks only) |+| `{{ base }}` | main | Base branch (creation hooks only) |+| `{{ base_worktree_path }}` | /path/to/myproject | Base branch worktree (creation hooks only) |See [Designing effective hooks](#designing-effective-hooks) for `main_worktree_path` patterns.diff --git a/src/cli.rs b/src/cli.rsindex 52022f92f..8edf05624 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -2098,6 +2098,8 @@ Hooks can use template variables that expand at runtime:| `{{ remote_url }}` | [email protected]:user/repo.git | Remote URL || `{{ upstream }}` | origin/feature | Upstream tracking branch || `{{ target }}` | main | Target branch (merge hooks only) |+| `{{ base }}` | main | Base branch (creation hooks only) |+| `{{ base_worktree_path }}` | /path/to/myproject | Base branch worktree (creation hooks only) |See [Designing effective hooks](#designing-effective-hooks) for `main_worktree_path` patterns.diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex bfef0602e..b8ea5c7e5 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -82,9 +82,6 @@ pub fn build_hook_context(map.insert("repo_path".into(), repo_path.clone());map.insert("worktree_path".into(), worktree.clone());- // TODO: Add `base` (branch) and `base_worktree_path` for post-create/post-switch hooks.- // Requires tracking source worktree before switch and passing via extra_vars.-// Deprecated aliases (kept for backward compatibility)map.insert("main_worktree".into(), repo_name.into());map.insert("repo_root".into(), repo_path);diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex aba280623..10970b269 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -348,6 +348,8 @@ pub enum SwitchResult {created_branch: bool,/// Base branch when creating new branch (e.g., "main")base_branch: Option<String>,+ /// Absolute path to base branch's worktree (POSIX format for shell compatibility)+ base_worktree_path: Option<String>,/// Remote tracking branch if created from remote (e.g., "origin/feature")/// This is set when git's DWIM created a local branch from a remotefrom_remote: Option<String>,@@ -693,6 +695,12 @@ pub fn handle_switch(None};+ // Compute base worktree path once for hooks and result+ let base_worktree_path = base_for_creation+ .as_ref()+ .and_then(|b| repo.worktree_for_branch(b).ok().flatten())+ .map(|p| worktrunk::path::to_posix_path(&p.to_string_lossy()));+// Execute post-create commands (sequential, blocking)// Note: If user declines, continue anyway - worktree already createdif !no_verify {@@ -705,8 +713,19 @@ pub fn handle_switch(&repo_root,force,);++ let extra_vars: Vec<(&str, &str)> = [+ base_for_creation.as_ref().map(|b| ("base", b.as_str())),+ base_worktree_path+ .as_ref()+ .map(|p| ("base_worktree_path", p.as_str())),+ ]+ .into_iter()+ .flatten()+ .collect();+// Approval was handled at the gate- ctx.execute_post_create_commands()?;+ ctx.execute_post_create_commands(&extra_vars)?;}// Note: post-start commands are spawned AFTER success message is shown@@ -720,6 +739,7 @@ pub fn handle_switch(path: worktree_path,created_branch: create,base_branch: base_for_creation,+ base_worktree_path,from_remote,},SwitchBranchInfo {@@ -786,7 +806,9 @@ impl<'a> CommandContext<'a> {/// Runs user hooks first, then project hooks./// Shows path in hook announcements when shell integration isn't active (user's shell/// won't cd to the new worktree, so they need to know where hooks ran).- pub fn execute_post_create_commands(&self) -> anyhow::Result<()> {+ ///+ /// `extra_vars`: Additional template variables (e.g., `base`, `base_worktree_path`).+ pub fn execute_post_create_commands(&self, extra_vars: &[(&str, &str)]) -> anyhow::Result<()> {let project_config = self.repo.load_project_config()?;super::hooks::run_hook_with_filter(self,@@ -795,7 +817,7 @@ impl<'a> CommandContext<'a> {.as_ref().and_then(|c| c.hooks.post_create.as_ref()),HookType::PostCreate,- &[],+ extra_vars,HookFailureStrategy::Warn,None,crate::output::post_hook_display_path(self.worktree_path),@@ -804,10 +826,12 @@ impl<'a> CommandContext<'a> {/// Spawn post-start commands in parallel as background processes (non-blocking)///+ /// `extra_vars`: Additional template variables (e.g., `base`, `base_worktree_path`)./// `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_start_commands(&self,+ extra_vars: &[(&str, &str)],display_path: Option<&std::path::Path>,) -> anyhow::Result<()> {let project_config = self.repo.load_project_config()?;@@ -819,7 +843,7 @@ impl<'a> CommandContext<'a> {.as_ref().and_then(|c| c.hooks.post_start.as_ref()),HookType::PostStart,- &[],+ extra_vars,None,display_path,)?;@@ -831,10 +855,12 @@ impl<'a> CommandContext<'a> {////// Runs on every switch, including to existing worktrees and newly created ones.///+ /// `extra_vars`: Additional template variables (e.g., `base`, `base_worktree_path`)./// `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,+ extra_vars: &[(&str, &str)],display_path: Option<&std::path::Path>,) -> anyhow::Result<()> {let project_config = self.repo.load_project_config()?;@@ -846,7 +872,7 @@ impl<'a> CommandContext<'a> {.as_ref().and_then(|c| c.hooks.post_switch.as_ref()),HookType::PostSwitch,- &[],+ extra_vars,None,display_path,)?;@@ -1070,6 +1096,7 @@ mod tests {path: path.clone(),created_branch: true,base_branch: Some("main".to_string()),+ base_worktree_path: Some("/test/main".to_string()),from_remote: None,};assert_eq!(result.path(), &path);@@ -1082,6 +1109,7 @@ mod tests {path: path.clone(),created_branch: false,base_branch: None,+ base_worktree_path: None,from_remote: Some("origin/feature".to_string()),};assert_eq!(result.path(), &path);diff --git a/src/main.rs b/src/main.rsindex d5ce97d97..63d034c52 100644--- a/src/main.rs+++ b/src/main.rs@@ -1315,12 +1315,32 @@ fn main() {yes,);+ // Build extra vars for base branch context+ // "base" is the branch we branched from when creating a new worktree.+ // For existing worktrees, there's no base concept.+ let (base_branch, base_worktree_path): (Option<&str>, Option<&str>) =+ match &result {+ SwitchResult::Created {+ base_branch,+ base_worktree_path,+ ..+ } => (base_branch.as_deref(), base_worktree_path.as_deref()),+ SwitchResult::Existing(_) | SwitchResult::AlreadyAt(_) => (None, None),+ };+ let extra_vars: Vec<(&str, &str)> = [+ base_branch.map(|b| ("base", b)),+ base_worktree_path.map(|p| ("base_worktree_path", p)),+ ]+ .into_iter()+ .flatten()+ .collect();+// Post-switch runs first (immediate "I'm here" signal)- ctx.spawn_post_switch_commands(hooks_display_path.as_deref())?;+ ctx.spawn_post_switch_commands(&extra_vars, hooks_display_path.as_deref())?;// Post-start runs only on creation (setup tasks)if matches!(&result, SwitchResult::Created { .. }) {- ctx.spawn_post_start_commands(hooks_display_path.as_deref())?;+ ctx.spawn_post_start_commands(&extra_vars, hooks_display_path.as_deref())?;}}diff --git a/src/output/global.rs b/src/output/global.rsindex c803ceee7..d45d3211c 100644--- a/src/output/global.rs+++ b/src/output/global.rs@@ -337,11 +337,11 @@ pub fn pre_hook_display_path(hooks_run_at: &std::path::Path) -> Option<&std::pat/// # Examples////// ```ignore-/// // In post-create, post-switch, post-merge hooks:-/// ctx.spawn_post_start_commands(post_hook_display_path(&destination))?;+/// // In post-create, post-start, post-switch hooks (creation path):+/// ctx.spawn_post_start_commands(&extra_vars, post_hook_display_path(&destination))?;////// // After remove when switching to main:-/// ctx.spawn_post_switch_commands(post_hook_display_path(main_path))?;+/// ctx.spawn_post_switch_commands(&[], post_hook_display_path(main_path))?;/// ```pub fn post_hook_display_path(destination: &std::path::Path) -> Option<&std::path::Path> {if is_shell_integration_active() {diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex a52dd79bd..fc91df9a7 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -551,7 +551,8 @@ fn spawn_post_switch_after_remove(&repo_root,false, // force=false for CommandContext);- ctx.spawn_post_switch_commands(super::post_hook_display_path(main_path))+ // No base context for remove-triggered switch (we're returning to main, not creating)+ ctx.spawn_post_switch_commands(&[], super::post_hook_display_path(main_path))}/// Handle output for RemovedWorktree removaldiff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rsindex f32d7bd3b..191a65c05 100644--- a/tests/integration_tests/post_start_commands.rs+++ b/tests/integration_tests/post_start_commands.rs@@ -350,6 +350,76 @@ fn test_post_create_upstream_template(#[from(repo_with_remote)] repo: TestRepo));}+#[rstest]+fn test_post_create_base_variables(repo: TestRepo) {+ // Create project config with base template variables+ repo.write_project_config(+ r#"[post-create]+base = "echo 'Base: {{ base }}' > base_info.txt"+base_path = "echo 'Base Path: {{ base_worktree_path }}' >> base_info.txt"+"#,+ );++ repo.commit("Add config with base template variables");++ // Pre-approve the commands+ repo.write_test_config(+ r#"[projects."repo"]+approved-commands = [+ "echo 'Base: {{ base }}' > base_info.txt",+ "echo 'Base Path: {{ base_worktree_path }}' >> base_info.txt",+]+"#,+ );++ // Create a feature branch worktree from main+ snapshot_switch(+ "post_create_base_variables",+ &repo,+ &["--create", "feature", "--base", "main"],+ );++ // Verify template expansion actually worked+ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");+ let base_file = worktree_path.join("base_info.txt");++ assert!(+ base_file.exists(),+ "base_info.txt should have been created in the worktree"+ );++ let contents = fs::read_to_string(&base_file).unwrap();++ // Verify base variable (branch name we branched from)+ assert!(+ contents.contains("Base: main"),+ "Should contain expanded base branch, got: {}",+ contents+ );++ // Verify base_worktree_path variable (path to main worktree)+ // The path should contain the repo root (main worktree is at repo root)+ assert!(+ contents.contains("Base Path: "),+ "Should have base_worktree_path line, got: {}",+ contents+ );++ // The base_worktree_path should be the main worktree's path (POSIX format)+ let base_path_line = contents+ .lines()+ .find(|l| l.starts_with("Base Path: "))+ .expect("Should have Base Path line");+ let base_path = base_path_line.strip_prefix("Base Path: ").unwrap();++ // Convert expected path to POSIX format for comparison+ let expected_base_path = worktrunk::path::to_posix_path(&repo.root_path().to_string_lossy());+ assert_eq!(+ base_path, expected_base_path,+ "Base path should match main worktree path"+ );+}+#[rstest]fn test_post_create_json_stdin(repo: TestRepo) {use crate::common::wt_command;diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_base_variables.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_base_variables.snapnew file mode 100644index 000000000..a2b6d1048--- /dev/null+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_base_variables.snap@@ -0,0 +1,45 @@+---+source: tests/integration_tests/post_start_commands.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - feature+ - "--base"+ - main+ 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"+ TERM: alacritty+ 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 -----+[36m◎[39m [36mRunning post-create [1mproject:base[22m @ [1m_REPO_.feature[22m:[39m+[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'Base: main'[0m[2m [0m[2m[36m>[0m[2m base_info.txt+[0m[36m◎[39m [36mRunning post-create [1mproject:base_path[22m @ [1m_REPO_.feature[22m:[39m+[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'Base Path: _REPO_'[0m[2m [0m[2m[36m>>[0m[2m base_info.txt+[0m[32m✓[39m [32mCreated branch [1mfeature[22m and worktree from [1mmain[22m @ [1m_REPO_.feature[22m[39m+[2m↳[22m [2mCustomize worktree locations: [90mwt config create[39m[22m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22m