Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(hook): --KEY=VALUE shorthand, custom vars, unreferenced-var warning (#2117)
Maximilian Roosb2a42bbfc801
diff --git a/docs/content/hook.md b/docs/content/hook.mdindex 2f5bd6df0..c75113027 100644--- a/docs/content/hook.md+++ b/docs/content/hook.md@@ -208,11 +208,11 @@ if ctx['branch'].startswith('feature/') and 'backend' in ctx['repo']:`wt hook <type>` runs hooks on demand — useful for testing during development, running in CI pipelines, or re-running after a failure.-{{ terminal(cmd="wt hook pre-merge # Run all pre-merge hooks|||wt hook pre-merge test # Run hooks named __WT_QUOT__test__WT_QUOT__ from both sources|||wt hook pre-merge test build # Run hooks named __WT_QUOT__test__WT_QUOT__ and __WT_QUOT__build__WT_QUOT__|||wt hook pre-merge user: # Run all user hooks|||wt hook pre-merge project: # Run all project hooks|||wt hook pre-merge user:test # Run only user's __WT_QUOT__test__WT_QUOT__ hook|||wt hook pre-merge project:test # Run only project's __WT_QUOT__test__WT_QUOT__ hook|||wt hook pre-merge --yes # Skip approval prompts (for CI)|||wt hook pre-start --var branch=feature/test # Override template variable") }}+{{ terminal(cmd="wt hook pre-merge # Run all pre-merge hooks|||wt hook pre-merge test # Run hooks named __WT_QUOT__test__WT_QUOT__ from both sources|||wt hook pre-merge test build # Run hooks named __WT_QUOT__test__WT_QUOT__ and __WT_QUOT__build__WT_QUOT__|||wt hook pre-merge user: # Run all user hooks|||wt hook pre-merge project: # Run all project hooks|||wt hook pre-merge user:test # Run only user's __WT_QUOT__test__WT_QUOT__ hook|||wt hook pre-merge --yes # Skip approval prompts (for CI)|||wt hook pre-start --branch=feature/test # Override a 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 overrides built-in template variables — useful for testing hooks with different contexts without switching to that context.+Any unknown `--KEY=VALUE` flag is treated as a template variable assignment — useful for testing hooks with different contexts without switching to that context. The long form `--var KEY=VALUE` is equivalent and remains the escape hatch when a variable name collides with a built-in flag (e.g. `config`, `yes`, `dry-run`, `foreground`, `verbose`).# Pipeline Orderingdiff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.mdindex bd8a1df94..81af74ec7 100644--- a/skills/worktrunk/reference/hook.md+++ b/skills/worktrunk/reference/hook.md@@ -206,14 +206,13 @@ $ wt hook pre-merge test build # Run hooks named "test" and "build"$ wt hook pre-merge user: # Run all user hooks$ wt hook pre-merge project: # Run all project hooks$ wt hook pre-merge user:test # Run only user's "test" hook-$ wt hook pre-merge project:test # Run only project's "test" hook$ wt hook pre-merge --yes # Skip approval prompts (for CI)-$ wt hook pre-start --var branch=feature/test # Override template variable+$ wt hook pre-start --branch=feature/test # Override a 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 overrides built-in template variables — useful for testing hooks with different contexts without switching to that context.+Any unknown `--KEY=VALUE` flag is treated as a template variable assignment — useful for testing hooks with different contexts without switching to that context. The long form `--var KEY=VALUE` is equivalent and remains the escape hatch when a variable name collides with a built-in flag (e.g. `config`, `yes`, `dry-run`, `foreground`, `verbose`).# Pipeline Ordering [experimental]diff --git a/src/cli/hook.rs b/src/cli/hook.rsindex cd7b5c65a..d4e6f3f17 100644--- a/src/cli/hook.rs+++ b/src/cli/hook.rs@@ -1,7 +1,379 @@+use std::ffi::{OsStr, OsString};+use clap::Subcommand;use super::config::ApprovalsCommand;+/// Hook subcommands that accept `--var KEY=VALUE` (and the `--KEY=VALUE` shorthand).+///+/// Excludes `show`, `approvals`, and `run-pipeline`, which don't expand+/// template variables. `post-create` is the deprecated alias for `pre-start`.+const HOOK_SUBCOMMANDS_WITH_VARS: &[&str] = &[+ "pre-switch",+ "post-switch",+ "pre-start",+ "post-start",+ "post-create",+ "pre-commit",+ "post-commit",+ "pre-merge",+ "post-merge",+ "pre-remove",+ "post-remove",+];++/// Long flags on hook subcommands that must never be rewritten as template+/// variables. Includes hook-specific flags and global flags (`-C` is a short+/// flag so it's excluded; the `--` prefix check handles that automatically).+const KNOWN_HOOK_LONG_FLAGS: &[&str] = &[+ "--yes",+ "--dry-run",+ "--foreground",+ "--var",+ "--help",+ "--config",+ "--verbose",+];++/// Rewrite `wt hook <type> --KEY=VALUE` into `wt hook <type> --var KEY=VALUE`+/// for unknown `--key=value` flags, matching the ergonomics of the alias+/// variable shorthand (see `AliasOptions::parse`).+///+/// Only args after a `hook <type>` prefix are touched, and only when `<type>`+/// is a hook that accepts `--var`.+///+/// Use the long `--var KEY=VALUE` form when a variable name collides with a+/// built-in flag like `--config` or `--yes`.+pub(crate) fn rewrite_var_shorthand(args: Vec<OsString>) -> Vec<OsString> {+ // Locate `hook` in argv, skipping the program name and guarding against+ // `hook` appearing as the value of `-C` or `--config`.+ let Some(hook_idx) = args.iter().enumerate().find_map(|(i, arg)| {+ if i == 0 || arg.as_os_str() != OsStr::new("hook") {+ return None;+ }+ let prev = args[i - 1].as_os_str();+ if prev == OsStr::new("-C") || prev == OsStr::new("--config") {+ return None;+ }+ Some(i)+ }) else {+ return args;+ };++ let Some(sub_str) = args.get(hook_idx + 1).and_then(|s| s.to_str()) else {+ return args;+ };+ if !HOOK_SUBCOMMANDS_WITH_VARS.contains(&sub_str) {+ return args;+ }++ let rewrite_start = hook_idx + 2;+ let mut out: Vec<OsString> = Vec::with_capacity(args.len());+ out.extend(args[..rewrite_start].iter().cloned());+ let mut past_double_dash = false;+ for token in &args[rewrite_start..] {+ if token == "--" {+ past_double_dash = true;+ out.push(token.clone());+ continue;+ }+ if !past_double_dash+ && let Some(s) = token.to_str()+ && let Some(rest) = s.strip_prefix("--")+ && let Some((key, value)) = rest.split_once('=')+ && !key.is_empty()+ {+ let flag_name = format!("--{key}");+ if !KNOWN_HOOK_LONG_FLAGS.contains(&flag_name.as_str()) {+ out.push(OsString::from("--var"));+ out.push(OsString::from(format!("{key}={value}")));+ continue;+ }+ }+ out.push(token.clone());+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ fn rewrite(args: &[&str]) -> Vec<String> {+ rewrite_var_shorthand(args.iter().map(OsString::from).collect())+ .into_iter()+ .map(|s| s.into_string().unwrap())+ .collect()+ }++ #[test]+ fn test_rewrite_var_shorthand() {+ // Shorthand gets rewritten+ assert_eq!(+ rewrite(&["wt", "hook", "pre-start", "--branch=feature/test"]),+ vec!["wt", "hook", "pre-start", "--var", "branch=feature/test"]+ );++ // Multiple shorthand args+ assert_eq!(+ rewrite(&[+ "wt",+ "hook",+ "post-merge",+ "--branch=main",+ "--target=develop"+ ]),+ vec![+ "wt",+ "hook",+ "post-merge",+ "--var",+ "branch=main",+ "--var",+ "target=develop"+ ]+ );++ // Shorthand mixed with known flags+ assert_eq!(+ rewrite(&[+ "wt",+ "hook",+ "pre-merge",+ "--yes",+ "--branch=feature",+ "--dry-run"+ ]),+ vec![+ "wt",+ "hook",+ "pre-merge",+ "--yes",+ "--var",+ "branch=feature",+ "--dry-run"+ ]+ );++ // Shorthand mixed with name filter positional+ assert_eq!(+ rewrite(&["wt", "hook", "pre-merge", "test", "--branch=feature"]),+ vec!["wt", "hook", "pre-merge", "test", "--var", "branch=feature"]+ );++ // Deprecated post-create alias still works+ assert_eq!(+ rewrite(&["wt", "hook", "post-create", "--branch=x"]),+ vec!["wt", "hook", "post-create", "--var", "branch=x"]+ );++ // Value containing equals sign+ assert_eq!(+ rewrite(&["wt", "hook", "pre-start", "--url=http://host?a=1"]),+ vec!["wt", "hook", "pre-start", "--var", "url=http://host?a=1"]+ );++ // Empty value+ assert_eq!(+ rewrite(&["wt", "hook", "pre-start", "--branch="]),+ vec!["wt", "hook", "pre-start", "--var", "branch="]+ );+ }++ #[test]+ fn test_rewrite_preserves_known_flags() {+ // --var=KEY=VAL is untouched (still handled by clap's parser)+ assert_eq!(+ rewrite(&["wt", "hook", "pre-start", "--var=branch=feature"]),+ vec!["wt", "hook", "pre-start", "--var=branch=feature"]+ );++ // --config=path is a global flag, not a variable shorthand+ assert_eq!(+ rewrite(&["wt", "hook", "pre-start", "--config=/tmp/config.toml"]),+ vec!["wt", "hook", "pre-start", "--config=/tmp/config.toml"]+ );++ // --dry-run, --yes, --foreground pass through+ assert_eq!(+ rewrite(&[+ "wt",+ "hook",+ "post-merge",+ "--yes",+ "--dry-run",+ "--foreground"+ ]),+ vec![+ "wt",+ "hook",+ "post-merge",+ "--yes",+ "--dry-run",+ "--foreground"+ ]+ );+ }++ #[test]+ fn test_rewrite_leaves_non_hook_subcommands_alone() {+ // `wt hook show` doesn't accept --var, so pass through unchanged+ assert_eq!(+ rewrite(&["wt", "hook", "show", "--expanded"]),+ vec!["wt", "hook", "show", "--expanded"]+ );++ // `wt hook approvals add --all` passes through unchanged+ assert_eq!(+ rewrite(&["wt", "hook", "approvals", "add", "--all"]),+ vec!["wt", "hook", "approvals", "add", "--all"]+ );++ // `wt switch --foo=bar` is not a hook command, pass through+ assert_eq!(+ rewrite(&["wt", "switch", "--foo=bar"]),+ vec!["wt", "switch", "--foo=bar"]+ );++ // `wt` alone+ assert_eq!(rewrite(&["wt"]), vec!["wt"]);+ }++ #[test]+ fn test_rewrite_skips_hook_in_flag_value_position() {+ // `wt -C hook pre-start` — here `hook` is a path, not the subcommand+ assert_eq!(+ rewrite(&["wt", "-C", "hook", "pre-start", "--branch=x"]),+ vec!["wt", "-C", "hook", "pre-start", "--branch=x"]+ );++ // `wt --config hook pre-start` — same guard+ assert_eq!(+ rewrite(&["wt", "--config", "hook", "pre-start", "--branch=x"]),+ vec!["wt", "--config", "hook", "pre-start", "--branch=x"]+ );+ }++ #[test]+ fn test_rewrite_handles_global_flags_before_hook() {+ // Global flags before `hook` shouldn't interfere+ assert_eq!(+ rewrite(&["wt", "-v", "hook", "pre-start", "--branch=x"]),+ vec!["wt", "-v", "hook", "pre-start", "--var", "branch=x"]+ );+ }++ #[test]+ fn test_rewrite_ignores_bare_hyphen_args() {+ // Bare `--`, single dash, and short flags pass through+ assert_eq!(+ rewrite(&["wt", "hook", "pre-start", "-y", "--branch=x"]),+ vec!["wt", "hook", "pre-start", "-y", "--var", "branch=x"]+ );++ // `--` with no key portion+ assert_eq!(+ rewrite(&["wt", "hook", "pre-start", "--=val"]),+ vec!["wt", "hook", "pre-start", "--=val"]+ );++ // `--` stops rewriting — args after it are positional+ assert_eq!(+ rewrite(&["wt", "hook", "pre-start", "--", "--branch=x"]),+ vec!["wt", "hook", "pre-start", "--", "--branch=x"]+ );+ }++ /// Verify HOOK_SUBCOMMANDS_WITH_VARS stays in sync with HookCommand variants+ /// that accept `--var`. If a hook subcommand is added/removed without updating+ /// the list, this test catches the drift.+ ///+ /// `post-create` is a deprecated alias for `pre-start` — it appears in the+ /// list (users can still type `wt hook post-create`) but not as a separate+ /// clap subcommand, so it's excluded from the reverse check.+ #[test]+ fn test_hook_subcommands_with_vars_matches_clap() {+ use crate::cli::Cli;+ use clap::CommandFactory;++ let app = Cli::command();+ let hook_cmd = app+ .get_subcommands()+ .find(|c| c.get_name() == "hook")+ .expect("hook subcommand exists");++ let subs_with_var: Vec<&str> = hook_cmd+ .get_subcommands()+ .filter(|c| c.get_arguments().any(|a| a.get_id() == "vars"))+ .map(|c| c.get_name())+ .collect();++ for name in &subs_with_var {+ assert!(+ HOOK_SUBCOMMANDS_WITH_VARS.contains(name),+ "Hook subcommand '{name}' accepts --var but is missing from \+ HOOK_SUBCOMMANDS_WITH_VARS. Add it so --KEY=VALUE shorthand works."+ );+ }++ // Deprecated aliases live in the list but not as separate clap subcommands+ let deprecated_aliases: &[&str] = &["post-create"];+ for name in HOOK_SUBCOMMANDS_WITH_VARS {+ if deprecated_aliases.contains(name) {+ continue;+ }+ assert!(+ subs_with_var.contains(name),+ "HOOK_SUBCOMMANDS_WITH_VARS contains '{name}' but that subcommand \+ doesn't accept --var. Remove it from the list."+ );+ }+ }++ /// Verify KNOWN_HOOK_LONG_FLAGS stays in sync with actual clap flags on+ /// hook subcommands. An unlisted flag would be silently rewritten to+ /// `--var`, which clap then rejects — but the error message would be+ /// confusing rather than helpful.+ #[test]+ fn test_known_hook_long_flags_matches_clap() {+ use crate::cli::Cli;+ use clap::CommandFactory;++ let app = Cli::command();+ let hook_cmd = app+ .get_subcommands()+ .find(|c| c.get_name() == "hook")+ .expect("hook subcommand exists");++ // Collect all long flags from hook subcommands that accept --var+ let mut clap_flags: std::collections::HashSet<String> = std::collections::HashSet::new();+ for sub in hook_cmd.get_subcommands() {+ if !sub.get_arguments().any(|a| a.get_id() == "vars") {+ continue;+ }+ for arg in sub.get_arguments() {+ if let Some(long) = arg.get_long() {+ clap_flags.insert(format!("--{long}"));+ }+ }+ }+ // Also include global flags that appear after `hook <type>`+ for arg in app.get_arguments() {+ if let Some(long) = arg.get_long() {+ clap_flags.insert(format!("--{long}"));+ }+ }++ for flag in &clap_flags {+ assert!(+ KNOWN_HOOK_LONG_FLAGS.contains(&flag.as_str()),+ "Hook subcommand flag '{flag}' is missing from KNOWN_HOOK_LONG_FLAGS. \+ Add it so --KEY=VALUE shorthand doesn't rewrite it."+ );+ }+ }+}+// Ordering: worktree lifecycle phases (switch → start → commit → merge →// remove), with each phase's `pre-` immediately before its `post-`. `show`// first (read-only introspection), `approvals` last (administration). Hidden@@ -41,7 +413,7 @@ pub enum HookCommand {#[arg(long)]dry_run: bool,- /// Override built-in template variable (KEY=VALUE)+ /// Set template variable (KEY=VALUE)#[arg(long = "var", value_name = "KEY=VALUE", value_parser = super::parse_key_val, action = clap::ArgAction::Append)]vars: Vec<(String, String)>,},@@ -69,7 +441,7 @@ pub enum HookCommand {#[arg(long)]foreground: bool,- /// Override built-in template variable (KEY=VALUE)+ /// Set template variable (KEY=VALUE)#[arg(long = "var", value_name = "KEY=VALUE", value_parser = super::parse_key_val, action = clap::ArgAction::Append)]vars: Vec<(String, String)>,},@@ -94,7 +466,7 @@ pub enum HookCommand {#[arg(long)]dry_run: bool,- /// Override built-in template variable (KEY=VALUE)+ /// Set template variable (KEY=VALUE)#[arg(long = "var", value_name = "KEY=VALUE", value_parser = super::parse_key_val, action = clap::ArgAction::Append)]vars: Vec<(String, String)>,},@@ -122,7 +494,7 @@ pub enum HookCommand {#[arg(long)]foreground: bool,- /// Override built-in template variable (KEY=VALUE)+ /// Set template variable (KEY=VALUE)#[arg(long = "var", value_name = "KEY=VALUE", value_parser = super::parse_key_val, action = clap::ArgAction::Append)]vars: Vec<(String, String)>,},@@ -144,7 +516,7 @@ pub enum HookCommand {#[arg(long)]dry_run: bool,- /// Override built-in template variable (KEY=VALUE)+ /// Set template variable (KEY=VALUE)#[arg(long = "var", value_name = "KEY=VALUE", value_parser = super::parse_key_val, action = clap::ArgAction::Append)]vars: Vec<(String, String)>,},@@ -172,7 +544,7 @@ pub enum HookCommand {#[arg(long)]foreground: bool,- /// Override built-in template variable (KEY=VALUE)+ /// Set template variable (KEY=VALUE)#[arg(long = "var", value_name = "KEY=VALUE", value_parser = super::parse_key_val, action = clap::ArgAction::Append)]vars: Vec<(String, String)>,},@@ -194,7 +566,7 @@ pub enum HookCommand {#[arg(long)]dry_run: bool,- /// Override built-in template variable (KEY=VALUE)+ /// Set template variable (KEY=VALUE)#[arg(long = "var", value_name = "KEY=VALUE", value_parser = super::parse_key_val, action = clap::ArgAction::Append)]vars: Vec<(String, String)>,},@@ -222,7 +594,7 @@ pub enum HookCommand {#[arg(long)]foreground: bool,- /// Override built-in template variable (KEY=VALUE)+ /// Set template variable (KEY=VALUE)#[arg(long = "var", value_name = "KEY=VALUE", value_parser = super::parse_key_val, action = clap::ArgAction::Append)]vars: Vec<(String, String)>,},@@ -244,7 +616,7 @@ pub enum HookCommand {#[arg(long)]dry_run: bool,- /// Override built-in template variable (KEY=VALUE)+ /// Set template variable (KEY=VALUE)#[arg(long = "var", value_name = "KEY=VALUE", value_parser = super::parse_key_val, action = clap::ArgAction::Append)]vars: Vec<(String, String)>,},@@ -272,7 +644,7 @@ pub enum HookCommand {#[arg(long)]foreground: bool,- /// Override built-in template variable (KEY=VALUE)+ /// Set template variable (KEY=VALUE)#[arg(long = "var", value_name = "KEY=VALUE", value_parser = super::parse_key_val, action = clap::ArgAction::Append)]vars: Vec<(String, String)>,},diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex cc8598f92..11df1d062 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -8,7 +8,7 @@ pub(crate) use config::{ConfigPluginsCommand, ConfigPluginsOpencodeCommand, ConfigShellCommand, DefaultBranchAction,HintsAction, LogsAction, MarkerAction, PreviousBranchAction, StateCommand, VarsAction,};-pub(crate) use hook::HookCommand;+pub(crate) use hook::{HookCommand, rewrite_var_shorthand};pub(crate) use list::ListSubcommand;pub(crate) use step::StepCommand;@@ -16,34 +16,25 @@ use clap::builder::styling::{AnsiColor, Color, Styles};use clap::{Args, Command, CommandFactory, Parser, Subcommand, ValueEnum};use std::ffi::OsString;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.+/// Parse `KEY=VALUE` string into a tuple for `--var` on hook commands.///-/// 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).-pub(super) 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()))+/// Accepts any variable name — built-in template variables (branch, target, …)+/// are overridden; custom names are injected into the template context so hooks+/// can reference `{{ my_var }}`. Hyphens in key names are canonicalized to+/// underscores (minijinja parses `{{ my-var }}` as subtraction).+///+/// Values are shell-escaped during template expansion (see `expand_template`).+pub(crate) fn parse_key_val(s: &str) -> Result<(String, String), String> {+ let (key, value) = parse_vars_assignment(s)?;+ Ok((key.replace('-', "_"), value))}/// Parse KEY=VALUE string for `wt config state vars set`.///-/// Like `parse_key_val`, but without template variable name validation.+/// Like `parse_key_val`, but without hyphen→underscore canonicalization./// Key validation is deferred to `validate_vars_key` in the command handler.pub(super) fn parse_vars_assignment(s: &str) -> Result<(String, String), String> {let (key, value) = s@@ -1404,14 +1395,13 @@ $ wt hook pre-merge test build # Run hooks named "test" and "build"$ wt hook pre-merge user: # Run all user hooks$ wt hook pre-merge project: # Run all project hooks$ wt hook pre-merge user:test # Run only user's "test" hook-$ wt hook pre-merge project:test # Run only project's "test" hook$ wt hook pre-merge --yes # Skip approval prompts (for CI)-$ wt hook pre-start --var branch=feature/test # Override template variable+$ wt hook pre-start --branch=feature/test # Override a 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 overrides built-in template variables — useful for testing hooks with different contexts without switching to that context.+Any unknown `--KEY=VALUE` flag is treated as a template variable assignment — useful for testing hooks with different contexts without switching to that context. The long form `--var KEY=VALUE` is equivalent and remains the escape hatch when a variable name collides with a built-in flag (e.g. `config`, `yes`, `dry-run`, `foreground`, `verbose`).# Pipeline Ordering [experimental]diff --git a/src/commands/alias.rs b/src/commands/alias.rsindex 3a70852d1..a029b9945 100644--- a/src/commands/alias.rs+++ b/src/commands/alias.rs@@ -120,20 +120,21 @@ impl AliasOptions {if i >= args.len() {bail!("--var requires a KEY=VALUE argument");}- let pair = parse_var(&args[i])?;+ let pair =+ crate::cli::parse_key_val(&args[i]).map_err(|e| anyhow::anyhow!(e))?;vars.push(pair);}arg if arg.starts_with("--var=") => {- let pair = parse_var(arg.strip_prefix("--var=").unwrap())?;+ let pair = crate::cli::parse_key_val(arg.strip_prefix("--var=").unwrap())+ .map_err(|e| anyhow::anyhow!(e))?;vars.push(pair);}arg if arg.starts_with("--") => {let rest = &arg[2..];- if let Some((key, value)) = rest.split_once('=') {- if key.is_empty() {- bail!("Variable name must not be empty (got '--={value}')");- }- vars.push((key.replace('-', "_"), value.to_string()));+ if rest.contains('=') {+ let pair =+ crate::cli::parse_key_val(rest).map_err(|e| anyhow::anyhow!(e))?;+ vars.push(pair);} else {bail!("Unknown flag '{arg}' for alias '{name}' (use --{rest}=VALUE to pass a variable)"@@ -156,14 +157,6 @@ impl AliasOptions {}}-fn parse_var(s: &str) -> anyhow::Result<(String, String)> {- let (key, value) = s.split_once('=').context("--var value must be KEY=VALUE")?;- if key.is_empty() {- bail!("--var key must not be empty (got '={value}')");- }- Ok((key.replace('-', "_"), value.to_string()))-}-/// Determine whether an alias requires project-config approval.////// Returns the project-config commands for this alias, if any exist.@@ -781,11 +774,11 @@ cmd = [use insta::assert_snapshot;assert_snapshot!(parse(&[]).unwrap_err(), @"Missing alias name");assert_snapshot!(parse(&["deploy", "--var"]).unwrap_err(), @"--var requires a KEY=VALUE argument");- assert_snapshot!(parse(&["deploy", "--var", "noequals"]).unwrap_err(), @"--var value must be KEY=VALUE");+ assert_snapshot!(parse(&["deploy", "--var", "noequals"]).unwrap_err(), @"invalid KEY=VALUE: no `=` found in `noequals`");assert_snapshot!(parse(&["deploy", "--verbose"]).unwrap_err(), @"Unknown flag '--verbose' for alias 'deploy' (use --verbose=VALUE to pass a variable)");assert_snapshot!(parse(&["deploy", "arg1"]).unwrap_err(), @"Unexpected argument 'arg1' for alias 'deploy'");- assert_snapshot!(parse(&["deploy", "--var", "=value"]).unwrap_err(), @"--var key must not be empty (got '=value')");- assert_snapshot!(parse(&["deploy", "--=value"]).unwrap_err(), @"Variable name must not be empty (got '--=value')");+ assert_snapshot!(parse(&["deploy", "--var", "=value"]).unwrap_err(), @"invalid KEY=VALUE: key cannot be empty");+ assert_snapshot!(parse(&["deploy", "--=value"]).unwrap_err(), @"invalid KEY=VALUE: key cannot be empty");}#[test]diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex d11b6d177..ffdd6effe 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -26,6 +26,7 @@ use super::command_executor::build_hook_context;use super::command_executor::CommandContext;use super::context::CommandEnv;+use super::hook_filter::{HookSource, ParsedFilter};use super::hooks::{HookCommandSpec, HookFailureStrategy, check_name_filter_matched, command_summary_name,count_sourced_commands, prepare_background_hooks, prepare_sourced_steps, run_hook_with_filter,@@ -157,6 +158,83 @@ fn build_manual_hook_extra_vars<'a>(vars}+/// Warn about user-provided `--var` flags that aren't referenced by any template+/// in the hooks that will run. Catches typos in variable names that would+/// otherwise silently have no effect.+///+/// Only checks top-level variable references (not `{{ vars.foo }}`). Name+/// filters are respected — if the user runs `wt hook pre-merge test` and `test`+/// doesn't use the var but `build` does, we still warn because `build` won't run.+fn warn_unreferenced_custom_vars(+ user_config: Option<&CommandConfig>,+ project_config: Option<&CommandConfig>,+ name_filters: &[String],+ custom_vars: &[(String, String)],+) {+ if custom_vars.is_empty() {+ return;+ }++ let parsed_filters: Vec<ParsedFilter<'_>> = name_filters+ .iter()+ .map(|f| ParsedFilter::parse(f))+ .collect();+ let filter_names: Vec<&str> = parsed_filters+ .iter()+ .filter(|f| !f.name.is_empty())+ .map(|f| f.name)+ .collect();++ // Empty environment: every variable reference in the template appears as+ // "undeclared", giving us the full set of referenced top-level names.+ let env = minijinja::Environment::new();+ let mut referenced: std::collections::HashSet<String> = std::collections::HashSet::new();++ for (source, config) in [+ (HookSource::User, user_config),+ (HookSource::Project, project_config),+ ] {+ let Some(config) = config else { continue };++ // Skip this source if no filter matches it+ if !parsed_filters.is_empty() && !parsed_filters.iter().any(|f| f.matches_source(source)) {+ continue;+ }++ for step in config.steps() {+ let commands: &[worktrunk::config::Command] = match step {+ worktrunk::config::HookStep::Single(cmd) => std::slice::from_ref(cmd),+ worktrunk::config::HookStep::Concurrent(cmds) => cmds.as_slice(),+ };+ for cmd in commands {+ // If names are filtered, skip commands whose name doesn't match+ if !filter_names.is_empty()+ && !cmd+ .name+ .as_deref()+ .is_some_and(|n| filter_names.contains(&n))+ {+ continue;+ }+ if let Ok(tmpl) = env.template_from_str(&cmd.template) {+ referenced.extend(tmpl.undeclared_variables(false));+ }+ }+ }+ }++ for (key, _) in custom_vars {+ if !referenced.contains(key) {+ eprintln!(+ "{}",+ warning_message(cformat!(+ "--var <bold>{key}</> is not referenced by any hook template — typo?"+ ))+ );+ }+ }+}+/// Handle `wt hook` command////// When explicitly invoking hooks, ALL hooks run (both user and project).@@ -222,6 +300,9 @@ pub fn run_hook(return Ok(());}+ // Warn about typos in --var flags — vars that no template references+ warn_unreferenced_custom_vars(user_config, proj_config, name_filters, custom_vars);+// Build extra vars per hook type (shared by dry-run and execution paths)let default_branch = repo.default_branch();let worktree_path_str = worktrunk::path::to_posix_path(&ctx.worktree_path.to_string_lossy());diff --git a/src/config/expansion.rs b/src/config/expansion.rsindex 998452cdc..11b32134d 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -26,8 +26,6 @@ use crate::styling::{////// 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","owner",diff --git a/src/main.rs b/src/main.rsindex 440401834..5f0a56ac0 100644--- a/src/main.rs+++ b/src/main.rs@@ -906,7 +906,8 @@ fn parse_cli() -> Option<Cli> {// When available, use built-in setting. Until then, could use try_parse() to intercept// MissingRequiredArgument errors and print custom messages with ValueEnum::value_variants().let cmd = cli::build_command();- let matches = cmd.try_get_matches().unwrap_or_else(|e| {+ let args = cli::rewrite_var_shorthand(std::env::args_os().collect());+ let matches = cmd.try_get_matches_from(args).unwrap_or_else(|e| {enhance_and_exit_error(e);});Some(Cli::from_arg_matches(&matches).unwrap_or_else(|e| e.exit()))diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex 28d3b2d8e..968f71ae3 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -1906,20 +1906,33 @@ fn test_var_flag_invalid_format_fails() {);}-#[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"])+#[rstest]+fn test_var_flag_custom_variable(repo: TestRepo) {+ // Custom variable names (not built-in template vars) are accepted and+ // injected into the template context, matching alias behavior.+ repo.write_test_config(+ r#"[post-create]+test = "echo '{{ custom_var }}' > custom_var_output.txt"+"#,+ );++ let output = repo+ .wt_command()+ .args(["hook", "post-create", "--yes", "--var", "custom_var=hello"]).output()- .expect("Failed to run wt");+ .expect("Failed to run wt hook");- assert!(!output.status.success(), "Unknown variable should fail");+ assert!(+ output.status.success(),+ "Custom variable should succeed, stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );- let stderr = String::from_utf8_lossy(&output.stderr);+ let output_file = repo.root_path().join("custom_var_output.txt");+ let contents = fs::read_to_string(&output_file).unwrap();assert!(- stderr.contains("unknown variable"),- "Error should mention unknown variable, got: {stderr}"+ contents.contains("hello"),+ "Custom variable should be expanded, got: {contents}");}@@ -1956,6 +1969,196 @@ test = "echo '{{ target }}' > target_output.txt");}+#[rstest]+fn test_var_shorthand_overrides_template_variable(repo: TestRepo) {+ // `--KEY=VALUE` is equivalent to `--var KEY=VALUE` for template variables.+ repo.write_test_config(+ r#"[post-create]+test = "echo '{{ branch }}' > shorthand_output.txt"+"#,+ );++ let output = repo+ .wt_command()+ .args(["hook", "post-create", "--yes", "--branch=SHORTHAND_BRANCH"])+ .output()+ .expect("Failed to run wt hook");++ assert!(+ output.status.success(),+ "Hook should succeed, stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ let output_file = repo.root_path().join("shorthand_output.txt");+ let contents = fs::read_to_string(&output_file).unwrap();+ assert!(+ contents.contains("SHORTHAND_BRANCH"),+ "Shorthand should override template variable, got: {contents}"+ );+}++#[rstest]+fn test_var_shorthand_mixed_with_long_form(repo: TestRepo) {+ // Shorthand and `--var` forms coexist in the same invocation.+ repo.write_test_config(+ r#"[post-create]+test = "echo '{{ branch }} {{ target }}' > mixed_output.txt"+"#,+ );++ let output = repo+ .wt_command()+ .args([+ "hook",+ "post-create",+ "--yes",+ "--branch=SHORT",+ "--var",+ "target=LONG",+ ])+ .output()+ .expect("Failed to run wt hook");++ assert!(output.status.success());++ let output_file = repo.root_path().join("mixed_output.txt");+ let contents = fs::read_to_string(&output_file).unwrap();+ assert!(+ contents.contains("SHORT") && contents.contains("LONG"),+ "Both forms should coexist, got: {contents}"+ );+}++#[rstest]+fn test_var_shorthand_custom_variable(repo: TestRepo) {+ // Custom variable names (not built-in template vars) are accepted and+ // injected into the template context, matching alias behavior. Hyphens in+ // variable names are canonicalized to underscores.+ repo.write_test_config(+ r#"[post-create]+test = "echo '{{ my_env }}' > custom_output.txt"+"#,+ );++ let output = repo+ .wt_command()+ .args(["hook", "post-create", "--yes", "--my-env=staging"])+ .output()+ .expect("Failed to run wt hook");++ assert!(+ output.status.success(),+ "Custom variable should succeed, stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ let output_file = repo.root_path().join("custom_output.txt");+ let contents = fs::read_to_string(&output_file).unwrap();+ assert!(+ contents.contains("staging"),+ "Custom variable with hyphens should be canonicalized and expanded, got: {contents}"+ );+}++#[rstest]+fn test_var_unreferenced_warning(repo: TestRepo) {+ // A --var whose key isn't referenced by any hook template should produce a+ // warning — catches typos that would otherwise silently have no effect.+ // The hook still runs.+ repo.write_test_config(+ r#"[post-create]+test = "echo '{{ branch }}' > unref_output.txt"+"#,+ );++ let output = repo+ .wt_command()+ .args(["hook", "post-create", "--yes", "--unused_var=value"])+ .output()+ .expect("Failed to run wt hook");++ assert!(+ output.status.success(),+ "Hook should still run despite the warning, stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("unused_var") && stderr.contains("not referenced"),+ "Expected unreferenced-var warning, got: {stderr}"+ );+}++#[rstest]+fn test_var_unreferenced_warning_respects_name_filter(repo: TestRepo) {+ // When a name filter excludes the hook that uses the var, still warn —+ // the filtered-out hook won't run, so the var has no effect.+ repo.write_test_config(+ r#"[post-create]+alpha = "echo '{{ branch }}' > alpha.txt"+beta = "echo '{{ my_env }}' > beta.txt"+"#,+ );++ let output = repo+ .wt_command()+ .args(["hook", "post-create", "--yes", "alpha", "--my-env=staging"])+ .output()+ .expect("Failed to run wt hook");++ assert!(output.status.success());++ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("my_env") && stderr.contains("not referenced"),+ "Expected warning for --my-env when only 'alpha' runs, got: {stderr}"+ );+}++#[rstest]+fn test_var_referenced_no_warning(repo: TestRepo) {+ // A --var that IS referenced by a template produces no warning.+ repo.write_test_config(+ r#"[post-create]+test = "echo '{{ my_env }}' > ref_output.txt"+"#,+ );++ let output = repo+ .wt_command()+ .args(["hook", "post-create", "--yes", "--my-env=staging"])+ .output()+ .expect("Failed to run wt hook");++ assert!(output.status.success());++ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ !stderr.contains("not referenced"),+ "Expected no warning, got: {stderr}"+ );+}++#[test]+fn test_var_shorthand_does_not_leak_into_hook_show() {+ // `wt hook show` doesn't accept `--var`, so shorthand preprocessing must+ // leave its argv alone — an unknown flag should still produce clap's+ // "unexpected argument" error, not a template-variable error.+ let output = std::process::Command::new(env!("CARGO_BIN_EXE_wt"))+ .args(["hook", "show", "--branch=feature"])+ .output()+ .expect("Failed to run wt");++ assert!(!output.status.success());+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("unexpected argument") || stderr.contains("--branch"),+ "Expected clap to reject --branch on `hook show`, got: {stderr}"+ );+}+#[rstest]fn test_var_flag_deprecated_alias_works(repo: TestRepo) {// Test that deprecated variable aliases (main_worktree, repo_root, worktree) can be overridden