Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(hook): unify hook argument syntax with alias smart routing (#2313)
Maximilian Roose4fab6c79105
diff --git a/docs/content/extending.md b/docs/content/extending.mdindex d52494cc7..58f2ae0d6 100644--- a/docs/content/extending.md+++ b/docs/content/extending.md@@ -243,3 +243,24 @@ Arguments pass through verbatim, stdio is inherited, and the child's exit code p### Examples- [`worktrunk-sync`](https://github.com/pablospe/worktrunk-sync) — rebases stacked worktree branches in dependency order, inferring the tree from git history. Install with `cargo install worktrunk-sync`, then run as `wt sync`.++## Reference: hooks vs. aliases++Hooks and aliases share a template-variable model and a smart-routing rule for `--KEY=VALUE` shorthand (bind if the template references the key, else forward to `{{ args }}`), so a pattern learned on one surface mostly transfers to the other. A few things differ.++<details>+<summary>Interface differences</summary>++| Axis | Hooks | Aliases |+|------|-------|---------|+| Invocation | `wt hook <type> [args...]` — nested under the `hook` built-in | `wt <name> [args...]` — top-level |+| Bare positionals | Filter names (`wt hook pre-merge test build` runs only `test` and `build`) | Forwarded to `{{ args }}` |+| Reach `{{ args }}` from positionals | Must use `--` (`wt hook pre-merge -- extra`) | Any bare positional lands there |+| Approval skip flag | Post-subcommand `--yes` / `-y` supported (`wt hook pre-merge --yes`) | Only the global form (`wt -y <alias>`); post-alias `--yes` falls through to `{{ args }}` |+| Source discrimination | `user:` / `project:` / `user:name` / `project:name` filter syntax | Run user first, then project; no filter syntax |+| Force-bind escape | `--var KEY=VALUE` (deprecated — prefer `--KEY=VALUE` — but still force-binds) | None — smart routing is the only path |+| `--help` | Clap-rendered per hook type (`wt hook --help`, `wt hook pre-merge --help`) | `wt <alias> --help` redirects to `wt config alias show` / `dry-run` |+| Inspection | `wt hook show [type] [--expanded]` | `wt config alias show <name>` / `wt config alias dry-run <name>` |+| Template-context extras | `hook_type`, `hook_name`, per-type operation vars (`base`, `target`, `pr_number`, …) | `args` on top of the shared base variables |++</details>diff --git a/docs/content/hook.md b/docs/content/hook.mdindex fa7638b0a..fbadca69f 100644--- a/docs/content/hook.md+++ b/docs/content/hook.md@@ -138,6 +138,7 @@ Hooks can use template variables that expand at runtime:| exec | `{{ cwd }}` | Directory where the hook command runs || | `{{ hook_type }}` | Hook type being run (e.g. `pre-start`, `pre-merge`) || | `{{ hook_name }}` | Hook command name (if named) |+| | `{{ args }}` | Tokens forwarded from the CLI — see [Running Hooks Manually](#running-hooks-manually) || user | `{{ vars.<key> }}` | Per-branch variables from [`wt config state vars`](@/config.md#wt-config-state-vars) |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:@@ -229,11 +230,17 @@ 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 --yes # Skip approval prompts (for CI)|||wt hook pre-start --branch=feature/test # Override a 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|||wt hook pre-merge -- --extra args # Forward tokens into __WT_OPEN2__ args __WT_CLOSE2__") }}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.-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`).+## Passing values++`--KEY=VALUE` binds `KEY` whenever `{{ KEY }}` appears in any command of the hook — the same smart-routing rule `wt <alias>` uses. Built-in variables can be overridden: `--branch=foo` sets `{{ branch }}` inside hook templates (the worktree's actual branch doesn't move). Hyphens in keys become underscores: `--my-var=x` sets `{{ my_var }}`.++Any `--KEY=VALUE` whose key isn't referenced by a hook template forwards into `{{ args }}` as a literal `--KEY=VALUE` token. Tokens after `--` also forward into `{{ args }}` verbatim. `{{ args }}` renders as a space-joined, shell-escaped string; index with `{{ args[0] }}`, loop with `{% for a in args %}…{% endfor %}`, count with `{{ args | length }}`.++The long form `--var KEY=VALUE` is deprecated but still supported. It force-binds regardless of whether any hook template references `KEY` — useful when a template only references the key conditionally (e.g. `{% if override %}…{% endif %}`).# Pipeline Orderingdiff --git a/skills/worktrunk/reference/extending.md b/skills/worktrunk/reference/extending.mdindex 07d1cb908..808306e57 100644--- a/skills/worktrunk/reference/extending.md+++ b/skills/worktrunk/reference/extending.md@@ -250,3 +250,24 @@ Arguments pass through verbatim, stdio is inherited, and the child's exit code p### Examples- [`worktrunk-sync`](https://github.com/pablospe/worktrunk-sync) — rebases stacked worktree branches in dependency order, inferring the tree from git history. Install with `cargo install worktrunk-sync`, then run as `wt sync`.++## Reference: hooks vs. aliases++Hooks and aliases share a template-variable model and a smart-routing rule for `--KEY=VALUE` shorthand (bind if the template references the key, else forward to `{{ args }}`), so a pattern learned on one surface mostly transfers to the other. A few things differ.++<details>+<summary>Interface differences</summary>++| Axis | Hooks | Aliases |+|------|-------|---------|+| Invocation | `wt hook <type> [args...]` — nested under the `hook` built-in | `wt <name> [args...]` — top-level |+| Bare positionals | Filter names (`wt hook pre-merge test build` runs only `test` and `build`) | Forwarded to `{{ args }}` |+| Reach `{{ args }}` from positionals | Must use `--` (`wt hook pre-merge -- extra`) | Any bare positional lands there |+| Approval skip flag | Post-subcommand `--yes` / `-y` supported (`wt hook pre-merge --yes`) | Only the global form (`wt -y <alias>`); post-alias `--yes` falls through to `{{ args }}` |+| Source discrimination | `user:` / `project:` / `user:name` / `project:name` filter syntax | Run user first, then project; no filter syntax |+| Force-bind escape | `--var KEY=VALUE` (deprecated — prefer `--KEY=VALUE` — but still force-binds) | None — smart routing is the only path |+| `--help` | Clap-rendered per hook type (`wt hook --help`, `wt hook pre-merge --help`) | `wt <alias> --help` redirects to `wt config alias show` / `dry-run` |+| Inspection | `wt hook show [type] [--expanded]` | `wt config alias show <name>` / `wt config alias dry-run <name>` |+| Template-context extras | `hook_type`, `hook_name`, per-type operation vars (`base`, `target`, `pr_number`, …) | `args` on top of the shared base variables |++</details>diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.mdindex a5e92eb4c..fbeafffa0 100644--- a/skills/worktrunk/reference/hook.md+++ b/skills/worktrunk/reference/hook.md@@ -129,6 +129,7 @@ Hooks can use template variables that expand at runtime:| exec | `{{ cwd }}` | Directory where the hook command runs || | `{{ hook_type }}` | Hook type being run (e.g. `pre-start`, `pre-merge`) || | `{{ hook_name }}` | Hook command name (if named) |+| | `{{ args }}` | Tokens forwarded from the CLI — see [Running Hooks Manually](#running-hooks-manually) || user | `{{ vars.<key> }}` | Per-branch variables from [`wt config state vars`](https://worktrunk.dev/config/#wt-config-state-vars) |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:@@ -229,11 +230,18 @@ $ 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 --yes # Skip approval prompts (for CI)$ wt hook pre-start --branch=feature/test # Override a template variable+$ wt hook pre-merge -- --extra args # Forward tokens into {{ args }}```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.-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`).+## Passing values++`--KEY=VALUE` binds `KEY` whenever `{{ KEY }}` appears in any command of the hook — the same smart-routing rule `wt <alias>` uses. Built-in variables can be overridden: `--branch=foo` sets `{{ branch }}` inside hook templates (the worktree's actual branch doesn't move). Hyphens in keys become underscores: `--my-var=x` sets `{{ my_var }}`.++Any `--KEY=VALUE` whose key isn't referenced by a hook template forwards into `{{ args }}` as a literal `--KEY=VALUE` token. Tokens after `--` also forward into `{{ args }}` verbatim. `{{ args }}` renders as a space-joined, shell-escaped string; index with `{{ args[0] }}`, loop with `{% for a in args %}…{% endfor %}`, count with `{{ args | length }}`.++The long form `--var KEY=VALUE` is deprecated but still supported. It force-binds regardless of whether any hook template references `KEY` — useful when a template only references the key conditionally (e.g. `{% if override %}…{% endif %}`).# Pipeline Ordering [experimental]diff --git a/src/cli/hook.rs b/src/cli/hook.rsindex bf75c849f..4612361cb 100644--- a/src/cli/hook.rs+++ b/src/cli/hook.rs@@ -1,20 +1,60 @@-use std::ffi::{OsStr, OsString};-+//! `wt hook` CLI surface.+//!+//! Hook invocations share a single `#[command(external_subcommand)]` catch-all+//! ([`HookCommand::Run`]) that captures everything after `wt hook <type>` as+//! raw argv — including the `--` literal-forward separator, which clap eats+//! in a trailing_var_arg positional but preserves in external_subcommand.+//! [`HookOptions::parse`] walks the argv with the same smart-routing rule as+//! `AliasOptions::parse`: `--KEY=VALUE` binds `{{ KEY }}` when any hook+//! template references it; otherwise the token forwards to `{{ args }}`.+//!+//! The collapse mirrors the alias pattern. Completion for hook type names+//! and help-rendering of `wt hook --help` / `wt hook <type> --help` both go+//! through `completion::inject_hook_subcommands`, which grafts stub+//! subcommands onto an augmented `Command` tree used only for those two+//! surfaces — the real parser still dispatches through `HookCommand::Run`.+//!+//! # External interface: hooks vs. aliases+//!+//! Both surfaces share the core smart-routing rule (`--KEY=VALUE` binds if+//! referenced, else forwards to `{{ args }}`), post-`--` literal forwarding,+//! hyphen-to-underscore key canonicalization, and the `ShellArgs` rendering+//! of `{{ args }}`. Where they diverge:+//!+//! | Axis | Hooks | Aliases |+//! |------|-------|---------|+//! | Invocation | `wt hook <type> [args...]` — nested external_subcommand under the `hook` built-in | `wt <name> [args...]` — top-level external_subcommand (`Cli::Custom`) |+//! | Bare positionals | **Filter names** (`wt hook pre-merge test build` runs only `test` and `build`) | Forwarded to `{{ args }}` |+//! | Reach `{{ args }}` from positionals | Must use `--` (`wt hook pre-merge -- extra`) | Any bare positional lands there |+//! | Approval skip flag | Post-subcommand `--yes` / `-y` recognized by [`HookOptions::parse`] | Only the global form (`wt -y <alias>`); post-alias `--yes` falls through to `{{ args }}` |+//! | Source discrimination | `user:` / `project:` / `user:name` / `project:name` filter syntax | Aliases run user first, then project; no filter syntax |+//! | Force-bind escape | `--var KEY=VALUE` (deprecated; emits warning; still binds unconditionally) | No equivalent — smart routing is the only path |+//! | Name validation | [`parse_hook_type`] validates the hook type with a did-you-mean hint | No validation — unknown alias falls through to `wt-<name>` PATH binary lookup |+//! | `--help` | Clap-rendered via injected stubs (both `wt hook --help` and `wt hook <type> --help`) | `wt <alias> --help` redirects to `wt config alias show` / `dry-run` |+//! | Inspection | `wt hook show [type] [--expanded]` | `wt config alias show <name>` / `dry-run <name>` |+//! | Trust / approval | User hooks trusted; project hooks require approval per-hook-type | User aliases trusted; project aliases require approval per-alias |+//! | Hook-specific flags | `--dry-run`, `--foreground`, `--var` parsed by [`HookOptions::parse`] | None — aliases have no CLI-level knobs beyond smart routing |+//! | Template-context extras | `hook_type`, `hook_name`, per-type operation vars (`base`, `target`, `pr_number`, …) | `args` only, on top of the shared base vars |++use std::ffi::OsString;++use anyhow::{Context, bail};use clap::Subcommand;+use worktrunk::HookType;use super::config::ApprovalsCommand;-/// Hook subcommands that accept `--var KEY=VALUE` (and the `--KEY=VALUE` shorthand).-///-/// Excludes `show`, `run-pipeline`, and the deprecated `approvals` (now under-/// `wt config approvals`), which don't expand template variables. `post-create`-/// is the deprecated alias for `pre-start`.-const HOOK_SUBCOMMANDS_WITH_VARS: &[&str] = &[+/// Canonical list of hook type names accepted after `wt hook`. Shared by+/// [`parse_hook_type`], `completion::inject_hook_subcommands`, and the+/// `wt hook show` value parser so drift is caught by tests rather than at+/// runtime. `post-create` is the deprecated alias for `pre-start`; it's+/// accepted by [`parse_hook_type`] but not listed here — completion lists+/// the canonical names only.+pub const HOOK_TYPE_NAMES: &[&str] = &["pre-switch","post-switch","pre-start","post-start",- "post-create","pre-commit","post-commit","pre-merge",@@ -23,602 +63,411 @@ const HOOK_SUBCOMMANDS_WITH_VARS: &[&str] = &["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",-];+// Ordering: `show` first (read-only introspection), then the external+// subcommand catch-all, then hidden commands. Hook types aren't listed+// as clap variants — `Run` catches them.+/// Run configured hooks+#[derive(Subcommand)]+pub enum HookCommand {+ /// Show configured hooks+ ///+ /// Lists user and project hooks. Project hooks show approval status (❓ = needs approval).+ Show {+ /// Hook type to show (default: all)+ #[arg(value_parser = ["pre-switch", "post-switch", "pre-start", "post-start", "pre-commit", "post-commit", "pre-merge", "post-merge", "pre-remove", "post-remove"])]+ hook_type: Option<String>,-/// Rewrite `wt hook <type> --KEY=VALUE` into `wt hook <type> --var KEY=VALUE`-/// for unknown `--key=value` flags, so hook invocations can use the same-/// `--KEY=VALUE` shorthand that `wt <alias>` supports. (Aliases route via-/// template references; hooks have no such discriminator, so the rewrite-/// here is an unconditional "unknown `--KEY=VALUE` means var".)-///-/// Only args after a `hook <type>` prefix are touched, and only when `<type>`-/// is a hook that accepts `--var`.+ /// Show expanded commands with current variables+ #[arg(long)]+ expanded: bool,+ },++ /// Internal: run a serialized pipeline from stdin+ #[command(hide = true, name = "run-pipeline")]+ RunPipeline,++ /// Deprecated: use `wt config approvals` instead+ #[command(hide = true)]+ Approvals {+ #[command(subcommand)]+ action: ApprovalsCommand,+ },++ /// Captures `wt hook <type> [ARGS...]` as raw argv. First element is the+ /// hook type name (clap doesn't validate — [`HookOptions::parse`] does,+ /// with a did-you-mean error for typos). External_subcommand preserves+ /// the `--` literal-forward separator, which a `trailing_var_arg`+ /// positional would eat.+ #[command(external_subcommand)]+ Run(Vec<OsString>),+}++/// Parsed form of `wt hook <type> [ARGS...]` — hook type plus every flag,+/// filter name, shorthand binding, and forwarded arg, routed per the alias+/// smart-routing model. `run_hook` consumes this.+#[derive(Debug)]+pub struct HookOptions {+ pub hook_type: HookType,+ pub yes: bool,+ pub dry_run: bool,+ /// `Some(true)` forces foreground for `post-*` hooks that normally run+ /// in the background. `None` defers to the hook type's default.+ pub foreground: Option<bool>,+ /// Positional filter names (`wt hook pre-merge test build`).+ pub name_filters: Vec<String>,+ /// Explicit `--var KEY=VALUE` bindings (deprecated force-bind).+ pub explicit_vars: Vec<(String, String)>,+ /// Raw `--KEY=VALUE` shorthand tokens, stored as `KEY=VALUE` (the+ /// original hyphenated key is preserved for forwarding to `{{ args }}`+ /// when unreferenced).+ pub shorthand_vars: Vec<String>,+ /// Tokens after `--` that forward to `{{ args }}` verbatim.+ pub forwarded_args: Vec<String>,+}++/// Map a hook type name to its [`HookType`] variant. Emits a did-you-mean+/// hint on typos (same `did_you_mean` helper used for unknown subcommands).///-/// 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;+/// `post-create` is the deprecated alias for `pre-start` — accepted here so+/// scripted invocations keep working. The deprecation warning is emitted by+/// the config loader when `[post-create]` appears in config; CLI invocations+/// map silently to `pre-start`.+pub fn parse_hook_type(name: &str) -> anyhow::Result<HookType> {+ match name {+ "pre-switch" => Ok(HookType::PreSwitch),+ "post-switch" => Ok(HookType::PostSwitch),+ "pre-start" | "post-create" => Ok(HookType::PreStart),+ "post-start" => Ok(HookType::PostStart),+ "pre-commit" => Ok(HookType::PreCommit),+ "post-commit" => Ok(HookType::PostCommit),+ "pre-merge" => Ok(HookType::PreMerge),+ "post-merge" => Ok(HookType::PostMerge),+ "pre-remove" => Ok(HookType::PreRemove),+ "post-remove" => Ok(HookType::PostRemove),+ other => {+ let candidates = HOOK_TYPE_NAMES.iter().map(|s| s.to_string());+ let suggestions = crate::commands::did_you_mean(other, candidates);+ if let Some(suggestion) = suggestions.first() {+ bail!("unknown hook type: `{other}` (did you mean `{suggestion}`?)");+ }+ bail!(+ "unknown hook type: `{other}` (expected one of: {})",+ HOOK_TYPE_NAMES.join(", ")+ );}- 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}")));+impl HookOptions {+ /// Parse `args` as `<hook-type> [FLAGS...] [NAME...] [--KEY=VALUE...] [-- TOKENS...]`.+ ///+ /// First element is the hook type name. Remaining tokens are walked+ /// left-to-right under this grammar:+ ///+ /// - `--yes` / `-y` — set `yes` (equivalent to the global `-y` flag,+ /// supported post-type so `wt hook pre-merge --yes` works).+ /// - `--dry-run` — set `dry_run`.+ /// - `--foreground` — set `foreground = Some(true)` (post-* hooks).+ /// - `--var KEY=VALUE` / `--var=KEY=VALUE` — explicit force-bind;+ /// appended to `explicit_vars`. Deprecated; dispatch warns.+ /// - `--KEY=VALUE` (other `--` flag with `=`) — captured as shorthand+ /// for `run_hook` to smart-route (bind if referenced, else forward).+ /// - `--` — literal-forward escape; every later token goes into+ /// `forwarded_args`.+ /// - Anything else — positional filter name.+ pub fn parse(args: &[OsString]) -> anyhow::Result<Self> {+ let first = args+ .first()+ .and_then(|s| s.to_str())+ .context("missing hook type after `wt hook`")?;+ let hook_type = parse_hook_type(first)?;++ let mut yes = false;+ let mut dry_run = false;+ let mut foreground: Option<bool> = None;+ let mut name_filters: Vec<String> = Vec::new();+ let mut explicit_vars: Vec<(String, String)> = Vec::new();+ let mut shorthand_vars: Vec<String> = Vec::new();+ let mut forwarded_args: Vec<String> = Vec::new();++ let mut literal_mode = false;+ let mut i = 1;+ while i < args.len() {+ let arg = args[i]+ .to_str()+ .with_context(|| format!("non-UTF-8 argument at position {i}"))?;+ if literal_mode {+ forwarded_args.push(arg.to_string());+ i += 1;continue;}+ match arg {+ "--" => {+ literal_mode = true;+ i += 1;+ continue;+ }+ "--yes" | "-y" => {+ yes = true;+ i += 1;+ continue;+ }+ "--dry-run" => {+ dry_run = true;+ i += 1;+ continue;+ }+ "--foreground" => {+ foreground = Some(true);+ i += 1;+ continue;+ }+ "--var" => {+ let value = args+ .get(i + 1)+ .and_then(|s| s.to_str())+ .context("--var requires KEY=VALUE")?;+ push_var(&mut explicit_vars, value)?;+ i += 2;+ continue;+ }+ _ => {}+ }+ if let Some(rest) = arg.strip_prefix("--var=") {+ push_var(&mut explicit_vars, rest)?;+ i += 1;+ continue;+ }+ if let Some(rest) = arg.strip_prefix("--")+ && let Some((key, value)) = rest.split_once('=')+ && !key.is_empty()+ {+ // Unknown `--KEY=VALUE` — shorthand for smart routing.+ shorthand_vars.push(format!("{key}={value}"));+ i += 1;+ continue;+ }+ if arg.starts_with("--") {+ // Unknown bare flag (`--foo` with no `=`) — refuse rather+ // than absorb as a filter name, since that would silently+ // accept typos like `--dryrun` intended as `--dry-run`.+ bail!(+ "unknown flag `{arg}` for `wt hook {first}` (use `--KEY=VALUE` for template \+ variables, `--` to forward tokens to {{{{ args }}}})"+ );+ }+ // Bare positional → filter name.+ name_filters.push(arg.to_string());+ i += 1;}- out.push(token.clone());++ Ok(Self {+ hook_type,+ yes,+ dry_run,+ foreground,+ name_filters,+ explicit_vars,+ shorthand_vars,+ forwarded_args,+ })}- out+}++/// Parse `KEY=VALUE` and push `(canonical_key, value)` onto `out`, mirroring+/// the old `parse_key_val` behavior (hyphen → underscore canonicalization).+fn push_var(out: &mut Vec<(String, String)>, raw: &str) -> anyhow::Result<()> {+ let (key, val) = raw+ .split_once('=')+ .with_context(|| format!("--var expected KEY=VALUE, got `{raw}`"))?;+ if key.is_empty() {+ bail!("--var key cannot be empty");+ }+ out.push((key.replace('-', "_"), val.to_string()));+ Ok(())}#[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()+ fn parse(args: &[&str]) -> anyhow::Result<HookOptions> {+ let os: Vec<OsString> = args.iter().map(OsString::from).collect();+ HookOptions::parse(&os)}#[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="]- );+ fn test_parse_minimal() {+ let opts = parse(&["pre-merge"]).unwrap();+ assert_eq!(opts.hook_type, HookType::PreMerge);+ assert!(!opts.yes);+ assert!(!opts.dry_run);+ assert_eq!(opts.foreground, None);+ assert!(opts.name_filters.is_empty());+ assert!(opts.explicit_vars.is_empty());+ assert!(opts.shorthand_vars.is_empty());+ assert!(opts.forwarded_args.is_empty());}#[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"]- );+ fn test_parse_flags() {+ let opts = parse(&["post-start", "--yes", "--dry-run", "--foreground"]).unwrap();+ assert_eq!(opts.hook_type, HookType::PostStart);+ assert!(opts.yes);+ assert!(opts.dry_run);+ assert_eq!(opts.foreground, Some(true));++ // `-y` alias for `--yes`.+ let opts = parse(&["pre-merge", "-y"]).unwrap();+ assert!(opts.yes);+ }- // --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_parse_name_filters() {+ let opts = parse(&["pre-merge", "test", "build"]).unwrap();+ assert_eq!(opts.name_filters, vec!["test", "build"]);+ assert!(opts.shorthand_vars.is_empty());++ // Source-prefix filters pass through as plain filter names.+ let opts = parse(&["pre-merge", "user:test", "project:"]).unwrap();+ assert_eq!(opts.name_filters, vec!["user:test", "project:"]);}#[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"]- );+ fn test_parse_shorthand() {+ let opts = parse(&["pre-merge", "--branch=feature/x"]).unwrap();+ assert_eq!(opts.shorthand_vars, vec!["branch=feature/x"]);+ // Value with `=` inside (URL, etc.) preserves everything after the+ // first `=` as the value.+ let opts = parse(&["pre-start", "--url=http://host?a=1"]).unwrap();+ assert_eq!(opts.shorthand_vars, vec!["url=http://host?a=1"]);+ // Empty value.+ let opts = parse(&["pre-start", "--branch="]).unwrap();+ assert_eq!(opts.shorthand_vars, vec!["branch="]);+ }- // `wt hook approvals add --all` passes through unchanged+ #[test]+ fn test_parse_explicit_var() {+ // Space form.+ let opts = parse(&["pre-merge", "--var", "branch=x"]).unwrap();assert_eq!(- rewrite(&["wt", "hook", "approvals", "add", "--all"]),- vec!["wt", "hook", "approvals", "add", "--all"]+ opts.explicit_vars,+ vec![("branch".to_string(), "x".to_string())]);+ assert!(opts.shorthand_vars.is_empty());- // `wt switch --foo=bar` is not a hook command, pass through+ // `=` form.+ let opts = parse(&["pre-merge", "--var=branch=x"]).unwrap();assert_eq!(- rewrite(&["wt", "switch", "--foo=bar"]),- vec!["wt", "switch", "--foo=bar"]+ opts.explicit_vars,+ vec![("branch".to_string(), "x".to_string())]);- // `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+ // Hyphen canonicalization to underscore.+ let opts = parse(&["pre-merge", "--var", "my-key=val"]).unwrap();assert_eq!(- rewrite(&["wt", "-C", "hook", "pre-start", "--branch=x"]),- vec!["wt", "-C", "hook", "pre-start", "--branch=x"]+ opts.explicit_vars,+ vec![("my_key".to_string(), "val".to_string())]);- // `wt --config hook pre-start` — same guard+ // Multiple `--var`.+ let opts = parse(&["pre-merge", "--var", "a=1", "--var", "b=2"]).unwrap();assert_eq!(- rewrite(&["wt", "--config", "hook", "pre-start", "--branch=x"]),- vec!["wt", "--config", "hook", "pre-start", "--branch=x"]+ opts.explicit_vars,+ vec![+ ("a".to_string(), "1".to_string()),+ ("b".to_string(), "2".to_string())+ ]);}#[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"]- );+ fn test_parse_literal_forward_escape() {+ // Tokens after `--` forward verbatim, even if they look like flags+ // or would have bound before `--`.+ let opts = parse(&[+ "pre-merge",+ "--branch=x",+ "--",+ "--fast",+ "--branch=y",+ "extra",+ ])+ .unwrap();+ assert_eq!(opts.shorthand_vars, vec!["branch=x"]);+ assert_eq!(opts.forwarded_args, vec!["--fast", "--branch=y", "extra"]);++ // Trailing `--` with nothing after — consumed silently.+ let opts = parse(&["pre-merge", "--"]).unwrap();+ assert!(opts.forwarded_args.is_empty());++ // `--` preserves filter names parsed before it.+ let opts = parse(&["pre-merge", "test", "--", "extra"]).unwrap();+ assert_eq!(opts.name_filters, vec!["test"]);+ assert_eq!(opts.forwarded_args, vec!["extra"]);}#[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+ fn test_parse_mixed() {+ // Every token type in one invocation.+ let opts = parse(&[+ "post-merge",+ "--yes",+ "test",+ "--branch=x",+ "--var",+ "override=1",+ "--dry-run",+ "--",+ "--fast",+ ])+ .unwrap();+ assert_eq!(opts.hook_type, HookType::PostMerge);+ assert!(opts.yes);+ assert!(opts.dry_run);+ assert_eq!(opts.name_filters, vec!["test"]);+ assert_eq!(opts.shorthand_vars, vec!["branch=x"]);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"]+ opts.explicit_vars,+ vec![("override".to_string(), "1".to_string())]);+ assert_eq!(opts.forwarded_args, vec!["--fast"]);}- /// 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."- );- }+ fn test_parse_hook_type_aliases() {+ // `post-create` is the deprecated alias for `pre-start`.+ let opts = parse(&["post-create"]).unwrap();+ assert_eq!(opts.hook_type, HookType::PreStart);}- /// 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). Hidden commands last.-/// Run configured hooks-#[derive(Subcommand)]-pub enum HookCommand {- /// Show configured hooks- ///- /// Lists user and project hooks. Project hooks show approval status (❓ = needs approval).- Show {- /// Hook type to show (default: all)- #[arg(value_parser = ["pre-switch", "post-switch", "pre-start", "post-start", "pre-commit", "post-commit", "pre-merge", "post-merge", "pre-remove", "post-remove"])]- hook_type: Option<String>,-- /// Show expanded commands with current variables- #[arg(long)]- expanded: bool,- },-- /// Run pre-switch hooks- ///- /// Blocking — waits for completion before continuing.- PreSwitch {- /// Filter by command name(s)- ///- /// Supports `user:name` or `project:name` to filter by source.- /// `user:` alone runs all user hooks; `project:` alone runs all project hooks.- #[arg(add = crate::completion::hook_command_name_completer())]- name: Vec<String>,-- /// Show what would run without executing- #[arg(long)]- dry_run: bool,-- /// 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)>,- },-- /// Run post-switch hooks- ///- /// Background by default. Use `--foreground` to run in foreground for debugging.- PostSwitch {- /// Filter by command name(s)- ///- /// Supports `user:name` or `project:name` to filter by source.- /// `user:` alone runs all user hooks; `project:` alone runs all project hooks.- #[arg(add = crate::completion::hook_command_name_completer())]- name: Vec<String>,-- /// Show what would run without executing- #[arg(long)]- dry_run: bool,-- /// Run in foreground (block until complete)- #[arg(long)]- foreground: bool,-- /// 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)>,- },-- /// Run pre-start hooks- ///- /// Blocking — waits for completion before continuing.- #[command(alias = "post-create")]- PreStart {- /// Filter by command name(s)- ///- /// Supports `user:name` or `project:name` to filter by source.- /// `user:` alone runs all user hooks; `project:` alone runs all project hooks.- #[arg(add = crate::completion::hook_command_name_completer())]- name: Vec<String>,-- /// Show what would run without executing- #[arg(long)]- dry_run: bool,-- /// 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)>,- },-- /// Run post-start hooks- ///- /// Background by default. Use `--foreground` to run in foreground for debugging.- PostStart {- /// Filter by command name(s)- ///- /// Supports `user:name` or `project:name` to filter by source.- /// `user:` alone runs all user hooks; `project:` alone runs all project hooks.- #[arg(add = crate::completion::hook_command_name_completer())]- name: Vec<String>,-- /// Show what would run without executing- #[arg(long)]- dry_run: bool,-- /// Run in foreground (block until complete)- #[arg(long)]- foreground: bool,-- /// 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)>,- },-- /// Run pre-commit hooks- PreCommit {- /// Filter by command name(s)- ///- /// Supports `user:name` or `project:name` to filter by source.- /// `user:` alone runs all user hooks; `project:` alone runs all project hooks.- #[arg(add = crate::completion::hook_command_name_completer())]- name: Vec<String>,-- /// Show what would run without executing- #[arg(long)]- dry_run: bool,-- /// 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)>,- },-- /// Run post-commit hooks- ///- /// Background by default. Use `--foreground` to run in foreground for debugging.- PostCommit {- /// Filter by command name(s)- ///- /// Supports `user:name` or `project:name` to filter by source.- /// `user:` alone runs all user hooks; `project:` alone runs all project hooks.- #[arg(add = crate::completion::hook_command_name_completer())]- name: Vec<String>,-- /// Show what would run without executing- #[arg(long)]- dry_run: bool,-- /// Run in foreground (block until complete)- #[arg(long)]- foreground: bool,-- /// 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)>,- },-- /// Run pre-merge hooks- PreMerge {- /// Filter by command name(s)- ///- /// Supports `user:name` or `project:name` to filter by source.- /// `user:` alone runs all user hooks; `project:` alone runs all project hooks.- #[arg(add = crate::completion::hook_command_name_completer())]- name: Vec<String>,-- /// Show what would run without executing- #[arg(long)]- dry_run: bool,-- /// 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)>,- },-- /// Run post-merge hooks- ///- /// Background by default. Use `--foreground` to run in foreground for debugging.- PostMerge {- /// Filter by command name(s)- ///- /// Supports `user:name` or `project:name` to filter by source.- /// `user:` alone runs all user hooks; `project:` alone runs all project hooks.- #[arg(add = crate::completion::hook_command_name_completer())]- name: Vec<String>,-- /// Show what would run without executing- #[arg(long)]- dry_run: bool,-- /// Run in foreground (block until complete)- #[arg(long)]- foreground: bool,-- /// 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)>,- },-- /// Run pre-remove hooks- PreRemove {- /// Filter by command name(s)- ///- /// Supports `user:name` or `project:name` to filter by source.- /// `user:` alone runs all user hooks; `project:` alone runs all project hooks.- #[arg(add = crate::completion::hook_command_name_completer())]- name: Vec<String>,-- /// Show what would run without executing- #[arg(long)]- dry_run: bool,-- /// 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)>,- },-- /// Run post-remove hooks- ///- /// Background by default. Use `--foreground` to run in foreground for debugging.- PostRemove {- /// Filter by command name(s)- ///- /// Supports `user:name` or `project:name` to filter by source.- /// `user:` alone runs all user hooks; `project:` alone runs all project hooks.- #[arg(add = crate::completion::hook_command_name_completer())]- name: Vec<String>,-- /// Show what would run without executing- #[arg(long)]- dry_run: bool,+ fn test_parse_errors() {+ // Missing hook type.+ assert!(HookOptions::parse(&[]).is_err());++ // Unknown hook type; typo that matches a canonical name produces a suggestion.+ let err = parse(&["pre-mrege"]).unwrap_err();+ let msg = err.to_string();+ assert!(+ msg.contains("pre-merge"),+ "expected did-you-mean suggestion, got: {msg}"+ );- /// Run in foreground (block until complete)- #[arg(long)]- foreground: bool,+ // Completely unknown hook type lists all valid names.+ let err = parse(&["zzz"]).unwrap_err();+ assert!(err.to_string().contains("expected one of"));- /// 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)>,- },+ // `--var` missing value.+ let err = parse(&["pre-merge", "--var"]).unwrap_err();+ assert!(err.to_string().contains("--var"));- /// Internal: run a serialized pipeline from stdin- #[command(hide = true, name = "run-pipeline")]- RunPipeline,+ // `--var` with empty key.+ let err = parse(&["pre-merge", "--var", "=value"]).unwrap_err();+ assert!(err.to_string().contains("empty"));- /// Deprecated: use `wt config approvals` instead- #[command(hide = true)]- Approvals {- #[command(subcommand)]- action: ApprovalsCommand,- },+ // Unknown bare flag rejected (no silent filter-name fallback).+ let err = parse(&["pre-merge", "--dryrun"]).unwrap_err();+ assert!(err.to_string().contains("unknown flag"));+ }}diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 88221c4be..17ed3b324 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -9,7 +9,7 @@ pub(crate) use config::{ConfigShellCommand, DefaultBranchAction, HintsAction, LogsAction, MarkerAction,PreviousBranchAction, StateCommand, VarsAction,};-pub(crate) use hook::{HookCommand, rewrite_var_shorthand};+pub(crate) use hook::{HOOK_TYPE_NAMES, HookCommand, HookOptions};pub(crate) use list::ListSubcommand;pub(crate) use step::StepCommand;@@ -20,19 +20,6 @@ use std::sync::OnceLock;use crate::commands::Shell;-/// Parse `KEY=VALUE` string into a tuple for `--var` on hook commands.-///-/// 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 hyphen→underscore canonicalization.@@ -148,6 +135,13 @@ pub(crate) fn suggest_nested_subcommand(cmd: &Command, unknown: &str) -> Option<return Some(format!("wt {parent} {unknown}"));}}+ // Hook types aren't clap subcommands of `hook` (they're caught by+ // `external_subcommand`), so the structural search above misses them.+ // Check the canonical name list directly so `wt pre-merge` → `wt hook+ // pre-merge` still suggests correctly.+ if HOOK_TYPE_NAMES.contains(&unknown) {+ return Some(format!("wt hook {unknown}"));+ }None}@@ -1276,6 +1270,7 @@ Hooks can use template variables that expand at runtime:| exec | `{{ cwd }}` | Directory where the hook command runs || | `{{ hook_type }}` | Hook type being run (e.g. `pre-start`, `pre-merge`) || | `{{ hook_name }}` | Hook command name (if named) |+| | `{{ args }}` | Tokens forwarded from the CLI — see [Running Hooks Manually](#running-hooks-manually) || user | `{{ vars.<key> }}` | Per-branch variables from [`wt config state vars`](@/config.md#wt-config-state-vars) |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:@@ -1376,11 +1371,18 @@ $ 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 --yes # Skip approval prompts (for CI)$ wt hook pre-start --branch=feature/test # Override a template variable+$ wt hook pre-merge -- --extra args # Forward tokens into {{ args }}```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.-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`).+## Passing values++`--KEY=VALUE` binds `KEY` whenever `{{ KEY }}` appears in any command of the hook — the same smart-routing rule `wt <alias>` uses. Built-in variables can be overridden: `--branch=foo` sets `{{ branch }}` inside hook templates (the worktree's actual branch doesn't move). Hyphens in keys become underscores: `--my-var=x` sets `{{ my_var }}`.++Any `--KEY=VALUE` whose key isn't referenced by a hook template forwards into `{{ args }}` as a literal `--KEY=VALUE` token. Tokens after `--` also forward into `{{ args }}` verbatim. `{{ args }}` renders as a space-joined, shell-escaped string; index with `{{ args[0] }}`, loop with `{% for a in args %}…{% endfor %}`, count with `{{ args | length }}`.++The long form `--var KEY=VALUE` is deprecated but still supported. It force-binds regardless of whether any hook template references `KEY` — useful when a template only references the key conditionally (e.g. `{% if override %}…{% endif %}`).# Pipeline Ordering [experimental]diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex 77a67cbd0..beda7a883 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -583,6 +583,14 @@ fn expand_commands(// hook_type is always available as a template variable and in JSON contextbase_context.insert("hook_type".into(), hook_type.to_string());+ // `{{ args }}` is always available in hook scope. Default to an empty+ // JSON sequence (rendered via ShellArgs rehydration) so templates can+ // use `{{ args }}` unconditionally. Manual `wt hook <type>` overrides+ // via extra_vars earlier in the chain; internal invocations (merge,+ // switch, etc.) leave the default in place.+ base_context+ .entry(worktrunk::config::ALIAS_ARGS_KEY.to_string())+ .or_insert_with(|| "[]".to_string());let mut result = Vec::new();diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 2c8d5b560..3aff91af9 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -11,7 +11,9 @@ use anyhow::Context;use color_print::cformat;use strum::IntoEnumIterator;use worktrunk::HookType;-use worktrunk::config::{Approvals, CommandConfig, ProjectConfig, UserConfig};+use worktrunk::config::{+ ALIAS_ARGS_KEY, Approvals, CommandConfig, ProjectConfig, UserConfig, referenced_vars_for_config,+};use worktrunk::git::Repository;use worktrunk::path::format_path_for_display;use worktrunk::styling::{@@ -25,7 +27,6 @@ use super::command_executor::build_hook_context;use super::command_executor::CommandContext;use super::command_executor::{FailureStrategy, command_summary_name};use super::context::CommandEnv;-use super::hook_filter::{HookSource, ParsedFilter};use super::hooks::{HookCommandSpec, check_name_filter_matched, count_sourced_commands, prepare_sourced_steps,run_hook_with_filter, spawn_background_hooks, spawn_hook_pipeline,@@ -152,84 +153,53 @@ 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.+/// Parse a raw `KEY=VALUE` shorthand token into a canonicalized+/// `(canonical_key, original_key, value)` triple.///-/// 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(+/// Canonicalization replaces `-` with `_` in the key to match the template+/// naming convention (minijinja parses `{{ my-var }}` as subtraction), the+/// same rule `parse_key_val` applies to `--var`. The original key is preserved+/// for reconstructing `--KEY=VALUE` when forwarding to `{{ args }}`.+fn parse_shorthand_token(raw: &str) -> anyhow::Result<(String, String, String)> {+ let (key, value) = raw+ .split_once('=')+ .ok_or_else(|| anyhow::anyhow!("invalid shorthand (missing `=`): {raw}"))?;+ if key.is_empty() {+ anyhow::bail!("invalid shorthand (empty key): {raw}");+ }+ Ok((key.replace('-', "_"), key.to_string(), value.to_string()))+}++/// Union of top-level template variable names referenced across every command+/// in both configs for this hook type. Matches alias pipeline semantics:+/// referenced in any step is a binding candidate for the whole invocation.+fn referenced_vars_union(user_config: Option<&CommandConfig>,project_config: Option<&CommandConfig>,- name_filters: &[String],- custom_vars: &[(String, String)],-) {- if custom_vars.is_empty() {- return;+) -> anyhow::Result<std::collections::BTreeSet<String>> {+ let mut out = std::collections::BTreeSet::new();+ if let Some(cfg) = user_config {+ out.extend(referenced_vars_for_config(cfg)?);}-- 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));- }- }- }+ if let Some(cfg) = project_config {+ out.extend(referenced_vars_for_config(cfg)?);}+ Ok(out)+}- // TODO: show the original (pre-canonicalized) key in the warning so- // `--my-env=staging` produces "my-env" not "my_env". Requires threading- // the raw input through parse_key_val.- for (key, _) in custom_vars {- if !referenced.contains(key) {- eprintln!(- "{}",- warning_message(cformat!(- "--var <bold>{key}</> is not referenced by any hook template — typo?"- ))- );- }- }+/// CLI-origin arguments to a manual `wt hook <type>` invocation. Bundled so+/// the call sites in `main.rs` don't balloon past clippy's+/// `too_many_arguments` threshold as the shorthand/forwarding surface grows.+pub struct HookCliArgs<'a> {+ /// Positional name filters: `wt hook pre-merge test build` → `["test", "build"]`.+ pub name_filters: &'a [String],+ /// Explicit `--var KEY=VALUE` bindings (deprecated force-bind).+ pub explicit_vars: &'a [(String, String)],+ /// Raw `KEY=VALUE` tokens from the `--KEY=VALUE` shorthand. Smart-routed:+ /// bind if any hook template references KEY, else forward to `{{ args }}`.+ pub shorthand_vars: &'a [String],+ /// Tokens after `--` that forward to `{{ args }}` verbatim.+ pub forwarded_args: &'a [String],}/// Handle `wt hook` command@@ -239,8 +209,13 @@ fn warn_unreferenced_custom_vars(////// Works in detached HEAD state - `{{ branch }}` template variable will be "HEAD".///-/// 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.+/// Template variables come from three sources in [`HookCliArgs`], routed per+/// alias semantics:+/// - `shorthand_vars` (`--KEY=VALUE`): binds `{{ KEY }}` if any hook template+/// references it; otherwise forwards `--KEY=VALUE` into `{{ args }}`.+/// - `forwarded_args` (tokens after `--`): forwards into `{{ args }}` verbatim.+/// - `explicit_vars` (`--var KEY=VALUE`): deprecated force-bind. Always binds,+/// regardless of whether any template references the key.////// The `foreground` parameter controls execution mode for hooks that normally run/// in background (post-start, post-switch):@@ -252,9 +227,14 @@ pub fn run_hook(yes: bool,foreground: Option<bool>,dry_run: bool,- name_filters: &[String],- custom_vars: &[(String, String)],+ cli: HookCliArgs<'_>,) -> anyhow::Result<()> {+ let HookCliArgs {+ name_filters,+ explicit_vars,+ shorthand_vars,+ forwarded_args,+ } = cli;// Derive context from current environment (branch-optional for CI compatibility)let env = CommandEnv::for_action_branchless()?;let repo = &env.repo;@@ -274,12 +254,6 @@ pub fn run_hook(}}- // 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();-// Get effective user hooks (global + per-project merged)let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());let (user_config, proj_config) = (@@ -297,19 +271,59 @@ 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);+ // Smart-route shorthand: bind when the template references the key,+ // forward otherwise. Mirrors `AliasOptions::parse` for the alias path.+ let referenced = referenced_vars_union(user_config, proj_config)?;+ let mut bindings: Vec<(String, String)> = Vec::new();+ let mut args: Vec<String> = Vec::new();+ for raw in shorthand_vars {+ let (canon_key, orig_key, value) = parse_shorthand_token(raw)?;+ if referenced.contains(&canon_key) {+ bindings.push((canon_key, value));+ } else {+ args.push(format!("--{orig_key}={value}"));+ }+ }+ args.extend(forwarded_args.iter().cloned());++ // Explicit `--var KEY=VALUE` is deprecated — prefer `--KEY=VALUE`. It+ // still force-binds (useful when a template references the key only+ // conditionally, e.g. `{% if override %}`), so keep the binding.+ if !explicit_vars.is_empty() {+ eprintln!(+ "{}",+ warning_message(+ "--var is deprecated; use --KEY=VALUE shorthand (binds automatically when any hook template references KEY)",+ )+ );+ bindings.extend(explicit_vars.iter().cloned());+ }++ let custom_vars_refs: Vec<(&str, &str)> = bindings+ .iter()+ .map(|(k, v)| (k.as_str(), v.as_str()))+ .collect();// 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());- let extra_vars = build_manual_hook_extra_vars(+ // Splice `args` into the template context as a JSON-encoded sequence.+ // `expand_template` rehydrates it as `ShellArgs` so bare `{{ args }}`+ // renders space-joined with per-element shell escaping. Mirrors+ // `run_alias` at `src/commands/alias.rs`.+ let args_json =+ serde_json::to_string(&args).expect("Vec<String> serialization should never fail");+ let mut extra_vars = build_manual_hook_extra_vars(&ctx,hook_type,&custom_vars_refs,default_branch.as_deref(),&worktree_path_str,);+ // Forward positional CLI args as `{{ args }}` (empty sequence when+ // nothing was forwarded). `expand_template` rehydrates this JSON into a+ // `ShellArgs` sequence that renders space-joined, per-element escaped.+ extra_vars.push((ALIAS_ARGS_KEY, &args_json));if dry_run {let steps = prepare_sourced_steps(@@ -618,6 +632,10 @@ fn expand_command_template(if let Some(name) = hook_name {template_ctx.insert("hook_name".into(), name.into());}+ // Preview has no CLI args to forward. Inject an empty JSON sequence+ // so templates that reference `{{ args }}` render cleanly rather than+ // erroring with "undefined value" at the preview site.+ template_ctx.insert(ALIAS_ARGS_KEY.into(), "[]".into());let vars: HashMap<&str, &str> = template_ctx.iter().map(|(k, v)| (k.as_str(), v.as_str()))diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex c5269bf13..ee4bf43d3 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -45,7 +45,7 @@ pub(crate) use custom::handle_custom_command;pub(crate) use eval::step_eval;pub(crate) use for_each::step_for_each;pub(crate) use handle_switch::{SwitchOptions, handle_switch};-pub(crate) use hook_commands::{handle_hook_show, run_hook};+pub(crate) use hook_commands::{HookCliArgs, handle_hook_show, run_hook};pub(crate) use init::{handle_completions, handle_init};pub(crate) use list::handle_list;pub(crate) use merge::{MergeOptions, handle_merge};diff --git a/src/completion.rs b/src/completion.rsindex 9b639add6..3a0a5a3b1 100644--- a/src/completion.rs+++ b/src/completion.rs@@ -425,10 +425,77 @@ thread_local! {fn completion_command() -> Command {let cmd = cli::build_command();let cmd = inject_alias_subcommands(cmd);+ let cmd = inject_hook_subcommands(cmd);let cmd = inject_custom_subcommands(cmd);hide_non_positional_options_for_completion(cmd)}+/// Inject hook type names as subcommands of `hook` so both completion and+/// `wt hook --help` list them. Clap doesn't dispatch these at runtime — the+/// real parser uses the `external_subcommand` `Run(Vec<OsString>)` variant —+/// but the help renderer and completion engine both walk the `Command` tree+/// to produce their output, so injecting stubs into an augmented clone shows+/// the types without affecting argument dispatch.+///+/// Mirrors `inject_alias_subcommands` which does the equivalent for+/// top-level alias names.+pub(crate) fn inject_hook_subcommands(cmd: Command) -> Command {+ cmd.mut_subcommand("hook", |mut hook| {+ for &name in cli::HOOK_TYPE_NAMES {+ // Skip if a real subcommand already uses this name (won't happen+ // today, but keeps the injection idempotent).+ if hook.get_subcommands().any(|s| s.get_name() == name) {+ continue;+ }+ hook = hook.subcommand(build_hook_completion_command(name));+ }+ hook+ })+}++/// Build a completion stub `clap::Command` for a hook type. Same shape as+/// `build_alias_completion_command` — declares the known flags (so they show+/// up in `wt hook pre-merge --<Tab>` completions) and wires the name completer+/// for the first positional (hook command name filter).+fn build_hook_completion_command(name: &'static str) -> Command {+ let about: &'static str = Box::leak(format!("Run {name} hooks").into_boxed_str());+ Command::new(name)+ .about(about)+ .arg(+ clap::Arg::new("dry-run")+ .long("dry-run")+ .action(clap::ArgAction::SetTrue)+ .help("Show what would run without executing"),+ )+ .arg(+ clap::Arg::new("foreground")+ .long("foreground")+ .action(clap::ArgAction::SetTrue)+ .help("Run in foreground (block until complete)"),+ )+ .arg(+ clap::Arg::new("yes")+ .short('y')+ .long("yes")+ .action(clap::ArgAction::SetTrue)+ .help("Skip approval prompts for project hooks"),+ )+ .arg(+ clap::Arg::new("var")+ .long("var")+ .value_name("KEY=VALUE")+ .num_args(1)+ .action(clap::ArgAction::Append)+ .help("Set template variable (deprecated — prefer --KEY=VALUE)"),+ )+ .arg(+ clap::Arg::new("name")+ .num_args(0..)+ .add(hook_command_name_completer())+ .help("Filter by command name(s)"),+ )+}+/// Inject configured aliases as subcommands at both the top level and under/// `step` so they appear in completions for `wt <Tab>` and `wt step <Tab>`.///diff --git a/src/config/expansion.rs b/src/config/expansion.rsindex 574262d6c..ef8ed81a6 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -160,6 +160,7 @@ pub fn vars_available_in(scope: ValidationScope) -> Vec<&'static str> {ValidationScope::Hook(hook_type) => {vars.extend(HOOK_INFRASTRUCTURE_VARS);vars.extend(hook_extras(hook_type));+ vars.push(ALIAS_ARGS_KEY);}ValidationScope::SwitchExecute => {vars.extend(["base", "base_worktree_path"]);@@ -579,10 +580,10 @@ pub fn validate_template("vars".to_string(),minijinja::Value::from_serialize(std::collections::BTreeMap::<String, String>::new()),);- // In alias scope, inject `args` as an empty sequence so `{{ args }}`,- // `{{ args[0] | default(...) }}`, `{{ args | length }}`, and- // `{% for a in args %}…{% endfor %}` all validate.- if matches!(scope, ValidationScope::Alias) {+ // In alias and hook scopes, inject `args` as an empty sequence so+ // `{{ args }}`, `{{ args[0] | default(...) }}`, `{{ args | length }}`,+ // and `{% for a in args %}…{% endfor %}` all validate.+ if matches!(scope, ValidationScope::Alias | ValidationScope::Hook(_)) {context.insert(ALIAS_ARGS_KEY.to_string(),Value::from_object(ShellArgs::new(Vec::new())),@@ -1682,7 +1683,8 @@ mod tests {// Deprecated vars still valid in every scopeassert!(validate_template("{{ main_worktree }}", hook, &test.repo, "test").is_ok());- // `args` validates only in Alias scope.+ // `args` validates in both Hook and Alias scopes.+ assert!(validate_template("echo {{ args }}", hook, &test.repo, "test").is_ok());let alias = ValidationScope::Alias;assert!(validate_template("wt switch {{ args }}", alias, &test.repo, "test").is_ok());assert!(validate_template("{{ args | length }}", alias, &test.repo, "test").is_ok());@@ -1701,20 +1703,6 @@ mod tests {fn test_validate_template_scope_rejects_out_of_scope_vars() {let test = test_repo();- // `args` is alias-only — referencing it in a hook fails validation.- let err = validate_template(- "{{ args }}",- ValidationScope::Hook(HookType::PreStart),- &test.repo,- "test",- )- .unwrap_err();- assert!(- err.message.contains("undefined value"),- "got: {}",- err.message- );-// `base` is unavailable in pre-merge — catch the typo at validation time.let err = validate_template("{{ base }}",@@ -1780,6 +1768,17 @@ mod tests {err.message);+ // `args` is available in hook scope (forwarded via smart routing).+ assert!(+ validate_template(+ "{{ args }}",+ ValidationScope::Hook(HookType::PreStart),+ &test.repo,+ "test",+ )+ .is_ok()+ );+// `args` is not available in SwitchExecute.let err = validate_template("{{ args }}",diff --git a/src/help.rs b/src/help.rsindex 4f2be6ff0..4545f6ec8 100644--- a/src/help.rs+++ b/src/help.rs@@ -97,6 +97,7 @@ pub fn maybe_handle_help_with_pager(alias_help_context: Option<crate::commands::// Check for --help-md flag (output raw markdown without ANSI rendering)if args.iter().any(|a| a == "--help-md") {let mut cmd = cli::build_command();+ cmd = crate::completion::inject_hook_subcommands(cmd);cmd = cmd.color(ColorChoice::Never); // No ANSI codes for raw markdown// Replace --help-md with --help for clap@@ -132,6 +133,7 @@ pub fn maybe_handle_help_with_pager(alias_help_context: Option<crate::commands::}let mut cmd = cli::build_command();+ cmd = crate::completion::inject_hook_subcommands(cmd);cmd = cmd.color(clap::ColorChoice::Always); // Force clap to emit ANSI codesif let Err(err) = cmd.try_get_matches_from_mut(&args) {@@ -206,6 +208,7 @@ fn help_reference_inner(command_path: &[&str], width: Option<usize>, color: Coloargs.push("--help".to_string());let mut cmd = cli::build_command();+ cmd = crate::completion::inject_hook_subcommands(cmd);cmd = cmd.color(color);if let Some(w) = width {cmd = cmd.term_width(w);@@ -310,6 +313,7 @@ fn extract_about_and_subtitle(cmd: &clap::Command) -> (Option<String>, Option<St/// by the docs sync test to auto-populate the `description` field in frontmatter.fn handle_help_description(args: &[String]) {let mut cmd = cli::build_command();+ cmd = crate::completion::inject_hook_subcommands(cmd);cmd = cmd.color(ColorChoice::Never);let subcommand = args@@ -362,6 +366,7 @@ fn handle_help_description(args: &[String]) {/// This is used to generate docs/content/merge.md etc from the source.fn handle_help_page(args: &[String], plain: bool) {let mut cmd = cli::build_command();+ cmd = crate::completion::inject_hook_subcommands(cmd);cmd = cmd.color(ColorChoice::Never);// Find the subcommand name (the arg before --help-page, or after wt)diff --git a/src/main.rs b/src/main.rsindex f6b2f53ed..cc663f05f 100644--- a/src/main.rs+++ b/src/main.rs@@ -47,17 +47,18 @@ use commands::handle_picker;use commands::repository_ext::RepositoryCliExt;use commands::worktree::{handle_no_ff_merge, handle_push};use commands::{- MergeOptions, OperationMode, RebaseResult, RemoveTarget, SquashResult, SwitchOptions,- add_approvals, clear_approvals, handle_alias_dry_run, handle_alias_show, handle_claude_install,- handle_claude_install_statusline, handle_claude_uninstall, handle_completions,- handle_config_create, handle_config_show, handle_config_update, handle_configure_shell,- handle_custom_command, handle_hints_clear, handle_hints_get, handle_hook_show, handle_init,- handle_list, handle_logs_list, handle_merge, handle_opencode_install,- handle_opencode_uninstall, handle_promote, handle_rebase, handle_show_theme, handle_squash,- handle_state_clear, handle_state_clear_all, handle_state_get, handle_state_set,- handle_state_show, handle_switch, handle_unconfigure_shell, handle_vars_clear, handle_vars_get,- handle_vars_list, handle_vars_set, resolve_worktree_arg, run_hook, step_commit,- step_copy_ignored, step_diff, step_eval, step_for_each, step_prune, step_relocate,+ HookCliArgs, MergeOptions, OperationMode, RebaseResult, RemoveTarget, SquashResult,+ SwitchOptions, add_approvals, clear_approvals, handle_alias_dry_run, handle_alias_show,+ handle_claude_install, handle_claude_install_statusline, handle_claude_uninstall,+ handle_completions, handle_config_create, handle_config_show, handle_config_update,+ handle_configure_shell, handle_custom_command, handle_hints_clear, handle_hints_get,+ handle_hook_show, handle_init, handle_list, handle_logs_list, handle_merge,+ handle_opencode_install, handle_opencode_uninstall, handle_promote, handle_rebase,+ handle_show_theme, handle_squash, handle_state_clear, handle_state_clear_all, handle_state_get,+ handle_state_set, handle_state_show, handle_switch, handle_unconfigure_shell,+ handle_vars_clear, handle_vars_get, handle_vars_list, handle_vars_set, resolve_worktree_arg,+ run_hook, step_commit, step_copy_ignored, step_diff, step_eval, step_for_each, step_prune,+ step_relocate,};use output::handle_remove_output;use worktrunk::git::BranchDeletionMode;@@ -65,9 +66,9 @@ use worktrunk::git::BranchDeletionMode;use cli::{ApprovalsCommand, CiStatusAction, Cli, Commands, ConfigAliasCommand, ConfigCommand,ConfigPluginsClaudeCommand, ConfigPluginsCommand, ConfigPluginsOpencodeCommand,- ConfigShellCommand, DefaultBranchAction, HintsAction, HookCommand, ListArgs, ListSubcommand,- LogsAction, MarkerAction, MergeArgs, PreviousBranchAction, RemoveArgs, StateCommand,- StepCommand, SwitchArgs, SwitchFormat, VarsAction,+ ConfigShellCommand, DefaultBranchAction, HintsAction, HookCommand, HookOptions, ListArgs,+ ListSubcommand, LogsAction, MarkerAction, MergeArgs, PreviousBranchAction, RemoveArgs,+ StateCommand, StepCommand, SwitchArgs, SwitchFormat, VarsAction,};use worktrunk::HookType;@@ -134,27 +135,6 @@ fn flag_pair(positive: bool, negative: bool) -> Option<bool> {}}-fn run_non_toggle_hook(- hook_type: HookType,- yes: bool,- dry_run: bool,- names: &[String],- vars: &[(String, String)],-) -> anyhow::Result<()> {- run_hook(hook_type, yes, None, dry_run, names, vars)-}--fn run_toggleable_hook(- hook_type: HookType,- yes: bool,- dry_run: bool,- foreground: bool,- names: &[String],- vars: &[(String, String)],-) -> anyhow::Result<()> {- run_hook(hook_type, yes, Some(foreground), dry_run, names, vars)-}-fn warn_select_deprecated() {eprintln!("{}",@@ -182,68 +162,6 @@ fn handle_hook_command(action: HookCommand, yes: bool) -> anyhow::Result<()> {hook_type,expanded,} => handle_hook_show(hook_type.as_deref(), expanded),- HookCommand::PreSwitch {- name,- dry_run,- vars,- } => run_non_toggle_hook(HookType::PreSwitch, yes, dry_run, &name, &vars),- HookCommand::PostSwitch {- name,- dry_run,- foreground,- vars,- } => run_toggleable_hook(HookType::PostSwitch, yes, dry_run, foreground, &name, &vars),- HookCommand::PreStart {- name,- dry_run,- vars,- } => run_non_toggle_hook(HookType::PreStart, yes, dry_run, &name, &vars),- HookCommand::PostStart {- name,- dry_run,- foreground,- vars,- } => run_toggleable_hook(HookType::PostStart, yes, dry_run, foreground, &name, &vars),- HookCommand::PreCommit {- name,- dry_run,- vars,- } => run_non_toggle_hook(HookType::PreCommit, yes, dry_run, &name, &vars),- HookCommand::PostCommit {- name,- dry_run,- foreground,- vars,- } => run_toggleable_hook(HookType::PostCommit, yes, dry_run, foreground, &name, &vars),- HookCommand::PreMerge {- name,- dry_run,- vars,- } => run_non_toggle_hook(HookType::PreMerge, yes, dry_run, &name, &vars),- HookCommand::PostMerge {- name,- dry_run,- foreground,- vars,- } => run_toggleable_hook(HookType::PostMerge, yes, dry_run, foreground, &name, &vars),- HookCommand::PreRemove {- name,- dry_run,- vars,- } => run_non_toggle_hook(HookType::PreRemove, yes, dry_run, &name, &vars),- HookCommand::PostRemove {- name,- dry_run,- foreground,- vars,- } => run_hook(- HookType::PostRemove,- yes,- Some(foreground),- dry_run,- &name,- &vars,- ),HookCommand::RunPipeline => commands::run_pipeline(),HookCommand::Approvals { action } => {eprintln!(@@ -255,6 +173,25 @@ fn handle_hook_command(action: HookCommand, yes: bool) -> anyhow::Result<()> {ApprovalsCommand::Clear { global } => clear_approvals(global),}}+ HookCommand::Run(args) => {+ // `--help` / `-h` is handled upstream in `maybe_handle_help_with_pager`,+ // which parses against a clap tree augmented with hook-type+ // subcommand stubs and renders their help directly. Execution flow+ // only reaches here for non-help invocations.+ let opts = HookOptions::parse(&args)?;+ run_hook(+ opts.hook_type,+ yes || opts.yes,+ opts.foreground,+ opts.dry_run,+ HookCliArgs {+ name_filters: &opts.name_filters,+ explicit_vars: &opts.explicit_vars,+ shorthand_vars: &opts.shorthand_vars,+ forwarded_args: &opts.forwarded_args,+ },+ )+ }}}@@ -975,10 +912,11 @@ 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 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);- });+ let matches = cmd+ .try_get_matches_from(std::env::args_os())+ .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 2aa3b48f2..39283bac0 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -2003,7 +2003,7 @@ fn test_var_flag_invalid_format_fails() {let stderr = String::from_utf8_lossy(&output.stderr);assert!(- stderr.contains("invalid KEY=VALUE") || stderr.contains("no `=` found"),+ stderr.contains("expected KEY=VALUE"),"Error should mention invalid format, got: {stderr}");}@@ -2164,73 +2164,97 @@ test = "echo '{{ my_env }}' > custom_output.txt"}#[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.+fn test_shorthand_unreferenced_forwards_to_args(repo: TestRepo) {+ // `--KEY=VALUE` shorthand for an unreferenced KEY is smart-routed to+ // `{{ args }}` — the hook template captures the flag verbatim.repo.write_test_config(r#"[post-create]-test = "echo '{{ branch }}' > unref_output.txt"+test = "echo '{{ args }}' > args_output.txt""#,);let output = repo.wt_command()- .args(["hook", "post-create", "--yes", "--unused_var=value"])+ .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: {}",+ "Hook should succeed, stderr: {}",String::from_utf8_lossy(&output.stderr));- let stderr = String::from_utf8_lossy(&output.stderr);+ let contents = fs::read_to_string(repo.root_path().join("args_output.txt")).unwrap();assert!(- stderr.contains("unused_var") && stderr.contains("not referenced"),- "Expected unreferenced-var warning, got: {stderr}"+ contents.contains("--unused-var=value"),+ "Unreferenced shorthand should be forwarded to {{{{ args }}}}, got: {contents}");}#[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.+fn test_shorthand_referenced_binds_not_args(repo: TestRepo) {+ // When KEY is referenced by any hook template, `--KEY=VALUE` binds+ // `{{ KEY }}` and is NOT forwarded to `{{ args }}`.repo.write_test_config(r#"[post-create]-alpha = "echo '{{ branch }}' > alpha.txt"-beta = "echo '{{ my_env }}' > beta.txt"+test = "echo '{{ my_env }}:{{ args }}' > combined_output.txt""#,);let output = repo.wt_command()- .args(["hook", "post-create", "--yes", "alpha", "--my-env=staging"])+ .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);+ let contents = fs::read_to_string(repo.root_path().join("combined_output.txt")).unwrap();+ assert_eq!(contents.trim(), "staging:");+}++#[rstest]+fn test_post_double_dash_forwards_to_args(repo: TestRepo) {+ // Tokens after `--` forward verbatim into `{{ args }}`.+ repo.write_test_config(+ r#"[post-create]+test = "echo '{{ args }}' > dashdash_output.txt"+"#,+ );++ let output = repo+ .wt_command()+ .args(["hook", "post-create", "--yes", "--", "--fast", "extra"])+ .output()+ .expect("Failed to run wt hook");+assert!(- stderr.contains("my_env") && stderr.contains("not referenced"),- "Expected warning for --my-env when only 'alpha' runs, got: {stderr}"+ output.status.success(),+ "Hook should succeed, stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ let contents = fs::read_to_string(repo.root_path().join("dashdash_output.txt")).unwrap();+ assert!(+ contents.contains("--fast") && contents.contains("extra"),+ "Post-`--` tokens should forward verbatim to {{{{ args }}}}, got: {contents}");}#[rstest]-fn test_var_referenced_no_warning(repo: TestRepo) {- // A --var that IS referenced by a template produces no warning.+fn test_var_deprecation_warning(repo: TestRepo) {+ // Explicit `--var` still force-binds but emits a deprecation warning+ // pointing at `--KEY=VALUE` shorthand.repo.write_test_config(r#"[post-create]-test = "echo '{{ my_env }}' > ref_output.txt"+test = "echo '{{ my_env }}' > deprecated_output.txt""#,);let output = repo.wt_command()- .args(["hook", "post-create", "--yes", "--my-env=staging"])+ .args(["hook", "post-create", "--yes", "--var", "my_env=staging"]).output().expect("Failed to run wt hook");@@ -2238,8 +2262,80 @@ test = "echo '{{ my_env }}' > ref_output.txt"let stderr = String::from_utf8_lossy(&output.stderr);assert!(- !stderr.contains("not referenced"),- "Expected no warning, got: {stderr}"+ stderr.contains("--var is deprecated"),+ "Expected --var deprecation warning, got: {stderr}"+ );++ let contents = fs::read_to_string(repo.root_path().join("deprecated_output.txt")).unwrap();+ assert_eq!(contents.trim(), "staging");+}++#[rstest]+fn test_args_indexing_and_length_in_hook_template(repo: TestRepo) {+ // `{{ args }}` is a ShellArgs sequence — indexing, length, and iteration+ // all work the same as in alias templates.+ repo.write_test_config(+ r#"[post-create]+test = "echo '{{ args[0] | default(__WT_QUOT__none__WT_QUOT__) }}:{{ args | length }}' > args_seq.txt"+"#+ .replace("__WT_QUOT__", "'")+ .as_str(),+ );++ let output = repo+ .wt_command()+ .args(["hook", "post-create", "--yes", "--", "first", "second"])+ .output()+ .expect("Failed to run wt hook");++ assert!(output.status.success());++ let contents = fs::read_to_string(repo.root_path().join("args_seq.txt")).unwrap();+ assert_eq!(contents.trim(), "first:2");+}++#[rstest]+fn test_mixed_var_shorthand_and_forwarded_args(repo: TestRepo) {+ // Explicit `--var` binds, referenced shorthand binds, unreferenced shorthand+ // + post-`--` tokens forward — all coexist in one invocation without+ // cross-contamination.+ repo.write_test_config(+ r#"[post-create]+test = "echo '{{ my_env }}|{{ override }}|{{ args }}' > mixed_output.txt"+"#,+ );++ let output = repo+ .wt_command()+ .args([+ "hook",+ "post-create",+ "--yes",+ "--my-env=prod",+ "--var",+ "override=forced",+ "--unused=x",+ "--",+ "extra",+ ])+ .output()+ .expect("Failed to run wt hook");++ assert!(+ output.status.success(),+ "Hook should succeed, stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ let contents = fs::read_to_string(repo.root_path().join("mixed_output.txt")).unwrap();+ let trimmed = contents.trim();+ assert!(+ trimmed.starts_with("prod|forced|"),+ "Expected my_env + override bound, got: {trimmed}"+ );+ assert!(+ trimmed.contains("--unused=x") && trimmed.contains("extra"),+ "Unreferenced + post-`--` tokens should forward to {{{{ args }}}}, got: {trimmed}");}diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snapindex f95506d2a..43ac729bf 100644--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snap+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snap@@ -50,4 +50,4 @@ exit_code: 1[2m↳[22m [2mTo see details, run [4mwt config show[24m; to apply updates, run [4mwt config update[24m[22m[31m✗[39m [31mFailed to expand project pre-start hook: undefined value @ line 1[39m[107m [0m echo 'Upstream: {{ upstream }}' > upstream.txt-[2m↳[22m [2mAvailable variables: [4mbase[24m, [4mbase_worktree_path[24m, [4mbranch[24m, [4mcommit[24m, [4mcwd[24m, [4mdefault_branch[24m, [4mhook_type[24m, [4mmain_worktree[24m, [4mmain_worktree_path[24m, [4mprimary_worktree_path[24m, [4mremote[24m, [4mremote_url[24m, [4mrepo[24m, [4mrepo_path[24m, [4mrepo_root[24m, [4mshort_commit[24m, [4mtarget[24m, [4mtarget_worktree_path[24m, [4mworktree[24m, [4mworktree_name[24m, [4mworktree_path[24m[22m+[2m↳[22m [2mAvailable variables: [4margs[24m, [4mbase[24m, [4mbase_worktree_path[24m, [4mbranch[24m, [4mcommit[24m, [4mcwd[24m, [4mdefault_branch[24m, [4mhook_type[24m, [4mmain_worktree[24m, [4mmain_worktree_path[24m, [4mprimary_worktree_path[24m, [4mremote[24m, [4mremote_url[24m, [4mrepo[24m, [4mrepo_path[24m, [4mrepo_root[24m, [4mshort_commit[24m, [4mtarget[24m, [4mtarget_worktree_path[24m, [4mworktree[24m, [4mworktree_name[24m, [4mworktree_path[24m[22m