Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: background lazy pipeline vars expansion (#1855)
Maximilian Roos346e27431f08
diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rsindex 4bccca2e3..870fc3477 100644--- a/src/commands/handle_switch.rs+++ b/src/commands/handle_switch.rs@@ -5,7 +5,7 @@ use std::path::Path;use anyhow::Context;use worktrunk::HookType;-use worktrunk::config::{UserConfig, expand_template, validate_template};+use worktrunk::config::{UserConfig, expand_template, template_references_var, validate_template};use worktrunk::git::{GitError, Repository, SwitchSuggestionCtx, current_or_recover};use worktrunk::styling::{eprintln, info_message};@@ -482,6 +482,12 @@ 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.+ if template_references_var(&cmd.template, "vars") {+ continue;+ }let name = match &cmd.name {Some(n) => format!("{source} {hook_type}:{n}"),None => format!("{source} {hook_type} hook"),diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex daac79a9b..130c06fbe 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -325,7 +325,7 @@ fn format_cmd(cmd: &PreparedCommand, wt_bin: &str, env_vars: &mut Vec<(String, SSome(template) => {let var_name = format!("__WT_TPL_{}", env_vars.len());env_vars.push((var_name.clone(), template.clone()));- format!(r#"eval "$({wt_bin} step eval --shell-escape "${var_name}")"#)+ format!(r#"eval "$({wt_bin} step eval --shell-escape "${var_name}")""#)}None => cmd.expanded.clone(),}@@ -898,18 +898,15 @@ mod tests {];let (cmd, env) = build_pipeline_command(&steps);- // Lazy step uses eval wrapping with env var reference+ // Lazy step uses eval wrapping with properly quoted env var reference.+ // The closing ")" must be outside $() — a missing " produces broken shell.assert!(cmd.contains("eval \"$("),"should contain eval wrapping: {cmd}");assert!(- cmd.contains("step eval --shell-escape"),- "should reference step eval: {cmd}"- );- assert!(- cmd.contains("$__WT_TPL_0"),- "should reference env var: {cmd}"+ cmd.contains("\"$__WT_TPL_0\")\""),+ "should close with proper quoting (var quote, paren, outer quote): {cmd}");// Env var contains the raw template@@ -934,7 +931,10 @@ mod tests {// Concurrent group has one lazy and one eagerassert!(cmd.contains("npm run lint"), "eager concurrent cmd: {cmd}");- assert!(cmd.contains("$__WT_TPL_0"), "lazy concurrent cmd: {cmd}");+ assert!(+ cmd.contains("\"$__WT_TPL_0\")\""),+ "lazy concurrent cmd should have proper quoting: {cmd}"+ );// Only one env var (for the lazy command)assert_eq!(env.len(), 1);@@ -954,11 +954,19 @@ mod tests {"echo {{ vars.b }}",))),];- let (_, env) = build_pipeline_command(&steps);+ let (cmd, env) = build_pipeline_command(&steps);- // Each lazy step gets its own numbered env var+ // Each lazy step gets its own numbered env var with proper quotingassert_eq!(env.len(), 2);assert_eq!(env[0].0, "__WT_TPL_0");assert_eq!(env[1].0, "__WT_TPL_1");+ assert!(+ cmd.contains("\"$__WT_TPL_0\")\""),+ "first lazy step should have proper quoting: {cmd}"+ );+ assert!(+ cmd.contains("\"$__WT_TPL_1\")\""),+ "second lazy step should have proper quoting: {cmd}"+ );}}diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex a6452c385..089ac22fb 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -2407,3 +2407,36 @@ fn test_user_post_start_pipeline_lazy_vars_foreground(repo: TestRepo) {"Lazy step should see var set by prior step");}++#[rstest]+fn test_user_post_start_pipeline_lazy_vars_background(repo: TestRepo) {+ // Pipeline step 1 sets a var via git config (not `wt config` — bare `wt`+ // isn't on PATH in the detached background shell). Step 2 references+ // {{ vars.name }}, which triggers the lazy expansion path where+ // build_pipeline_command() wraps it in+ // eval "$(path/to/wt step eval --shell-escape ...)"+ // The absolute binary path comes from std::env::current_exe().+ repo.write_test_config(+ r#"post-start = [+ "git config worktrunk.state.{{ branch }}.vars.name '{{ branch | sanitize }}-postgres'",+ { db = "echo {{ vars.name }} > lazy_bg_expanded.txt" }+]+"#,+ );++ snapshot_switch(+ "user_post_start_pipeline_lazy_vars_bg",+ &repo,+ &["--create", "feature"],+ );++ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");+ let marker_file = worktree_path.join("lazy_bg_expanded.txt");+ wait_for_file_content(&marker_file);++ let content = fs::read_to_string(&marker_file).unwrap().trim().to_string();+ assert_eq!(+ content, "feature-postgres",+ "Background lazy step should see var set by prior step"+ );+}diff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_post_start_pipeline_lazy_vars_bg.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_post_start_pipeline_lazy_vars_bg.snapnew file mode 100644index 000000000..6ea25cb95--- /dev/null+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_post_start_pipeline_lazy_vars_bg.snap@@ -0,0 +1,50 @@+---+source: tests/integration_tests/user_hooks.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - feature+ 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: ""+ 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_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[32m✓[39m [32mCreated branch [1mfeature[22m from [1mmain[22m and worktree @ [1m_REPO_.feature[22m[39m+[2m↳[22m [2mTo customize worktree locations, run [4mwt config create[24m[22m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [4mwt config shell install[24m[22m+[36m◎[39m [36mRunning post-start: [1mcmd-0[22m → [1mdb[22m @ [1m_REPO_.feature[22m[39m