Skip to content

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

fix(alias): make `wt step <alias> --dry-run` match lazy-expansion runtime (#2170)

Maximilian Roos5da43d199468
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index 1100676a5..ed81c9b14 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -30,11 +30,14 @@
//! the EXEC directive file is scrubbed so alias bodies cannot inject
//! arbitrary shell into the interactive session.
-use std::collections::BTreeMap;
+use std::collections::{BTreeMap, HashMap};
use anyhow::{Context, bail};
use color_print::cformat;
-use worktrunk::config::{CommandConfig, HookStep, ProjectConfig, UserConfig, append_aliases};
+use worktrunk::config::{
+ CommandConfig, HookStep, ProjectConfig, UserConfig, append_aliases, template_references_var,
+ validate_template_syntax,
+};
use worktrunk::git::Repository;
use worktrunk::styling::{
eprintln, format_bash_with_gutter, info_message, progress_message, warning_message,
@@ -318,8 +321,8 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {
if opts.dry_run {
let expanded: Vec<_> = cmd_config
.commands()
- .map(|cmd| expand_shell_template(&cmd.template, &context_map, &repo, &opts.name))
- .collect::<Result<_, _>>()?;
+ .map(|cmd| render_for_dry_run(&cmd.template, &context_map, &repo, &opts.name))
+ .collect::<anyhow::Result<_>>()?;
eprintln!(
"{}",
info_message(cformat!(
@@ -380,6 +383,30 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {
)
}
+/// Render a command template for `--dry-run` display.
+///
+/// Mirrors execution-time lazy semantics: templates referencing `vars.*` may
+/// read values set by earlier pipeline steps via git config, and at dry-run
+/// time those values haven't been written yet (even if git config happens to
+/// hold a stale value from a previous run, the execution path would overwrite
+/// it). For those templates, syntax-validate (catching typos like
+/// `{{ vars..foo }}`) and show the raw template. Other templates expand
+/// eagerly against the initial context just like before.
+fn render_for_dry_run(
+ 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)?)
+ }
+}
+
/// Build a PreparedCommand for an alias, deferring template expansion to execution time.
fn alias_prepared_command(cmd: &worktrunk::config::Command, context_json: &str) -> PreparedCommand {
PreparedCommand {
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 7bfd66687..09d770267 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -6,6 +6,7 @@ use color_print::cformat;
use worktrunk::HookType;
use worktrunk::config::{
Command, CommandConfig, HookStep, UserConfig, expand_template, template_references_var,
+ validate_template_syntax,
};
use worktrunk::git::{Repository, WorktrunkError};
use worktrunk::path::{format_path_for_display, to_posix_path};
@@ -593,8 +594,7 @@ fn expand_commands(
// 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.
- let env = minijinja::Environment::new();
- env.template_from_named_str(&template_name, &cmd.template)
+ 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))
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 5fabd788d..7873e6126 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -352,6 +352,17 @@ pub fn template_references_var(template: &str, var: &str) -> bool {
tmpl.undeclared_variables(false).contains(var)
}
+/// 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> {
+ minijinja::Environment::new()
+ .template_from_named_str(name, template)
+ .map(|_| ())
+}
+
/// Validate that a template can be expanded without errors.
///
/// Performs a trial expansion with placeholder values for all known template variables
diff --git a/src/config/mod.rs b/src/config/mod.rs
index bad3f030c..7449176d8 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -116,7 +116,7 @@ pub use deprecation::{
pub use expansion::{
DEPRECATED_TEMPLATE_VARS, TEMPLATE_VARS, TemplateExpandError, expand_template,
redact_credentials, sanitize_branch_name, sanitize_db, short_hash, template_references_var,
- validate_template,
+ validate_template, validate_template_syntax,
};
pub use hooks::HooksConfig;
pub use project::{
diff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rs
index 22fc1bdea..3910cb55a 100644
--- a/tests/integration_tests/step_alias.rs
+++ b/tests/integration_tests/step_alias.rs
@@ -988,6 +988,67 @@ deploy = [
);
}
+/// `--dry-run` for a pipeline where a later step references `{{ vars.X }}`
+/// set by an earlier step succeeds, mirroring the lazy execution path. The
+/// unresolved `vars.*` reference is shown as the raw template since its value
+/// isn't knowable until the earlier step actually runs.
+#[rstest]
+fn test_step_alias_dry_run_vars_across_steps(mut repo: TestRepo) {
+ repo.write_project_config(
+ r#"
+[aliases]
+deploy = [
+ "git config worktrunk.state.main.vars.target 'prod'",
+ { publish = "echo deploying to {{ vars.target }}" },
+]
+"#,
+ );
+ repo.commit("Add alias config");
+ let feature_path = repo.add_worktree("feature");
+
+ let settings = setup_snapshot_settings(&repo);
+ let _guard = settings.bind_to_scope();
+
+ // Must succeed: dry-run must not require vars.* to be resolvable.
+ // --yes bypasses approval for project-config aliases.
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "step",
+ &["deploy", "--dry-run", "--yes"],
+ Some(&feature_path),
+ ));
+}
+
+/// `--dry-run` still catches template syntax errors (e.g., `{{ vars..foo }}`)
+/// even on the lazy path where `vars.*` rendering is skipped.
+#[rstest]
+fn test_step_alias_dry_run_catches_syntax_error(mut repo: TestRepo) {
+ repo.write_project_config(
+ r#"
+[aliases]
+broken = "echo {{ vars..target }}"
+"#,
+ );
+ repo.commit("Add alias config");
+ let feature_path = repo.add_worktree("feature");
+
+ let output = repo
+ .wt_command()
+ .args(["step", "broken", "--dry-run", "--yes"])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ !output.status.success(),
+ "dry-run should fail on syntax error; stderr:\n{stderr}"
+ );
+ assert!(
+ stderr.contains("syntax error"),
+ "expected 'syntax error' in stderr, got:\n{stderr}"
+ );
+}
+
/// `wt step` with no subcommand lists built-in steps plus configured aliases.
///
/// Skipped on Windows: clap renders `[experimental]` subcommand tags
diff --git a/tests/snapshots/integration__integration_tests__step_alias__step_alias_dry_run_vars_across_steps.snap b/tests/snapshots/integration__integration_tests__step_alias__step_alias_dry_run_vars_across_steps.snap
new file mode 100644
index 000000000..bc8ec58c2
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_alias__step_alias_dry_run_vars_across_steps.snap
@@ -0,0 +1,51 @@
+---
+source: tests/integration_tests/step_alias.rs
+info:
+ program: wt
+ args:
+ - step
+ - deploy
+ - "--dry-run"
+ - "--yes"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ 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_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+○ Alias deploy would run:
+  git config worktrunk.state.main.vars.target 'prod'
+  echo deploying to {{ vars.target }}