Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(hooks): add --var flag to override template variables (#466)
Maximilian Roosdf5804030e8d
diff --git a/docs/content/hook.md b/docs/content/hook.mdindex 9c210bd87..7f5a488dd 100644--- a/docs/content/hook.md+++ b/docs/content/hook.md@@ -388,10 +388,13 @@ wt hook pre-merge project: # Run all project hookswt hook pre-merge user:test # Run only user's "test" hookwt hook pre-merge project:test # Run only project's "test" hookwt hook pre-merge --yes # Skip approval prompts (for CI)+wt hook post-create --var branch=feature/test # Override template variable```The `user:` and `project:` prefixes filter by source. Use `user:` or `project:` alone to run all hooks from that source, or `user:name` / `project:name` to run a specific hook.+The `--var KEY=VALUE` flag lets you override built-in template variables — useful for testing hooks with different contexts without switching to that context.+## Language-specific tipsEach ecosystem has quirks that affect hook design. Contributions welcome for languages not listed.diff --git a/src/cli.rs b/src/cli.rsindex 318b7b43a..d07414bee 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -1,9 +1,31 @@use clap::builder::styling::{AnsiColor, Color, Styles};use clap::{Command, CommandFactory, Parser, Subcommand, ValueEnum};use std::sync::OnceLock;+use worktrunk::config::{DEPRECATED_TEMPLATE_VARS, TEMPLATE_VARS};use crate::commands::Shell;+/// Parse key=value string into a tuple, validating that the key is a known template variable.+///+/// Used by the `--var` flag on hook commands to override built-in template variables.+/// Values are shell-escaped during template expansion (see `expand_template` in expansion.rs).+fn parse_key_val(s: &str) -> Result<(String, String), String> {+ let (key, value) = s+ .split_once('=')+ .ok_or_else(|| format!("invalid KEY=VALUE: no `=` found in `{s}`"))?;+ if key.is_empty() {+ return Err("invalid KEY=VALUE: key cannot be empty".to_string());+ }+ if !TEMPLATE_VARS.contains(&key) && !DEPRECATED_TEMPLATE_VARS.contains(&key) {+ return Err(format!(+ "unknown variable `{key}`; valid variables: {} (deprecated: {})",+ TEMPLATE_VARS.join(", "),+ DEPRECATED_TEMPLATE_VARS.join(", ")+ ));+ }+ Ok((key.to_string(), value.to_string()))+}+/// Custom styles for help output - matches worktrunk's color schemefn help_styles() -> Styles {Styles::styled()@@ -1100,6 +1122,10 @@ pub enum HookCommand {/// Skip approval prompts#[arg(short, long)]yes: bool,++ /// Override built-in template variable (KEY=VALUE)+ #[arg(long = "var", value_name = "KEY=VALUE", value_parser = parse_key_val, action = clap::ArgAction::Append)]+ vars: Vec<(String, String)>,},/// Run post-start hooks@@ -1116,6 +1142,10 @@ pub enum HookCommand {/// Skip approval prompts#[arg(short, long)]yes: bool,++ /// Override built-in template variable (KEY=VALUE)+ #[arg(long = "var", value_name = "KEY=VALUE", value_parser = parse_key_val, action = clap::ArgAction::Append)]+ vars: Vec<(String, String)>,},/// Run post-switch hooks@@ -1132,6 +1162,10 @@ pub enum HookCommand {/// Skip approval prompts#[arg(short, long)]yes: bool,++ /// Override built-in template variable (KEY=VALUE)+ #[arg(long = "var", value_name = "KEY=VALUE", value_parser = parse_key_val, action = clap::ArgAction::Append)]+ vars: Vec<(String, String)>,},/// Run pre-commit hooks@@ -1146,6 +1180,10 @@ pub enum HookCommand {/// Skip approval prompts#[arg(short, long)]yes: bool,++ /// Override built-in template variable (KEY=VALUE)+ #[arg(long = "var", value_name = "KEY=VALUE", value_parser = parse_key_val, action = clap::ArgAction::Append)]+ vars: Vec<(String, String)>,},/// Run pre-merge hooks@@ -1160,6 +1198,10 @@ pub enum HookCommand {/// Skip approval prompts#[arg(short, long)]yes: bool,++ /// Override built-in template variable (KEY=VALUE)+ #[arg(long = "var", value_name = "KEY=VALUE", value_parser = parse_key_val, action = clap::ArgAction::Append)]+ vars: Vec<(String, String)>,},/// Run post-merge hooks@@ -1174,6 +1216,10 @@ pub enum HookCommand {/// Skip approval prompts#[arg(short, long)]yes: bool,++ /// Override built-in template variable (KEY=VALUE)+ #[arg(long = "var", value_name = "KEY=VALUE", value_parser = parse_key_val, action = clap::ArgAction::Append)]+ vars: Vec<(String, String)>,},/// Run pre-remove hooks@@ -1188,6 +1234,10 @@ pub enum HookCommand {/// Skip approval prompts#[arg(short, long)]yes: bool,++ /// Override built-in template variable (KEY=VALUE)+ #[arg(long = "var", value_name = "KEY=VALUE", value_parser = parse_key_val, action = clap::ArgAction::Append)]+ vars: Vec<(String, String)>,},/// Manage command approvals@@ -2392,10 +2442,13 @@ wt hook pre-merge project: # Run all project hookswt hook pre-merge user:test # Run only user's "test" hookwt hook pre-merge project:test # Run only project's "test" hookwt hook pre-merge --yes # Skip approval prompts (for CI)+wt hook post-create --var branch=feature/test # Override template variable```The `user:` and `project:` prefixes filter by source. Use `user:` or `project:` alone to run all hooks from that source, or `user:name` / `project:name` to run a specific hook.+The `--var KEY=VALUE` flag lets you override built-in template variables — useful for testing hooks with different contexts without switching to that context.+## Language-specific tipsEach ecosystem has quirks that affect hook design. Contributions welcome for languages not listed.diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 2267a0167..e328c2c15 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -35,7 +35,15 @@ use super::project_config::collect_commands_for_hooks;/// There's no skip flag - if you explicitly run hooks, all configured hooks run.////// Works in detached HEAD state - `{{ branch }}` template variable will be "HEAD".-pub fn run_hook(hook_type: HookType, yes: bool, name_filter: Option<&str>) -> anyhow::Result<()> {+///+/// Custom variables from `--var KEY=VALUE` are merged into the template context,+/// allowing hooks to be tested with different values without being in that context.+pub fn run_hook(+ hook_type: HookType,+ yes: bool,+ name_filter: Option<&str>,+ custom_vars: &[(String, String)],+) -> anyhow::Result<()> {use super::command_approval::approve_hooks_filtered;// Derive context from current environment (branch-optional for CI compatibility)@@ -55,8 +63,11 @@ pub fn run_hook(hook_type: HookType, yes: bool, name_filter: Option<&str>) -> anreturn Ok(());}- // TODO: Add support for custom variable overrides (e.g., --var key=value)- // This would allow testing hooks with different contexts without being in that context+ // Build extra vars from command-line --var flags+ let custom_vars_refs: Vec<(&str, &str)> = custom_vars+ .iter()+ .map(|(k, v)| (k.as_str(), v.as_str()))+ .collect();// Helper to get user hook configmacro_rules! user_hook {@@ -94,7 +105,7 @@ pub fn run_hook(hook_type: HookType, yes: bool, name_filter: Option<&str>) -> anuser_config,project_config,hook_type,- &[],+ &custom_vars_refs,HookFailureStrategy::FailFast,name_filter,crate::output::pre_hook_display_path(ctx.worktree_path),@@ -112,7 +123,7 @@ pub fn run_hook(hook_type: HookType, yes: bool, name_filter: Option<&str>) -> anuser_config,project_config,hook_type,- &[],+ &custom_vars_refs,name_filter,None,)?;@@ -131,7 +142,7 @@ pub fn run_hook(hook_type: HookType, yes: bool, name_filter: Option<&str>) -> anuser_config,project_config,hook_type,- &[],+ &custom_vars_refs,name_filter,None,)?;@@ -145,12 +156,14 @@ pub fn run_hook(hook_type: HookType, yes: bool, name_filter: Option<&str>) -> an.and_then(|c| c.hooks.pre_commit.as_ref());require_hooks(user_config, project_config, hook_type)?;// Pre-commit hook can optionally use target branch context+ // Custom vars take precedence (added last)let target_branch = repo.default_branch().ok();- let extra_vars: Vec<(&str, &str)> = target_branch+ let mut extra_vars: Vec<(&str, &str)> = target_branch.as_deref().into_iter().map(|t| ("target", t)).collect();+ extra_vars.extend(&custom_vars_refs);// Manual wt hook: user stays at cwd (no cd happens)run_hook_with_filter(&ctx,@@ -168,7 +181,13 @@ pub fn run_hook(hook_type: HookType, yes: bool, name_filter: Option<&str>) -> an// which already handle user hooks (approval already happened at gate)// Use current branch as target (matches approval prompt for wt hook)let project_cfg = project_config.unwrap_or_default();- run_pre_merge_commands(&project_cfg, &ctx, ctx.branch_or_head(), name_filter)+ run_pre_merge_commands(+ &project_cfg,+ &ctx,+ ctx.branch_or_head(),+ name_filter,+ &custom_vars_refs,+ )}HookType::PostMerge => {// Manual wt hook: user stays at cwd (no cd happens)@@ -177,6 +196,7 @@ pub fn run_hook(hook_type: HookType, yes: bool, name_filter: Option<&str>) -> anctx.branch_or_head(),name_filter,crate::output::pre_hook_display_path(ctx.worktree_path),+ &custom_vars_refs,)}HookType::PreRemove => {@@ -185,6 +205,7 @@ pub fn run_hook(hook_type: HookType, yes: bool, name_filter: Option<&str>) -> an&ctx,name_filter,crate::output::pre_hook_display_path(ctx.worktree_path),+ &custom_vars_refs,)}}diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex e47dcfd57..aebd6dc36 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -179,7 +179,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {if verify {let ctx = env.context(yes);let project_config = repo.load_project_config()?.unwrap_or_default();- run_pre_merge_commands(&project_config, &ctx, &target_branch, None)?;+ run_pre_merge_commands(&project_config, &ctx, &target_branch, None, &[])?;}// Fast-forward push to target branch with commit/squash/rebase info for consolidated message@@ -267,7 +267,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {// or worktree preserved so they stay in feature)crate::output::pre_hook_display_path(&destination_path)};- execute_post_merge_commands(&ctx, &target_branch, None, display_path)?;+ execute_post_merge_commands(&ctx, &target_branch, None, display_path, &[])?;}Ok(())@@ -282,13 +282,17 @@ pub fn run_pre_merge_commands(ctx: &CommandContext,target_branch: &str,name_filter: Option<&str>,+ extra_vars: &[(&str, &str)],) -> anyhow::Result<()> {+ // Combine target with any custom vars (custom vars take precedence, added last)+ let mut vars = vec![("target", target_branch)];+ vars.extend_from_slice(extra_vars);run_hook_with_filter(ctx,ctx.config.hooks.pre_merge.as_ref(),project_config.hooks.pre_merge.as_ref(),HookType::PreMerge,- &[("target", target_branch)],+ &vars,HookFailureStrategy::FailFast,name_filter,crate::output::pre_hook_display_path(ctx.worktree_path),@@ -308,10 +312,14 @@ pub fn execute_post_merge_commands(target_branch: &str,name_filter: Option<&str>,display_path: Option<&Path>,+ extra_vars: &[(&str, &str)],) -> anyhow::Result<()> {// Load project config from the main worktree pathlet project_config = ctx.repo.load_project_config()?;+ // Combine target with any custom vars (custom vars take precedence, added last)+ let mut vars = vec![("target", target_branch)];+ vars.extend_from_slice(extra_vars);run_hook_with_filter(ctx,ctx.config.hooks.post_merge.as_ref(),@@ -319,7 +327,7 @@ pub fn execute_post_merge_commands(.as_ref().and_then(|c| c.hooks.post_merge.as_ref()),HookType::PostMerge,- &[("target", target_branch)],+ &vars,HookFailureStrategy::Warn,name_filter,display_path,@@ -339,6 +347,7 @@ pub fn execute_pre_remove_commands(ctx: &CommandContext,name_filter: Option<&str>,display_path: Option<&Path>,+ extra_vars: &[(&str, &str)],) -> anyhow::Result<()> {let project_config = ctx.repo.load_project_config()?;@@ -349,7 +358,7 @@ pub fn execute_pre_remove_commands(.as_ref().and_then(|c| c.hooks.pre_remove.as_ref()),HookType::PreRemove,- &[],+ extra_vars,HookFailureStrategy::FailFast,name_filter,display_path,diff --git a/src/config/expansion.rs b/src/config/expansion.rsindex 30ee7ef64..370a7d55a 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -20,6 +20,37 @@//! ```use minijinja::{Environment, Value};++/// Known template variables available in hook commands.+///+/// These are populated by `build_hook_context()` in `command_executor.rs`.+/// Some variables are conditional (e.g., `upstream` only exists if tracking is configured).+///+/// This list is the single source of truth for `--var` validation in CLI.+pub const TEMPLATE_VARS: &[&str] = &[+ "repo",+ "branch",+ "worktree_name",+ "repo_path",+ "worktree_path",+ "default_branch",+ "main_worktree_path",+ "commit",+ "short_commit",+ "remote",+ "remote_url",+ "upstream",+ "target", // Added by merge/rebase hooks via extra_vars+];++/// Deprecated template variable aliases (still valid for backward compatibility).+///+/// These map to current variables:+/// - `main_worktree` → `repo`+/// - `repo_root` → `repo_path`+/// - `worktree` → `worktree_path`+pub const DEPRECATED_TEMPLATE_VARS: &[&str] = &["main_worktree", "repo_root", "worktree"];+use std::collections::HashMap;use std::hash::{Hash, Hasher};diff --git a/src/config/mod.rs b/src/config/mod.rsindex 350fed3dd..ec2475645 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -28,7 +28,9 @@ mod user;pub use commands::{Command, CommandConfig};pub use deprecation::check_and_migrate as check_deprecated_vars;pub use deprecation::normalize_template_vars;-pub use expansion::{expand_template, sanitize_branch_name};+pub use expansion::{+ DEPRECATED_TEMPLATE_VARS, TEMPLATE_VARS, expand_template, sanitize_branch_name,+};pub use hooks::HooksConfig;pub use project::{ProjectCiConfig, ProjectConfig, ProjectListConfig,diff --git a/src/main.rs b/src/main.rsindex 63d034c52..6e933ea3e 100644--- a/src/main.rs+++ b/src/main.rs@@ -1124,26 +1124,26 @@ fn main() {hook_type,expanded,} => handle_hook_show(hook_type.as_deref(), expanded),- HookCommand::PostCreate { name, yes } => {- run_hook(HookType::PostCreate, yes, name.as_deref())+ HookCommand::PostCreate { name, yes, vars } => {+ run_hook(HookType::PostCreate, yes, name.as_deref(), &vars)}- HookCommand::PostStart { name, yes } => {- run_hook(HookType::PostStart, yes, name.as_deref())+ HookCommand::PostStart { name, yes, vars } => {+ run_hook(HookType::PostStart, yes, name.as_deref(), &vars)}- HookCommand::PostSwitch { name, yes } => {- run_hook(HookType::PostSwitch, yes, name.as_deref())+ HookCommand::PostSwitch { name, yes, vars } => {+ run_hook(HookType::PostSwitch, yes, name.as_deref(), &vars)}- HookCommand::PreCommit { name, yes } => {- run_hook(HookType::PreCommit, yes, name.as_deref())+ HookCommand::PreCommit { name, yes, vars } => {+ run_hook(HookType::PreCommit, yes, name.as_deref(), &vars)}- HookCommand::PreMerge { name, yes } => {- run_hook(HookType::PreMerge, yes, name.as_deref())+ HookCommand::PreMerge { name, yes, vars } => {+ run_hook(HookType::PreMerge, yes, name.as_deref(), &vars)}- HookCommand::PostMerge { name, yes } => {- run_hook(HookType::PostMerge, yes, name.as_deref())+ HookCommand::PostMerge { name, yes, vars } => {+ run_hook(HookType::PostMerge, yes, name.as_deref(), &vars)}- HookCommand::PreRemove { name, yes } => {- run_hook(HookType::PreRemove, yes, name.as_deref())+ HookCommand::PreRemove { name, yes, vars } => {+ run_hook(HookType::PreRemove, yes, name.as_deref(), &vars)}HookCommand::Approvals { action } => match action {ApprovalsCommand::Add { all } => add_approvals(all),diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 8d3d8ad86..12c3b30c5 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -599,7 +599,7 @@ fn handle_removed_worktree_output(} else {Some(worktree_path) // Show path when user is elsewhere};- execute_pre_remove_commands(&ctx, None, display_path)?;+ execute_pre_remove_commands(&ctx, None, display_path, &[])?;}// Handle detached HEAD case (no branch known)diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex 9bd5d2084..ace978276 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -1064,3 +1064,200 @@ first = "echo 'FIRST'""Error should list available commands, got: {stderr}");}++// ============================================================================+// Custom Variable (--var) Tests+// ============================================================================++#[rstest]+fn test_var_flag_overrides_template_variable(repo: TestRepo) {+ // Write user config with a hook that uses a template variable+ repo.write_test_config(+ r#"[post-create]+test = "echo '{{ target }}' > target_output.txt"+"#,+ );++ let output = repo+ .wt_command()+ .args([+ "hook",+ "post-create",+ "--yes",+ "--var",+ "target=CUSTOM_TARGET",+ ])+ .output()+ .expect("Failed to run wt hook");++ assert!(output.status.success(), "Hook should succeed");++ let output_file = repo.root_path().join("target_output.txt");+ let contents = fs::read_to_string(&output_file).unwrap();+ assert!(+ contents.contains("CUSTOM_TARGET"),+ "Variable should be overridden in hook, got: {contents}"+ );+}++#[rstest]+fn test_var_flag_multiple_variables(repo: TestRepo) {+ // Write user config with a hook that uses multiple template variables+ repo.write_test_config(+ r#"[post-create]+test = "echo '{{ target }} {{ remote }}' > multi_var_output.txt"+"#,+ );++ let output = repo+ .wt_command()+ .args([+ "hook",+ "post-create",+ "--yes",+ "--var",+ "target=FIRST",+ "--var",+ "remote=SECOND",+ ])+ .output()+ .expect("Failed to run wt hook");++ assert!(output.status.success(), "Hook should succeed");++ let output_file = repo.root_path().join("multi_var_output.txt");+ let contents = fs::read_to_string(&output_file).unwrap();+ assert!(+ contents.contains("FIRST") && contents.contains("SECOND"),+ "Both variables should be overridden, got: {contents}"+ );+}++#[rstest]+fn test_var_flag_overrides_builtin_variable(repo: TestRepo) {+ // Write user config with a hook that uses the builtin branch variable+ repo.write_test_config(+ r#"[post-create]+test = "echo '{{ branch }}' > branch_output.txt"+"#,+ );++ let output = repo+ .wt_command()+ .args([+ "hook",+ "post-create",+ "--yes",+ "--var",+ "branch=CUSTOM_BRANCH_NAME",+ ])+ .output()+ .expect("Failed to run wt hook");++ assert!(output.status.success(), "Hook should succeed");++ let output_file = repo.root_path().join("branch_output.txt");+ let contents = fs::read_to_string(&output_file).unwrap();+ assert!(+ contents.contains("CUSTOM_BRANCH_NAME"),+ "Custom variable should override builtin, got: {contents}"+ );+}++#[rstest]+fn test_var_flag_invalid_format_fails() {+ // Test that invalid KEY=VALUE format is rejected+ let output = std::process::Command::new(env!("CARGO_BIN_EXE_wt"))+ .args(["hook", "post-create", "--var", "no_equals_sign"])+ .output()+ .expect("Failed to run wt");++ assert!(!output.status.success(), "Invalid --var format should fail");++ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("invalid KEY=VALUE") || stderr.contains("no `=` found"),+ "Error should mention invalid format, got: {stderr}"+ );+}++#[test]+fn test_var_flag_unknown_variable_fails() {+ // Test that unknown variable names are rejected+ let output = std::process::Command::new(env!("CARGO_BIN_EXE_wt"))+ .args(["hook", "post-create", "--var", "custom_var=value"])+ .output()+ .expect("Failed to run wt");++ assert!(!output.status.success(), "Unknown variable should fail");++ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("unknown variable"),+ "Error should mention unknown variable, got: {stderr}"+ );+}++#[rstest]+fn test_var_flag_last_value_wins(repo: TestRepo) {+ // Test that when the same variable is specified multiple times, the last value wins+ repo.write_test_config(+ r#"[post-create]+test = "echo '{{ target }}' > target_output.txt"+"#,+ );++ let output = repo+ .wt_command()+ .args([+ "hook",+ "post-create",+ "--yes",+ "--var",+ "target=FIRST",+ "--var",+ "target=SECOND",+ ])+ .output()+ .expect("Failed to run wt hook");++ assert!(output.status.success());++ let output_file = repo.root_path().join("target_output.txt");+ let contents = std::fs::read_to_string(&output_file).expect("Should have created output file");+ assert!(+ contents.contains("SECOND"),+ "Last --var value should win, got: {contents}"+ );+}++#[rstest]+fn test_var_flag_deprecated_alias_works(repo: TestRepo) {+ // Test that deprecated variable aliases (main_worktree, repo_root, worktree) can be overridden+ repo.write_test_config(+ r#"[post-create]+test = "echo '{{ main_worktree }}' > alias_output.txt"+"#,+ );++ let output = repo+ .wt_command()+ .args([+ "hook",+ "post-create",+ "--yes",+ "--var",+ "main_worktree=/custom/path",+ ])+ .output()+ .expect("Failed to run wt hook");++ assert!(output.status.success());++ let output_file = repo.root_path().join("alias_output.txt");+ let contents = std::fs::read_to_string(&output_file).expect("Should have created output file");+ assert!(+ contents.contains("/custom/path"),+ "Deprecated alias should be overridden, got: {contents}"+ );+}