Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

refactor(hooks): always-lazy template expansion for hooks and aliases (#3042)

Maximilian Roos371d286628a1
diff --git a/docs/content/hook.md b/docs/content/hook.md
index 6f2619ab5..61710384a 100644
--- a/docs/content/hook.md
+++ b/docs/content/hook.md
@@ -23,7 +23,7 @@ Hooks are shell commands that run at key points in the worktree lifecycle — au
| **merge** | `pre-merge` | `post-merge` |
| **remove** | `pre-remove` | `post-remove` |
-`pre-*` hooks block — failure aborts the operation. `post-*` hooks run in the background with output logged (use [`wt config state logs`](@/config.md#wt-config-state-logs) to find and manage log files). Use `-v` to see expanded command details for background hooks.
+`pre-*` hooks block — failure aborts the operation. `post-*` hooks run in the background with output logged (use [`wt config state logs`](@/config.md#wt-config-state-logs) to find and manage log files). Use `-v` to see the template variables for background hooks; `wt hook <type> --dry-run` previews the commands.
The most common creation hook is `post-start` — it runs background tasks (dev servers, file copying, builds) without blocking worktree creation. Prefer `post-start` over `pre-start` unless a later step needs the work completed first.
@@ -102,6 +102,8 @@ server = "npm run dev"
Here `install` runs first, then `build` and `server` run together.
+Templates are syntax-checked before the pipeline starts and rendered as each step runs, so a step can store [per-branch vars](@/config.md#wt-config-state-vars) that later steps read via `{{ vars.<key> }}`.
+
Most hooks don't need `[[hook]]` blocks. Reach for them when there's a dependency chain — typically setup that must complete before later steps, like installing dependencies before running a build and dev server concurrently.
Table form for pre-* hooks is deprecated and its behavior will change in a future version — use `[[hook]]` blocks instead.
diff --git a/docs/content/tips-patterns.md b/docs/content/tips-patterns.md
index bfc1aeddc..0def63ce0 100644
--- a/docs/content/tips-patterns.md
+++ b/docs/content/tips-patterns.md
@@ -105,7 +105,7 @@ docker run -d --rm \
db-stop = "docker stop {{ vars.container }} 2>/dev/null || true"
```
-The first pipeline step derives values from the branch and stores them as vars. The second step references `{{ vars.container }}` and `{{ vars.port }}` — expanded at execution time, after the vars are set. `pre-remove` reads the same vars to stop the container.
+The first pipeline step derives values from the branch and stores them as vars. The second step references `{{ vars.container }}` and `{{ vars.port }}` — templates render when each step runs, so the vars are already set. `pre-remove` reads the same vars to stop the container.
The `('db-' ~ branch)` concatenation hashes differently than plain `branch`, so database and dev server ports don't collide. The `sanitize_db` filter produces database-safe identifiers (lowercase, underscores, no leading digits, with a short hash suffix).
diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.md
index 4248e2dbe..1fa289d31 100644
--- a/skills/worktrunk/reference/hook.md
+++ b/skills/worktrunk/reference/hook.md
@@ -14,7 +14,7 @@ Hooks are shell commands that run at key points in the worktree lifecycle — au
| **merge** | `pre-merge` | `post-merge` |
| **remove** | `pre-remove` | `post-remove` |
-`pre-*` hooks block — failure aborts the operation. `post-*` hooks run in the background with output logged (use [`wt config state logs`](https://worktrunk.dev/config/#wt-config-state-logs) to find and manage log files). Use `-v` to see expanded command details for background hooks.
+`pre-*` hooks block — failure aborts the operation. `post-*` hooks run in the background with output logged (use [`wt config state logs`](https://worktrunk.dev/config/#wt-config-state-logs) to find and manage log files). Use `-v` to see the template variables for background hooks; `wt hook <type> --dry-run` previews the commands.
The most common creation hook is `post-start` — it runs background tasks (dev servers, file copying, builds) without blocking worktree creation. Prefer `post-start` over `pre-start` unless a later step needs the work completed first.
@@ -93,6 +93,8 @@ server = "npm run dev"
Here `install` runs first, then `build` and `server` run together.
+Templates are syntax-checked before the pipeline starts and rendered as each step runs, so a step can store [per-branch vars](https://worktrunk.dev/config/#wt-config-state-vars) that later steps read via `{{ vars.<key> }}`.
+
Most hooks don't need `[[hook]]` blocks. Reach for them when there's a dependency chain — typically setup that must complete before later steps, like installing dependencies before running a build and dev server concurrently.
Table form for pre-* hooks is deprecated and its behavior will change in a future version — use `[[hook]]` blocks instead.
diff --git a/skills/worktrunk/reference/tips-patterns.md b/skills/worktrunk/reference/tips-patterns.md
index f9e33e459..255343b75 100644
--- a/skills/worktrunk/reference/tips-patterns.md
+++ b/skills/worktrunk/reference/tips-patterns.md
@@ -98,7 +98,7 @@ docker run -d --rm \
db-stop = "docker stop {{ vars.container }} 2>/dev/null || true"
```
-The first pipeline step derives values from the branch and stores them as vars. The second step references `{{ vars.container }}` and `{{ vars.port }}` — expanded at execution time, after the vars are set. `pre-remove` reads the same vars to stop the container.
+The first pipeline step derives values from the branch and stores them as vars. The second step references `{{ vars.container }}` and `{{ vars.port }}` — templates render when each step runs, so the vars are already set. `pre-remove` reads the same vars to stop the container.
The `('db-' ~ branch)` concatenation hashes differently than plain `branch`, so database and dev server ports don't collide. The `sanitize_db` filter produces database-safe identifiers (lowercase, underscores, no leading digits, with a short hash suffix).
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 936bd6c73..aac2b7885 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1243,7 +1243,7 @@ $ wt step push
| **merge** | `pre-merge` | `post-merge` |
| **remove** | `pre-remove` | `post-remove` |
-`pre-*` hooks block — failure aborts the operation. `post-*` hooks run in the background with output logged (use [`wt config state logs`](@/config.md#wt-config-state-logs) to find and manage log files). Use `-v` to see expanded command details for background hooks.
+`pre-*` hooks block — failure aborts the operation. `post-*` hooks run in the background with output logged (use [`wt config state logs`](@/config.md#wt-config-state-logs) to find and manage log files). Use `-v` to see the template variables for background hooks; `wt hook <type> --dry-run` previews the commands.
The most common creation hook is `post-start` — it runs background tasks (dev servers, file copying, builds) without blocking worktree creation. Prefer `post-start` over `pre-start` unless a later step needs the work completed first.
@@ -1322,6 +1322,8 @@ server = "npm run dev"
Here `install` runs first, then `build` and `server` run together.
+Templates are syntax-checked before the pipeline starts and rendered as each step runs, so a step can store [per-branch vars](@/config.md#wt-config-state-vars) that later steps read via `{{ vars.<key> }}`.
+
Most hooks don't need `[[hook]]` blocks. Reach for them when there's a dependency chain — typically setup that must complete before later steps, like installing dependencies before running a build and dev server concurrently.
Table form for pre-* hooks is deprecated and its behavior will change in a future version — use `[[hook]]` blocks instead.
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index 1a46acc0c..e78433c4b 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -7,11 +7,16 @@
//!
//! ## Execution model
//!
-//! Aliases build `ForegroundStep`s from `CommandConfig::steps()`, preserving
-//! pipeline structure (`Single` vs `Concurrent`). All commands use lazy template
-//! expansion — `vars.*` references resolve from git config at execution time,
-//! so prior steps that set vars via `wt config state vars set` are visible to
-//! later steps.
+//! Aliases build `ForegroundStep`s from `CommandConfig::steps()` via the
+//! shared `map_config_steps` walker, preserving pipeline structure (`Single`
+//! vs `Concurrent`). Like hooks, templates are syntax-checked before any
+//! step runs (here as a byproduct of the arg-routing parse in
+//! `referenced_vars_for_entry`) and rendered when each step runs — `vars.*`
+//! references resolve from git config at execution time, so prior steps that
+//! set vars via `wt config state vars set` are visible to later steps. The
+//! alias-specific residue is the context (built once, filtered to referenced
+//! vars, with `{{ args }}` injected from the CLI) and the labels (the alias
+//! name, no per-command log label).
//!
//! ## Why foreground and background execution differ
//!
@@ -43,7 +48,7 @@ use std::collections::{BTreeMap, BTreeSet};
use anyhow::{Context, bail};
use color_print::cformat;
use worktrunk::config::{
- ALIAS_ARGS_KEY, CommandConfig, HookStep, ProjectConfig, UserConfig, alias_context_filter,
+ ALIAS_ARGS_KEY, CommandConfig, ProjectConfig, UserConfig, alias_context_filter,
format_alias_variables, referenced_vars_for_config,
};
use worktrunk::git::Repository;
@@ -55,8 +60,8 @@ use worktrunk::trace::Span;
use crate::commands::command_approval::approve_alias_commands;
use crate::commands::command_executor::{
- CommandContext, FailureStrategy, PipelineKind, PreparedCommand, PreparedStep,
- build_hook_context, execute_pipeline_foreground,
+ CommandContext, FailureStrategy, PipelineKind, PreparedCommand, build_hook_context,
+ execute_pipeline_foreground, map_config_steps,
};
use crate::commands::hook_announcement::{
SourcedStep, format_pipeline_summary_from_names, step_names_from_config,
@@ -407,11 +412,13 @@ pub(crate) fn load_aliases(
/// Union of variables referenced across both source bodies of an alias.
/// Drives `--KEY=VALUE` routing in `AliasOptions::parse`: a flag binds to
-/// `{{ KEY }}` if KEY is referenced by *any* source's body.
-fn referenced_vars_for_entry(entry: &AliasEntry) -> anyhow::Result<BTreeSet<String>> {
+/// `{{ KEY }}` if KEY is referenced by *any* source's body. This parse is
+/// also where a syntax error in any alias template aborts — before flags are
+/// routed and before any step runs.
+fn referenced_vars_for_entry(name: &str, entry: &AliasEntry) -> anyhow::Result<BTreeSet<String>> {
let mut out = BTreeSet::new();
for (_, cfg) in entry.iter() {
- out.extend(referenced_vars_for_config(cfg)?);
+ out.extend(referenced_vars_for_config(cfg, name)?);
}
Ok(out)
}
@@ -447,7 +454,7 @@ pub fn try_alias(name: String, rest: Vec<String>, global_yes: bool) -> anyhow::R
};
let referenced = {
let _span = Span::new("referenced_vars");
- referenced_vars_for_entry(entry)?
+ referenced_vars_for_entry(&name, entry)?
};
if try_intercept_alias_help(&name, &rest, &referenced) {
return Ok(Some(()));
@@ -511,7 +518,7 @@ pub fn step_alias(args: Vec<String>, global_yes: bool) -> anyhow::Result<()> {
.collect();
return Err(unknown_step_command_error(&name, &alias_names));
};
- let referenced = referenced_vars_for_entry(entry)?;
+ let referenced = referenced_vars_for_entry(&name, entry)?;
if try_intercept_alias_help(&name, &args[1..], &referenced) {
return Ok(());
}
@@ -609,9 +616,6 @@ fn run_alias(
.expect("Vec<String> serialization should never fail"),
);
- let context_json = serde_json::to_string(&context_map)
- .expect("HashMap<String, String> serialization should never fail");
-
if verbosity() >= 1 {
let vars = format_alias_variables(&context_map, Some(&referenced));
eprintln!("{}", info_message("template variables:"));
@@ -632,21 +636,20 @@ fn run_alias(
let _span = Span::new(format!("prepare_steps:{}", alias_name));
let mut sourced_steps = Vec::new();
for (source, cfg) in entry.iter() {
- for step in cfg.steps() {
- let prepared = match step {
- HookStep::Single(cmd) => PreparedStep::Single(alias_prepared_command(
- cmd,
- &context_json,
- &alias_name,
- )),
- HookStep::Concurrent(cmds) => PreparedStep::Concurrent(
- cmds.iter()
- .map(|cmd| alias_prepared_command(cmd, &context_json, &alias_name))
- .collect(),
- ),
- };
+ // No syntax check here: `referenced_vars_for_entry` already parsed
+ // every template for arg routing before dispatch reached this point.
+ let steps = map_config_steps(cfg, |cmd| {
+ Ok(PreparedCommand {
+ name: cmd.name.clone(),
+ template: cmd.template.clone(),
+ context: context_map.clone(),
+ template_name: alias_name.clone(),
+ label: alias_name.clone(),
+ })
+ })?;
+ for step in steps {
sourced_steps.push(SourcedStep {
- step: prepared,
+ step,
source,
// Aliases have no deprecated single-table form, so concurrent
// commands always run concurrently.
@@ -660,22 +663,6 @@ fn run_alias(
execute_pipeline_foreground(&foreground_steps, repo, &wt_path, FailureStrategy::FailFast)
}
-/// Build a PreparedCommand for an alias, deferring template expansion to execution time.
-fn alias_prepared_command(
- cmd: &worktrunk::config::Command,
- context_json: &str,
- alias_name: &str,
-) -> PreparedCommand {
- PreparedCommand {
- name: cmd.name.clone(),
- expanded: cmd.template.clone(),
- context_json: context_json.to_string(),
- lazy_template: Some(cmd.template.clone()),
- label: alias_name.to_string(),
- log_label: None,
- }
-}
-
/// Which help page is being augmented. Controls the "shadowed by built-in"
/// annotation: at the top level, only top-level built-ins shadow an alias
/// (`wt list` blocks an alias named `list`). Under `wt step`, only step
@@ -1443,7 +1430,7 @@ cmd = [
]
"#,
);
- let refs = worktrunk::config::referenced_vars_for_config(&cfg).unwrap();
+ let refs = worktrunk::config::referenced_vars_for_config(&cfg, "deploy").unwrap();
let names: Vec<&str> = refs.iter().map(String::as_str).collect();
assert_eq!(names, vec!["args", "env", "target"]);
}
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 5f4758a68..06da62e01 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -1,7 +1,7 @@
use std::collections::{BTreeSet, HashMap};
use std::path::{Path, PathBuf};
-use anyhow::{Context, Result};
+use anyhow::Result;
use color_print::cformat;
use worktrunk::HookType;
use worktrunk::config::{
@@ -25,16 +25,28 @@ use crate::output::{DirectivePassthrough, execute_shell_command};
#[derive(Debug)]
pub struct PreparedCommand {
pub name: Option<String>,
- pub expanded: String,
- pub context_json: String,
- /// Raw template for lazy expansion at execution time (when template references `vars.`).
- /// When `Some`, the `expanded` field is a placeholder — use `lazy_template` instead.
- pub lazy_template: Option<String>,
- /// Label for template expansion errors and per-command announcement summary.
+ /// Raw template, rendered against `context` when the command runs.
+ /// Syntax is validated at preparation; rendering is deferred so `vars.*`
+ /// set by earlier pipeline steps are read fresh from git config.
+ pub template: String,
+ /// Template variables, frozen at preparation. Serialized to JSON only at
+ /// the process boundary (child stdin, background pipeline spec).
+ pub context: HashMap<String, String>,
+ /// Name used in template expansion errors: `"user:foo"` for named hook
+ /// commands, `"user pre-merge hook"` for unnamed ones, the alias name for
+ /// aliases.
+ pub template_name: String,
+ /// Label for the per-command announcement summary and render span.
/// For hooks: `"user:foo"` for named, `"user"` for unnamed. For aliases: alias name.
pub label: String,
- /// Log label for command tracing (e.g. `"pre-merge user:foo"`). `None` skips logging.
- pub log_label: Option<String>,
+}
+
+impl PreparedCommand {
+ /// The JSON form of `context` piped to the child's stdin.
+ pub fn context_json(&self) -> String {
+ serde_json::to_string(&self.context)
+ .expect("HashMap<String, String> serialization should never fail")
+ }
}
/// A step in a prepared pipeline, mirroring `HookStep`.
@@ -86,6 +98,17 @@ pub enum PipelineKind {
},
}
+impl PipelineKind {
+ /// Log label for command tracing: hooks log as `"{hook_type} {label}"`
+ /// (e.g. `"pre-merge user:foo"`); aliases skip per-command logging.
+ fn log_label(&self, cmd: &PreparedCommand) -> Option<String> {
+ match self {
+ Self::Hook { hook_type, .. } => Some(format!("{hook_type} {}", cmd.label)),
+ Self::Alias { .. } => None,
+ }
+ }
+}
+
/// A pipeline step ready for foreground execution, with rendering / error policy.
pub struct ForegroundStep {
pub step: PreparedStep,
@@ -370,9 +393,9 @@ pub fn wait_first_error<E>(
/// [`ShellEscapeMode::Posix`]: every caller (foreground hooks, background
/// pipelines, aliases) interpolates the result into a command line run
/// through `Cmd::shell` (`sh`/Git Bash), which is always POSIX — unlike the
-/// `--execute` payload, this never reaches a PowerShell wrapper. Used by the
-/// three execution paths that defer `vars.*` expansion until just before the
-/// command runs so prior steps can set vars via git config.
+/// `--execute` payload, this never reaches a PowerShell wrapper. Every
+/// execution path renders just before the command runs so prior steps can
+/// set `vars.*` via git config.
pub fn expand_shell_template(
template: &str,
context: &HashMap<String, String>,
@@ -394,18 +417,29 @@ pub fn expand_shell_template(
/// Resolve the shell string to execute for a prepared command.
///
-/// Commands carrying a `lazy_template` are re-expanded against their
-/// `context_json` at execution time so they see fresh git-config state
-/// (`vars.*` set by earlier steps). Commands without one were already
-/// expanded at prep time — return the cached `expanded` string.
+/// Templates render at execution time against the frozen `context`, so they
+/// see fresh git-config state (`vars.*` set by earlier steps).
fn resolve_command_str(cmd: &PreparedCommand, repo: &Repository) -> Result<String> {
- match &cmd.lazy_template {
- Some(template) => {
- let context: HashMap<String, String> = serde_json::from_str(&cmd.context_json)
- .context("failed to deserialize context_json")?;
- expand_shell_template(template, &context, repo, &cmd.label)
- }
- None => Ok(cmd.expanded.clone()),
+ expand_shell_template(&cmd.template, &cmd.context, repo, &cmd.template_name)
+}
+
+/// Render a template for dry-run / preview display. Mirrors execution-time
+/// semantics: a template referencing `vars.*` is shown raw after a syntax
+/// check — its values resolve from git config when the step runs, possibly
+/// written by earlier pipeline steps — while everything else renders against
+/// `context`. Expansion is side-effect-free, so previewing never perturbs the
+/// real run.
+pub fn render_template_preview(
+ template: &str,
+ context: &HashMap<String, String>,
+ repo: &Repository,
+ name: &str,
+) -> Result<String> {
+ if template_references_var(template, "vars") {
+ validate_template_syntax(template, name)?;
+ Ok(template.to_string())
+ } else {
+ expand_shell_template(template, context, repo, name)
}
}
@@ -420,8 +454,8 @@ pub(crate) fn command_summary_name(name: Option<&str>, source: HookSource) -> St
/// Execute a pipeline of prepared steps in the foreground.
///
/// This is the canonical foreground execution path for both hooks and aliases.
-/// Handles serial/concurrent step execution, per-command announcement, lazy
-/// template resolution, and policy-driven error handling.
+/// Handles serial/concurrent step execution, per-command announcement,
+/// execution-time template rendering, and policy-driven error handling.
///
/// Each `ForegroundStep` carries a `concurrent` flag. When true, `Concurrent`
/// steps spawn threads via `thread::scope`. When false (deprecated pre-*
@@ -454,12 +488,13 @@ pub fn execute_pipeline_foreground(
/// Run every command in a concurrent group via the prefixed-line executor.
///
-/// Announces each command up front (per the step's `PipelineKind` — hooks
+/// Expands all templates sequentially before spawning any thread (template
+/// expansion reads git config; racing on reads would produce inconsistent
+/// state), announces each command (per the step's `PipelineKind` — hooks
/// render per-command announcements, aliases only announce the outer group),
-/// expands all templates sequentially (template expansion reads git config;
-/// racing on reads would produce inconsistent state), then dispatches to
-/// `run_concurrent_commands` which streams each child's output prefixed by
-/// its label and waits for all to complete before folding outcomes.
+/// then dispatches to `run_concurrent_commands` which streams each child's
+/// output prefixed by its label and waits for all to complete before folding
+/// outcomes.
fn run_concurrent_group(
cmds: &[PreparedCommand],
fg_step: &ForegroundStep,
@@ -468,9 +503,6 @@ fn run_concurrent_group(
failure_strategy: FailureStrategy,
) -> anyhow::Result<()> {
let directives = &fg_step.directives;
- for cmd in cmds {
- announce_command(cmd, &fg_step.announce);
- }
let expanded: Vec<String> = cmds
.iter()
@@ -480,6 +512,10 @@ fn run_concurrent_group(
})
.collect::<Result<_>>()?;
+ for (cmd, command_str) in cmds.iter().zip(&expanded) {
+ announce_command(cmd, &fg_step.announce, command_str);
+ }
+
// Both alias tables and hook tables produce named commands (TOML keys
// become `name`), so `cmd.name` is always `Some` here.
let labels: Vec<&str> = cmds
@@ -491,15 +527,19 @@ fn run_concurrent_group(
})
.collect();
- let specs: Vec<ConcurrentCommand<'_>> = cmds
+ let context_jsons: Vec<String> = cmds.iter().map(PreparedCommand::context_json).collect();
+ let log_labels: Vec<Option<String>> = cmds
.iter()
- .enumerate()
- .map(|(i, cmd)| ConcurrentCommand {
+ .map(|cmd| fg_step.announce.log_label(cmd))
+ .collect();
+
+ let specs: Vec<ConcurrentCommand<'_>> = (0..cmds.len())
+ .map(|i| ConcurrentCommand {
label: labels[i],
expanded: &expanded[i],
working_dir: wt_path,
- context_json: &cmd.context_json,
- log_label: cmd.log_label.as_deref(),
+ context_json: &context_jsons[i],
+ log_label: log_labels[i].as_deref(),
directives,
})
.collect();
@@ -524,7 +564,7 @@ fn run_concurrent_group(
}
}
-/// Execute a single prepared command: announce, expand, run, handle errors.
+/// Execute a single prepared command: expand, announce, run, handle errors.
fn run_one_command(
cmd: &PreparedCommand,
fg_step: &ForegroundStep,
@@ -533,26 +573,23 @@ fn run_one_command(
failure_strategy: FailureStrategy,
) -> anyhow::Result<()> {
let directives = &fg_step.directives;
- announce_command(cmd, &fg_step.announce);
let command_str = {
let _span = Span::new(format!("template_render:{}", cmd.label));
resolve_command_str(cmd, repo)?
};
+ announce_command(cmd, &fg_step.announce, &command_str);
// Hooks get a documented JSON context on stdin; aliases inherit stdin so
// interactive children (e.g. `wt switch`'s picker) keep their controlling
// terminal. Piping JSON into an interactive alias body steals the tty.
- let stdin_json = if fg_step.pipe_stdin {
- Some(cmd.context_json.as_str())
- } else {
- None
- };
+ let stdin_json = fg_step.pipe_stdin.then(|| cmd.context_json());
+ let log_label = fg_step.announce.log_label(cmd);
let result = execute_shell_command(
wt_path,
&command_str,
- stdin_json,
- cmd.log_label.as_deref(),
+ stdin_json.as_deref(),
+ log_label.as_deref(),
directives.clone(),
fg_step.redirect_stdout_to_stderr,
);
@@ -565,10 +602,11 @@ fn run_one_command(
/// Announce a command before execution, formatted per the step's pipeline kind.
///
-/// Hook pipelines emit a per-command "Running …" line plus the bash gutter.
-/// Alias pipelines emit nothing — the alias caller renders a single pipeline
-/// summary externally.
-fn announce_command(cmd: &PreparedCommand, kind: &PipelineKind) {
+/// Hook pipelines emit a per-command "Running …" line plus a bash gutter
+/// showing `command_str` — the rendered command about to run. Alias pipelines
+/// emit nothing — the alias caller renders a single pipeline summary
+/// externally.
+fn announce_command(cmd: &PreparedCommand, kind: &PipelineKind, command_str: &str) {
let PipelineKind::Hook {
hook_type,
display_path,
@@ -589,14 +627,12 @@ fn announce_command(cmd: &PreparedCommand, kind: &PipelineKind) {
None => full_label,
};
if verbosity() >= 1 {
- let ctx: HashMap<String, String> = serde_json::from_str(&cmd.context_json)
- .expect("context_json is always serialized from a HashMap<String, String>");
- let vars = format_hook_variables(*hook_type, &ctx);
+ let vars = format_hook_variables(*hook_type, &cmd.context);
eprintln!("{}", info_message("template variables:"));
eprintln!("{}", format_with_gutter(&vars, None));
}
eprintln!("{}", progress_message(message));
- eprintln!("{}", format_bash_with_gutter(&cmd.expanded));
+ eprintln!("{}", format_bash_with_gutter(command_str));
}
/// Build the standard `ErrorWrapper` for hook steps.
@@ -668,19 +704,44 @@ fn handle_command_error(
}
}
-/// Expand commands from a CommandConfig without approval.
+/// Walk a config's pipeline structure, preparing each command.
///
-/// When `lazy_enabled` is true, commands referencing `vars.` are validated but not
-/// expanded — they carry a `lazy_template` for deferred expansion at execution time.
-/// Only enable for pipeline steps where ordering guarantees vars are set by prior steps.
-fn expand_commands(
- commands: &[Command],
+/// Shared by hook and alias preparation: preserves the `Single` vs
+/// `Concurrent` grouping from the config while `prepare` supplies the
+/// per-command [`PreparedCommand`] (context construction and label naming
+/// differ between hooks and aliases).
+pub fn map_config_steps(
+ config: &CommandConfig,
+ mut prepare: impl FnMut(&Command) -> anyhow::Result<PreparedCommand>,
+) -> anyhow::Result<Vec<PreparedStep>> {
+ config
+ .steps()
+ .iter()
+ .map(|step| match step {
+ HookStep::Single(cmd) => Ok(PreparedStep::Single(prepare(cmd)?)),
+ HookStep::Concurrent(cmds) => Ok(PreparedStep::Concurrent(
+ cmds.iter().map(&mut prepare).collect::<Result<_>>()?,
+ )),
+ })
+ .collect()
+}
+
+/// Prepare hook pipeline steps for execution, preserving serial/concurrent
+/// structure. All hook preparation goes through this function (both
+/// foreground and background paths).
+///
+/// Each command freezes its context as JSON and keeps its raw template;
+/// rendering happens when the command runs. Syntax errors abort here — before
+/// the first step runs — while semantic errors (undefined variable, filter
+/// failure) surface at the failing step.
+pub fn prepare_steps(
+ command_config: &CommandConfig,
ctx: &CommandContext<'_>,
extra_vars: &[(&str, &str)],
hook_type: HookType,
source: HookSource,
- lazy_enabled: bool,
-) -> anyhow::Result<Vec<(Command, String, Option<String>)>> {
+) -> anyhow::Result<Vec<PreparedStep>> {
+ // Built once per pipeline — build_hook_context spawns git subprocesses.
let mut base_context = build_hook_context(ctx, extra_vars, None)?;
// hook_type is always available as a template variable and in JSON context
@@ -694,9 +755,7 @@ fn expand_commands(
.entry(worktrunk::config::ALIAS_ARGS_KEY.to_string())
.or_insert_with(|| "[]".to_string());
- let mut result = Vec::new();
-
- for cmd in commands {
+ map_config_steps(command_config, |cmd| {
// hook_name is per-command: available as template variable and in JSON context
let mut cmd_context = base_context.clone();
if let Some(ref name) = cmd.name {
@@ -704,100 +763,19 @@ fn expand_commands(
}
let template_name = match &cmd.name {
- Some(name) => format!("{}:{}", source, name),
- None => format!("{} {} hook", source, hook_type),
- };
-
- let lazy = lazy_enabled && template_references_var(&cmd.template, "vars");
-
- let (expanded_str, lazy_template) = if lazy {
- // Parse-only validation: catch syntax errors upfront without rendering.
- // Full rendering (validate_template) would fail on {{ vars.X }} because
- // vars aren't set yet — that's the whole point of lazy expansion.
- validate_template_syntax(&cmd.template, &template_name)
- .map_err(|e| anyhow::anyhow!("syntax error in {template_name}: {e}"))?;
- let tpl = cmd.template.clone();
- (tpl.clone(), Some(tpl))
- } else {
- (
- expand_shell_template(&cmd.template, &cmd_context, ctx.repo, &template_name)?,
- None,
- )
+ Some(name) => format!("{source}:{name}"),
+ None => format!("{source} {hook_type} hook"),
};
-
- let context_json = serde_json::to_string(&cmd_context)
- .expect("HashMap<String, String> serialization should never fail");
-
- result.push((
- Command::with_expansion(cmd.name.clone(), cmd.template.clone(), expanded_str),
- context_json,
- lazy_template,
- ));
- }
-
- Ok(result)
-}
-
-/// Prepare pipeline steps for execution, preserving serial/concurrent structure.
-///
-/// Returns `Vec<PreparedStep>` that preserves the pipeline structure from
-/// the config — `Single` vs `Concurrent` grouping. All hook preparation
-/// goes through this function (both foreground and background paths).
-pub fn prepare_steps(
- command_config: &CommandConfig,
- ctx: &CommandContext<'_>,
- extra_vars: &[(&str, &str)],
- hook_type: HookType,
- source: HookSource,
-) -> anyhow::Result<Vec<PreparedStep>> {
- let steps = command_config.steps();
-
- // Collect step sizes so we can re-partition after a single expand_commands call.
- // This avoids calling build_hook_context (which spawns git subprocesses) per step.
- let step_sizes: Vec<usize> = steps
- .iter()
- .map(|s| match s {
- HookStep::Single(_) => 1,
- HookStep::Concurrent(cmds) => cmds.len(),
+ validate_template_syntax(&cmd.template, &template_name)?;
+
+ Ok(PreparedCommand {
+ name: cmd.name.clone(),
+ template: cmd.template.clone(),
+ context: cmd_context,
+ template_name,
+ label: command_summary_name(cmd.name.as_deref(), source),
})
- .collect();
-
- let all_commands: Vec<Command> = command_config.commands().cloned().collect();
- let all_expanded = expand_commands(&all_commands, ctx, extra_vars, hook_type, source, true)?;
- let mut expanded_iter = all_expanded.into_iter();
-
- let make_prepared = |cmd: Command, json: String, lazy: Option<String>| -> PreparedCommand {
- let label = command_summary_name(cmd.name.as_deref(), source);
- let log_label = format!("{hook_type} {label}");
- PreparedCommand {
- name: cmd.name,
- expanded: cmd.expanded,
- context_json: json,
- lazy_template: lazy,
- label,
- log_label: Some(log_label),
- }
- };
-
- let mut result = Vec::new();
- for (step, &size) in steps.iter().zip(&step_sizes) {
- let chunk: Vec<_> = expanded_iter.by_ref().take(size).collect();
- match step {
- HookStep::Single(_) => {
- let (cmd, json, lazy) = chunk.into_iter().next().unwrap();
- result.push(PreparedStep::Single(make_prepared(cmd, json, lazy)));
- }
- HookStep::Concurrent(_) => {
- let prepared = chunk
- .into_iter()
- .map(|(cmd, json, lazy)| make_prepared(cmd, json, lazy))
- .collect();
- result.push(PreparedStep::Concurrent(prepared));
- }
- }
- }
-
- Ok(result)
+ })
}
#[cfg(test)]
@@ -806,14 +784,12 @@ mod tests {
fn make_cmd(name: Option<&str>) -> PreparedCommand {
let label = command_summary_name(name, HookSource::User);
- let log_label = format!("pre-merge {label}");
PreparedCommand {
name: name.map(String::from),
- expanded: "echo test".to_string(),
- context_json: "{}".to_string(),
- lazy_template: None,
+ template: "echo test".to_string(),
+ context: HashMap::new(),
+ template_name: label.clone(),
label,
- log_label: Some(log_label),
}
}
diff --git a/src/commands/config/alias.rs b/src/commands/config/alias.rs
index 558f1611c..945bf2440 100644
--- a/src/commands/config/alias.rs
+++ b/src/commands/config/alias.rs
@@ -20,14 +20,13 @@
//! alias-dispatch path single-purpose (always runs) and gives preview a
//! natural home alongside `show`.
-use std::collections::{BTreeSet, HashMap};
+use std::collections::BTreeSet;
use std::io::Write;
use anyhow::Context;
use color_print::cformat;
use worktrunk::config::{
ALIAS_ARGS_KEY, CommandConfig, ProjectConfig, UserConfig, referenced_vars_for_config,
- template_references_var, validate_template_syntax,
};
use worktrunk::git::{Repository, WorktrunkError};
use worktrunk::styling::{format_bash_with_gutter, info_message, println};
@@ -37,7 +36,7 @@ use crate::commands::alias::{
};
use crate::commands::build_invalid_subcommand_error;
use crate::commands::command_executor::{
- CommandContext, build_hook_context, expand_shell_template,
+ CommandContext, build_hook_context, render_template_preview,
};
use crate::commands::did_you_mean;
use crate::commands::hooks::HookSource;
@@ -139,10 +138,11 @@ fn warn_if_shadowed(name: &str) {
/// Preview an alias invocation: parse the args, build the template context,
/// and print the rendered command(s) without executing.
///
-/// Lazy semantics are preserved: templates referencing `vars.*` are shown
-/// raw (after syntax validation) because those values resolve from git
-/// config at execution time, potentially written by earlier pipeline steps.
-/// Other templates expand against the current context.
+/// Rendering goes through [`render_template_preview`], which mirrors
+/// execution-time semantics: templates referencing `vars.*` are shown raw
+/// (after syntax validation) because those values resolve from git config
+/// when the step runs, potentially written by earlier pipeline steps. Other
+/// templates expand against the current context.
pub fn handle_alias_dry_run(name: String, args: Vec<String>) -> anyhow::Result<()> {
let repo = Repository::current()?;
let user_config = repo.user_config();
@@ -165,7 +165,7 @@ pub fn handle_alias_dry_run(name: String, args: Vec<String>) -> anyhow::Result<(
// so a flag binds if any entry's template references it.
let mut referenced: BTreeSet<String> = BTreeSet::new();
for (cfg, _) in &entries {
- referenced.extend(referenced_vars_for_config(cfg)?);
+ referenced.extend(referenced_vars_for_config(cfg, &name)?);
}
let mut parse_args = Vec::with_capacity(1 + args.len());
parse_args.push(name.clone());
@@ -197,7 +197,7 @@ pub fn handle_alias_dry_run(name: String, args: Vec<String>) -> anyhow::Result<(
for (cfg, source) in &entries {
let bodies: Vec<String> = cfg
.commands()
- .map(|c| render_preview(&c.template, &context_map, &repo, &name))
+ .map(|c| render_template_preview(&c.template, &context_map, &repo, &name))
.collect::<anyhow::Result<_>>()?;
println!(
"{}",
@@ -243,23 +243,6 @@ fn format_routing_summary(opts: &AliasOptions) -> Option<String> {
Some(lines)
}
-/// Render a single command template for preview. Mirrors execution-time lazy
-/// semantics — see the module-level docstring.
-fn render_preview(
- template: &str,
- context: &HashMap<String, String>,
- repo: &Repository,
- alias_name: &str,
-) -> anyhow::Result<String> {
- if template_references_var(template, "vars") {
- validate_template_syntax(template, alias_name)
- .map_err(|e| anyhow::anyhow!("syntax error in alias {alias_name}: {e}"))?;
- Ok(template.to_string())
- } else {
- Ok(expand_shell_template(template, context, repo, alias_name)?)
- }
-}
-
/// Resolve `name` against user + project config, preserving runtime execution
/// order (user first, then project).
fn entries_for_name(
diff --git a/src/commands/hook_announcement.rs b/src/commands/hook_announcement.rs
index e9b60fb1d..e8deb7e62 100644
--- a/src/commands/hook_announcement.rs
+++ b/src/commands/hook_announcement.rs
@@ -225,18 +225,17 @@ mod tests {
}
}
- fn make_cmd(name: Option<&str>, expanded: &str) -> PreparedCommand {
+ fn make_cmd(name: Option<&str>, template: &str) -> PreparedCommand {
let label = match name {
Some(n) => format!("user:{n}"),
None => "user".to_string(),
};
PreparedCommand {
name: name.map(String::from),
- expanded: expanded.to_string(),
- context_json: "{}".to_string(),
- lazy_template: None,
+ template: template.to_string(),
+ context: std::collections::HashMap::new(),
+ template_name: label.clone(),
label,
- log_label: None,
}
}
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index 47b5076ae..32da4de52 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -22,7 +22,9 @@ use worktrunk::styling::{
};
use super::command_approval::approve_hooks_filtered;
-use super::command_executor::{CommandContext, FailureStrategy, build_hook_context};
+use super::command_executor::{
+ CommandContext, FailureStrategy, build_hook_context, render_template_preview,
+};
use super::context::CommandEnv;
use super::hooks::{HookAnnouncer, prepare_and_check, run_hooks_foreground};
use super::template_vars::TemplateVars;
@@ -134,13 +136,20 @@ fn parse_shorthand_token(raw: &str) -> anyhow::Result<(String, String, String)>
fn referenced_vars_union(
user_config: Option<&CommandConfig>,
project_config: Option<&CommandConfig>,
+ hook_type: HookType,
) -> 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)?);
+ out.extend(referenced_vars_for_config(
+ cfg,
+ &format!("user {hook_type} hook"),
+ )?);
}
if let Some(cfg) = project_config {
- out.extend(referenced_vars_for_config(cfg)?);
+ out.extend(referenced_vars_for_config(
+ cfg,
+ &format!("project {hook_type} hook"),
+ )?);
}
Ok(out)
}
@@ -229,7 +238,7 @@ pub fn run_hook(
// 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 referenced = referenced_vars_union(user_config, proj_config, hook_type)?;
let mut bindings: Vec<(String, String)> = Vec::new();
let mut args: Vec<String> = Vec::new();
for raw in shorthand_vars {
@@ -288,6 +297,8 @@ pub fn run_hook(
for sourced in steps {
for cmd in sourced.step.into_commands() {
+ let preview =
+ render_template_preview(&cmd.template, &cmd.context, repo, &cmd.template_name)?;
let label = if cmd.name.is_some() {
cformat!("{hook_type} <bold>{}</> would run:", cmd.label)
} else {
@@ -295,10 +306,7 @@ pub fn run_hook(
};
eprintln!(
"{}",
- info_message(cformat!(
- "{label}\n{}",
- format_bash_with_gutter(&cmd.expanded)
- ))
+ info_message(cformat!("{label}\n{}", format_bash_with_gutter(&preview)))
);
}
}
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index 0e67a6e18..2940fb04d 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -62,7 +62,6 @@
//! (test isolation); user config (`~/.config/worktrunk/config.toml`) is global
//! and unaffected.
-use std::collections::HashMap;
use std::path::{Path, PathBuf};
use anyhow::Context;
@@ -468,12 +467,10 @@ fn print_background_variable_table(pipelines: &[PendingPipeline], hook_type: Hoo
PreparedStep::Single(cmd) => cmd,
PreparedStep::Concurrent(cmds) => &cmds[0],
};
- let ctx: HashMap<String, String> = serde_json::from_str(&cmd.context_json)
- .expect("context_json is always serialized from a HashMap<String, String>");
eprintln!("{}", info_message("template variables:"));
eprintln!(
"{}",
- format_with_gutter(&format_hook_variables(hook_type, &ctx), None)
+ format_with_gutter(&format_hook_variables(hook_type, &cmd.context), None)
);
return;
}
@@ -496,26 +493,24 @@ fn spawn_hook_pipeline_quiet(repo: &Repository, pipeline: &PendingPipeline) -> a
PreparedStep::Single(cmd) => cmd,
PreparedStep::Concurrent(cmds) => &cmds[0],
};
- let mut context: std::collections::HashMap<String, String> =
- serde_json::from_str(&first_cmd.context_json)
- .context("failed to deserialize context_json")?;
+ let mut context = first_cmd.context.clone();
context.remove("hook_name");
- // Build pipeline spec from prepared steps. Use the raw template for lazy
- // steps (vars-referencing) and the expanded command for eager steps.
+ // Build pipeline spec from prepared steps. The runner renders each raw
+ // template when its step runs (see `run_pipeline`'s "Template freshness").
let spec_steps: Vec<PipelineStepSpec> = steps
.iter()
.map(|s| match &s.step {
PreparedStep::Single(cmd) => PipelineStepSpec::Single {
name: cmd.name.clone(),
- template: cmd.lazy_template.as_ref().unwrap_or(&cmd.expanded).clone(),
+ template: cmd.template.clone(),
},
PreparedStep::Concurrent(cmds) => PipelineStepSpec::Concurrent {
commands: cmds
.iter()
.map(|c| PipelineCommandSpec {
name: c.name.clone(),
- template: c.lazy_template.as_ref().unwrap_or(&c.expanded).clone(),
+ template: c.template.clone(),
})
.collect(),
},
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 65fb65dd8..aeb170a1c 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -1981,9 +1981,10 @@ fn validate_switch_templates(
for (source, cfg) in [("user", user_cfg), ("project", proj_cfg)] {
if let Some(cfg) = cfg {
for cmd in cfg.commands() {
- // Skip full validation for lazy templates ({{ vars.X }}) —
- // they're expanded at runtime after prior pipeline steps set
- // the vars. Syntax is still checked by expand_commands.
+ // Skip full validation for templates referencing {{ vars.X }} —
+ // those values come from git config at execution time, after
+ // prior pipeline steps set them. Syntax is still checked by
+ // prepare_steps.
if template_references_var(&cmd.template, "vars") {
continue;
}
diff --git a/src/config/commands.rs b/src/config/commands.rs
index 2fe56d8f8..20e575881 100644
--- a/src/config/commands.rs
+++ b/src/config/commands.rs
@@ -44,34 +44,18 @@ use schemars::JsonSchema;
use serde::ser::SerializeMap;
use serde::{Deserialize, Serialize};
-/// Represents a command with its template and optionally expanded form.
+/// Represents a configured command template.
#[derive(Debug, Clone, PartialEq)]
pub struct Command {
/// Optional name for the command (e.g., "build", "test")
pub name: Option<String>,
/// Template string that may contain variables like {{ branch }}, {{ worktree }}
pub template: String,
- /// Expanded command with variables substituted (same as template if not expanded yet)
- pub expanded: String,
}
impl Command {
- /// Create a new command from a template (not yet expanded)
pub fn new(name: Option<String>, template: String) -> Self {
- Self {
- name,
- expanded: template.clone(),
- template,
- }
- }
-
- /// Create a command with both template and expanded forms
- pub fn with_expansion(name: Option<String>, template: String, expanded: String) -> Self {
- Self {
- name,
- template,
- expanded,
- }
+ Self { name, template }
}
}
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 33123c9e9..636e29d41 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -17,7 +17,6 @@ use std::fmt;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
-use anyhow::Context;
use color_print::cformat;
use minijinja::value::{Enumerator, Object, ObjectRepr};
use minijinja::{Environment, ErrorKind, UndefinedBehavior, Value};
@@ -790,13 +789,19 @@ pub fn template_references_var(template: &str, var: &str) -> bool {
/// a binding candidate for the whole invocation. A syntax error in any
/// template fails here so the user sees it before flags are routed — a
/// silent skip could mask a typo and change how subsequent CLI args bind.
-pub fn referenced_vars_for_config(cfg: &super::CommandConfig) -> anyhow::Result<BTreeSet<String>> {
+/// `name` labels the failing alias or hook in the error, which matches
+/// [`expand_template`]'s parse-failure shape so syntax errors render
+/// identically wherever they surface.
+pub fn referenced_vars_for_config(
+ cfg: &super::CommandConfig,
+ name: &str,
+) -> anyhow::Result<BTreeSet<String>> {
let env = minijinja::Environment::new();
let mut out = BTreeSet::new();
for cmd in cfg.commands() {
let tmpl = env
.template_from_str(&cmd.template)
- .with_context(|| format!("Failed to parse template: {:?}", cmd.template))?;
+ .map_err(|e| build_template_error(&e, &cmd.template, name, Vec::new()))?;
out.extend(tmpl.undeclared_variables(false));
}
Ok(out)
@@ -804,13 +809,17 @@ pub fn referenced_vars_for_config(cfg: &super::CommandConfig) -> anyhow::Result<
/// Parse-only syntax check for a template.
///
-/// Used on lazy-expansion paths (hooks + aliases) where rendering would fail
-/// because `vars.*` values are only known at execution time — we still want
-/// to catch typos like `{{ vars..foo }}` upfront.
-pub fn validate_template_syntax(template: &str, name: &str) -> Result<(), minijinja::Error> {
+/// Hook and alias preparation runs this on every template so syntax errors
+/// (e.g. `{{ vars..foo }}`) abort before the first pipeline step runs;
+/// rendering — and with it semantic errors like undefined variables — is
+/// deferred to execution time. The error matches [`expand_template`]'s
+/// parse-failure shape so syntax errors render identically wherever they
+/// surface.
+pub fn validate_template_syntax(template: &str, name: &str) -> Result<(), TemplateExpandError> {
minijinja::Environment::new()
.template_from_named_str(name, template)
.map(|_| ())
+ .map_err(|e| build_template_error(&e, template, name, Vec::new()))
}
/// Validate that a template can be expanded without errors in the given scope.
@@ -2767,9 +2776,9 @@ mod tests {
#[test]
fn test_referenced_vars_for_config_syntax_error_propagates() {
let cfg = super::super::CommandConfig::single("echo {{ unclosed");
- let err = referenced_vars_for_config(&cfg).unwrap_err();
+ let err = referenced_vars_for_config(&cfg, "deploy").unwrap_err();
let msg = format!("{err:#}");
- assert!(msg.contains("Failed to parse template"), "got: {msg}");
+ assert!(msg.contains("Failed to expand deploy"), "got: {msg}");
assert!(msg.contains("syntax error"), "got: {msg}");
}
diff --git a/src/git/repository/config.rs b/src/git/repository/config.rs
index 40c053f57..d2034e503 100644
--- a/src/git/repository/config.rs
+++ b/src/git/repository/config.rs
@@ -135,10 +135,10 @@ impl Repository {
/// via `{{ vars.key }}`.
///
/// Reads git config directly — **not** via the bulk `all_config` cache —
- /// because lazy template expansion in hook/alias pipelines depends on
- /// seeing writes that earlier steps made via their own `git config`
- /// subprocesses. Those external writes don't round-trip through our
- /// coherent `set_config_value` helper.
+ /// because hook/alias templates render at execution time and depend on
+ /// seeing writes that earlier pipeline steps made via their own
+ /// `git config` subprocesses. Those external writes don't round-trip
+ /// through our coherent `set_config_value` helper.
pub fn vars_entries(&self, branch: &str) -> std::collections::BTreeMap<String, String> {
let escaped = regex::escape(branch);
let pattern = format!(r"^worktrunk\.state\.{escaped}\.vars\.");
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index ad8d3243a..8da541878 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -1038,8 +1038,11 @@ fn test_merge_drops_pending_hooks_when_post_merge_fails(mut repo: TestRepo) {
let post_remove_marker = temp_root.join("drop_postremove_marker.txt");
let post_merge_marker = temp_root.join("drop_postmerge_marker.txt");
- // post-merge references an undefined variable, so `register` errors after
+ // post-merge has a template syntax error, so `register` errors after
// post-remove + post-switch are already pending in the announcer.
+ // (Semantic errors like undefined variables no longer fail prep — they
+ // surface when the runner renders the step; see
+ // test_background_hook_undefined_var_fails_in_runner.)
// Convert to forward slashes so the rendered shell command parses the same
// way under Windows Git Bash (where backslashes in unquoted paths get
// eaten as escape-of-next-char).
@@ -1051,7 +1054,7 @@ cleanup = "echo POST_REMOVE_RAN > {}"
notify = "echo switched"
[post-merge]
-sync = "echo POST_MERGE_RAN > {} {{{{ does_not_exist }}}}"
+sync = "echo POST_MERGE_RAN > {} {{{{ bad..syntax }}}}"
"#,
post_remove_marker.to_slash_lossy(),
post_merge_marker.to_slash_lossy(),
@@ -1065,7 +1068,7 @@ sync = "echo POST_MERGE_RAN > {} {{{{ does_not_exist }}}}"
.unwrap();
assert!(
!output.status.success(),
- "merge should fail when post-merge template references undefined variable"
+ "merge should fail when a post-merge template has a syntax error"
);
// Drop flushed the pending pipelines: post-remove ran despite the failure.
@@ -1083,6 +1086,81 @@ sync = "echo POST_MERGE_RAN > {} {{{{ does_not_exist }}}}"
);
}
+/// A semantic template error (undefined variable) in a background hook does
+/// not fail the foreground command: templates render when each step runs, so
+/// the error surfaces in the detached runner and lands in its log. Only
+/// syntax errors abort at prep (see
+/// test_merge_drops_pending_hooks_when_post_merge_fails).
+#[rstest]
+fn test_background_hook_undefined_var_fails_in_runner(repo: TestRepo) {
+ repo.write_test_config(
+ r#"[post-start]
+broken = "echo {{ does_not_exist }} > should_not_exist.txt"
+"#,
+ );
+
+ let mut cmd = crate::common::wt_command();
+ cmd.current_dir(repo.root_path());
+ cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
+ cmd.args(["hook", "post-start", "--yes"]);
+
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "background spawn should succeed; rendering fails later in the runner.\nstderr: {}",
+ String::from_utf8_lossy(&output.stderr),
+ );
+
+ // The runner renders the template, fails, and reports into its own log
+ // at `{branch}/{source}/{hook_type}/runner.log`.
+ let runner_log = resolve_git_common_dir(repo.root_path())
+ .join("wt/logs")
+ .join(worktrunk::path::sanitize_for_filename("main"))
+ .join("user")
+ .join("post-start")
+ .join("runner.log");
+ wait_for_file_content(&runner_log);
+ let log_content = fs::read_to_string(&runner_log).unwrap();
+ assert!(
+ log_content.contains("Failed to expand"),
+ "runner log should contain the template error, got: {log_content}"
+ );
+
+ // The step never ran.
+ assert!(!repo.root_path().join("should_not_exist.txt").exists());
+}
+
+/// A semantic template error in a foreground pipeline step surfaces when that
+/// step runs: earlier steps execute first, then the broken step's render
+/// aborts the pipeline. (Pre-change, prep expanded every template upfront and
+/// nothing ran.) Syntax errors still abort before step 1.
+#[rstest]
+fn test_foreground_pipeline_undefined_var_runs_earlier_steps(repo: TestRepo) {
+ repo.write_test_config(
+ r#"pre-merge = [
+ { first = "echo FIRST_RAN > first_marker.txt" },
+ { broken = "echo {{ does_not_exist }}" },
+]
+"#,
+ );
+
+ let mut cmd = crate::common::wt_command();
+ cmd.current_dir(repo.root_path());
+ cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
+ cmd.args(["hook", "pre-merge", "--yes"]);
+
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ assert_cmd_snapshot!("foreground_pipeline_undefined_var_runs_earlier_steps", cmd);
+ });
+
+ let marker = repo.root_path().join("first_marker.txt");
+ assert!(
+ marker.exists(),
+ "step 1 should have run before step 2's template error"
+ );
+}
+
/// When removing the current worktree (cd back to main), both post-remove and
/// post-switch hooks fire. They should appear on a single combined announcement line.
#[rstest]
@@ -3179,8 +3257,8 @@ fn test_user_post_start_pipeline_failure_skips_later_steps(repo: TestRepo) {
#[rstest]
fn test_user_post_start_pipeline_lazy_vars_foreground(repo: TestRepo) {
// Pipeline step 1 sets a var, step 2 uses it via {{ vars.name }}.
- // Foreground mode exercises the in-process lazy re-expansion path
- // in run_hook_with_filter.
+ // Foreground mode exercises the in-process execution-time render path,
+ // which reads vars fresh from git config per step.
repo.write_test_config(
r#"post-start = [
"git config worktrunk.state.main.vars.name '{{ branch | sanitize }}-postgres'",
@@ -3209,13 +3287,13 @@ fn test_user_post_start_pipeline_lazy_vars_foreground(repo: TestRepo) {
let marker_file = repo.root_path().join("lazy_expanded.txt");
assert!(
marker_file.exists(),
- "Foreground lazy expansion should create marker file"
+ "Foreground render should create marker file"
);
let content = fs::read_to_string(&marker_file).unwrap().trim().to_string();
assert_eq!(
content, "main-postgres",
- "Lazy step should see var set by prior step"
+ "Step 2 should see var set by prior step"
);
}
@@ -3486,11 +3564,11 @@ fn test_user_post_remove_pipeline_serial_ordering(mut repo: TestRepo) {
}
// ============================================================================
-// Name-filtered lazy template (Bug 3 regression test)
+// Name-filtered vars template (Bug 3 regression test)
// ============================================================================
#[rstest]
-fn test_standalone_hook_name_filtered_lazy_template(repo: TestRepo) {
+fn test_standalone_hook_name_filtered_vars_template(repo: TestRepo) {
// A pipeline step that uses {{ vars.X }} should expand correctly when
// name-filtered via `wt hook post-start db`. Before the fix, the flat
// spawn path passed the raw unexpanded template to the shell.
@@ -3499,7 +3577,7 @@ fn test_standalone_hook_name_filtered_lazy_template(repo: TestRepo) {
repo.write_test_config(
r#"post-start = [
{ setup = "echo setup" },
- { db = "echo {{ vars.name }} > lazy_filtered.txt" }
+ { db = "echo {{ vars.name }} > vars_filtered.txt" }
]
"#,
);
@@ -3513,16 +3591,16 @@ fn test_standalone_hook_name_filtered_lazy_template(repo: TestRepo) {
let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
let mut cmd = make_snapshot_cmd(&repo, "hook", &["post-start", "db"], None);
- assert_cmd_snapshot!("standalone_hook_name_filtered_lazy_template", cmd);
+ assert_cmd_snapshot!("standalone_hook_name_filtered_vars_template", cmd);
});
- let marker_file = repo.root_path().join("lazy_filtered.txt");
+ let marker_file = repo.root_path().join("vars_filtered.txt");
wait_for_file_content(&marker_file);
let content = fs::read_to_string(&marker_file).unwrap().trim().to_string();
assert_eq!(
content, "test-db",
- "Lazy template should expand {{ vars.name }} from git config"
+ "Template should expand {{ vars.name }} from git config"
);
}
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_verbose_output.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_verbose_output.snap
index 80b120d73..48b7fac53 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_verbose_output.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_verbose_output.snap
@@ -31,7 +31,6 @@ info:
OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
PATH: "[PATH]"
PSModulePath: ""
- RUST_LOG: warn
SHELL: ""
TERM: alacritty
USERPROFILE: "[TEST_HOME]"
@@ -66,10 +65,6 @@ exit_code: 0
↳ To customize worktree locations, run wt config create
▲ Cannot change directory — shell integration not installed
↳ To enable automatic cd, run wt config shell install
-○ Expanding project:setup
-  echo 'verbose test' > verbose.txt
-  →
-  echo 'verbose test' > verbose.txt
○ template variables:
  branch = feature
  worktree_path = _REPO_.feature
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__combined_post_remove_and_post_switch_verbose.snap b/tests/snapshots/integration__integration_tests__user_hooks__combined_post_remove_and_post_switch_verbose.snap
index 91a8f069c..886265e2f 100644
--- a/tests/snapshots/integration__integration_tests__user_hooks__combined_post_remove_and_post_switch_verbose.snap
+++ b/tests/snapshots/integration__integration_tests__user_hooks__combined_post_remove_and_post_switch_verbose.snap
@@ -13,32 +13,43 @@ info:
COLUMNS: "500"
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMON_DIR: ""
GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
GIT_CONFIG_SYSTEM: /dev/null
+ GIT_DIR: ""
GIT_EDITOR: ""
+ GIT_INDEX_FILE: ""
+ GIT_OBJECT_DIRECTORY: ""
GIT_TERMINAL_PROMPT: "0"
+ GIT_WORK_TREE: ""
HOME: "[TEST_HOME]"
LANG: C
LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
NO_COLOR: ""
OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
PATH: "[PATH]"
PSModulePath: ""
- RUST_LOG: warn
SHELL: ""
TERM: alacritty
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
---
success: true
@@ -53,14 +64,6 @@ exit_code: 0
◎ Removing feature worktree & branch in background (--force-delete)
▲ Cannot change directory — shell integration not installed
↳ To enable automatic cd, run wt config shell install
-○ Expanding user:cleanup
-  echo removed
-  →
-  echo removed
-○ Expanding user:notify
-  echo switched
-  →
-  echo switched
○ template variables:
  branch = feature
  worktree_path = _REPO_.feature
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__foreground_pipeline_undefined_var_runs_earlier_steps.snap b/tests/snapshots/integration__integration_tests__user_hooks__foreground_pipeline_undefined_var_runs_earlier_steps.snap
new file mode 100644
index 000000000..e938c31a3
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__foreground_pipeline_undefined_var_runs_earlier_steps.snap
@@ -0,0 +1,46 @@
+---
+source: tests/integration_tests/user_hooks.rs
+info:
+ program: wt
+ args:
+ - hook
+ - pre-merge
+ - "--yes"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
+ NO_COLOR: ""
+ PSModulePath: ""
+ SHELL: ""
+ TERM: alacritty
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+◎ Running pre-merge user:first
+  echo FIRST_RAN > first_marker.txt
+✗ Failed to expand user:broken: undefined value @ line 1
+  echo {{ does_not_exist }}
+↳ Available variables: args, branch, commit, cwd, default_branch, hook_name, hook_type, main_worktree, main_worktree_path, primary_worktree_path, remote, remote_url, repo, repo_path, repo_root, short_commit, target, target_worktree_path, upstream, worktree, worktree_name, worktree_path
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__hook_verbose_background_dedup.snap b/tests/snapshots/integration__integration_tests__user_hooks__hook_verbose_background_dedup.snap
index dd8280839..253723391 100644
--- a/tests/snapshots/integration__integration_tests__user_hooks__hook_verbose_background_dedup.snap
+++ b/tests/snapshots/integration__integration_tests__user_hooks__hook_verbose_background_dedup.snap
@@ -31,7 +31,6 @@ info:
OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
PATH: "[PATH]"
PSModulePath: ""
- RUST_LOG: warn
SHELL: ""
TERM: alacritty
USERPROFILE: "[TEST_HOME]"
@@ -66,14 +65,6 @@ exit_code: 0
↳ To customize worktree locations, run wt config create
▲ Cannot change directory — shell integration not installed
↳ To enable automatic cd, run wt config shell install
-○ Expanding user post-start hook
-  echo user-hook
-  →
-  echo user-hook
-○ Expanding project post-start hook
-  echo project-hook
-  →
-  echo project-hook
○ template variables:
  branch = feature
  worktree_path = _REPO_.feature
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_name_filtered_lazy_template.snap b/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_name_filtered_vars_template.snap
similarity index 100%
rename from tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_name_filtered_lazy_template.snap
rename to tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_name_filtered_vars_template.snap