Repository navigation
feat: lazy template expansion for pipeline vars - #1840
Merged
Merged
Conversation
Pipeline steps referencing `{{ vars.* }}` are now expanded at execution
time rather than upfront, so vars set by step N are available to step N+1.
Background pipelines wrap lazy steps in
`eval "$(wt step eval --shell-escape "$__WT_TPL_N")"` with templates
passed as env vars. Foreground mode re-expands in-process for structured
error reporting.
Extracts `template_references_var()` as shared helper for
minijinja-based variable detection. Updates database examples in docs
to use the pipeline pattern.
Co-Authored-By: Claude <[email protected]>
worktrunk-bot
left a comment
Collaborator
There was a problem hiding this comment.
Two minor issues, otherwise this looks good — clean design, correct separation of foreground/background lazy paths, solid test coverage.
| /// | ||
| /// Uses minijinja's AST analysis rather than string matching, avoiding false | ||
| /// positives from literal text like `template_vars.txt`. | ||
| pub fn template_references_var(template: &str, var: &str) -> bool { |
Collaborator
There was a problem hiding this comment.
The doc comment for template_references_var accidentally absorbs the doc comment that belongs to validate_template below. Rustdoc will render lines 339–357 as the docs for this function, and validate_template ends up undocumented.
Suggested change
| pub fn template_references_var(template: &str, var: &str) -> bool { | |
| pub fn template_references_var(template: &str, var: &str) -> bool { |
Move lines 339–352 (the validate_template doc) down to above pub fn validate_template, leaving only lines 354–357 here.
The foreground lazy test was using table format `[post-start]` which doesn't trigger lazy expansion. Switch to pipeline format so the test exercises the actual lazy path. Delete orphaned snapshot from earlier test rename. Co-Authored-By: Claude <[email protected]>
The hook subprocess doesn't have the test binary on PATH in CI. Use `git config` directly to set the var instead of `wt config state vars set`. Co-Authored-By: Claude <[email protected]>
max-sixty
added a commit
that referenced
this pull request
Apr 1, 2026
The background path for lazy template expansion (via `wt switch --create`) was broken by two bugs from PR #1840: 1. Raw string literal bug in `format_cmd()` — `r#"..."#` consumed the closing `"` of the shell command, producing `eval "$(wt step eval --shell-escape "$__WT_TPL_0)` instead of the properly quoted `eval "$(wt step eval --shell-escape "$__WT_TPL_0")"`. 2. `validate_switch_templates()` eagerly failed on `{{ vars.name }}` templates — it renders with an empty `vars` map, but these templates are lazily expanded at runtime after prior pipeline steps set the vars. Also adds the missing integration test for the background lazy vars path and strengthens unit test assertions to catch the quoting regression. Co-Authored-By: Claude <[email protected]>
max-sixty
added a commit
that referenced
this pull request
Apr 1, 2026
Two bugs from #1840 broke the background path for lazy template expansion (via `wt switch --create`): 1. **Raw string literal bug in `format_cmd()`** — `r#"..."#` consumed the closing `"` of the shell command, producing `eval "$(wt step eval --shell-escape "$__WT_TPL_0)` (missing closing quotes). The `"#` terminator matched the `"` that was supposed to be part of the output. Fixed by doubling the `"` before `"#`. 2. **`validate_switch_templates()` eagerly failed on `{{ vars.name }}`** — pre-flight validation renders templates with `vars` as an empty map, so accessing `vars.name` errors under SemiStrict mode. But these templates are lazily expanded at runtime after prior pipeline steps set the vars. Fixed by skipping full validation for templates that reference `vars.` (syntax is still checked by `expand_commands`). Also adds the missing integration test for the background lazy vars path and strengthens unit test assertions to catch the quoting regression. > _This was written by Claude Code on behalf of @max-sixty_ Co-authored-by: Claude <[email protected]>
1 of 2 tasks
max-sixty
added a commit
that referenced
this pull request
Apr 1, 2026
Pipeline steps referencing `{{ vars.* }}` are expanded at execution time
rather than upfront, so vars set by step N are available to step N+1.
This enables DRY patterns like deriving a container name once and
reusing it across pipeline steps and across hooks
(post-start/post-remove).
A pipeline that sets vars in step 1 and uses them in step 2:
```toml
post-start = [
"wt config state vars set container='{{ repo }}-{{ branch | sanitize }}-postgres'",
{ db = "docker run --name {{ vars.container }} ..." },
]
[post-remove]
db-stop = "docker stop {{ vars.container }} 2>/dev/null || true"
```
**Background pipelines** wrap lazy steps in `eval "$(wt step eval
--shell-escape "$__WT_TPL_N")"` with templates passed as env vars on the
spawned process. **Foreground mode** (`--foreground`) re-expands
templates in-process for structured error reporting.
Detection uses `minijinja::undeclared_variables` (via new shared
`template_references_var()` helper) — no string heuristics. Syntax
errors are caught at prepare time; only var resolution is deferred.
`--shell-escape` on `wt step eval` is hidden from `--help` (internal
mechanism).
Updates database examples in hook docs and tips-patterns to use the
pipeline pattern.
> _This was written by Claude Code on behalf of @max-sixty_
---------
Co-authored-by: Claude <[email protected]>
max-sixty
added a commit
that referenced
this pull request
Jun 11, 2026
…#3042) Hook templates expanded eagerly at prep time unless they referenced `vars.*` (#1840); aliases were unconditionally lazy. The dual representation (`expanded` + `lazy_template` on `PreparedCommand`) put a mode choice in front of every consumer, and the seams produced real bugs (#1855, #1910). The background runner also re-rendered eagerly-expanded strings: a latent double-expansion whenever expansion output contained `{{`. This PR unifies on one rule: syntax is validated at preparation (before step 1), templates render when each step runs, and `vars.*` always reads fresh from git config. This is the direction #2128 recorded ("treat hooks as aliases bound to triggers"). **Navigating the diff:** - `src/commands/command_executor.rs`: `PreparedCommand` now carries the raw template plus the frozen context map; JSON is produced only at the process boundary. A `template_name` field keeps the moved errors' text identical to the old prep-time messages. `prepare_steps` validates syntax and freezes context; `resolve_command_str` renders at execution; `map_config_steps` is the structural walker shared with aliases. - `src/commands/alias.rs`: alias prep shares the walker. The residual fork is genuinely alias-specific: context construction (filtered to referenced vars, `{{ args }}` injection) and labels. A prep-time syntax check turned out to be dead code (the arg-routing parse already aborts on syntax errors), so `referenced_vars_for_config` now produces the rich `TemplateExpandError` instead. - `src/commands/hooks.rs`: the background spec always ships raw templates; the runner renders each step (it already did for vars steps). - Dry-run paths (`wt hook --dry-run`, `wt config alias dry-run`) share `render_template_preview`: vars-referencing templates shown raw after a syntax check, everything else rendered at display time. **Behavior changes** (each pinned by a test or snapshot): 1. A foreground pipeline whose step N has a semantic template error (undefined variable) runs steps 1..N-1 before failing, matching what vars-referencing steps already did. New test: `test_foreground_pipeline_undefined_var_runs_earlier_steps`. 2. A semantic error in a background hook template no longer fails the foreground command; it surfaces in the runner log. Syntax errors still abort at prep. New test: `test_background_hook_undefined_var_fails_in_runner`; `test_merge_drops_pending_hooks_when_post_merge_fails` switched to a syntax-error fixture since that is what now reaches its subject (the announcer Drop-flush). 3. `-v` no longer prints the parent-side rendered command for background hooks (rendering happens in the runner). The variables table remains and `wt hook <type> --dry-run` previews commands; help text updated. Three snapshots changed by exactly this. 4. Announce gutters for vars-referencing foreground steps show the rendered command instead of the raw template. 5. Syntax errors caught by the arg-routing parse (aliases, `wt hook` `--KEY=VALUE` routing) render as the rich template error with the source-line gutter, naming the alias or hook. `ApprovedHookPlan` freezing, approval semantics (keyed and displayed by template), config file format, and CLI flags are unchanged. **Testing:** full local gate green (3917 tests + lints). The deferral semantics in changes 1 and 2 previously had no coverage; both are now pinned. > _This was written by Claude Code on behalf of max_ Co-authored-by: Claude Fable 5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Pipeline steps referencing
{{ vars.* }}are expanded at execution time rather than upfront, so vars set by step N are available to step N+1. This enables DRY patterns like deriving a container name once and reusing it across pipeline steps and across hooks (post-start/post-remove).A pipeline that sets vars in step 1 and uses them in step 2:
Background pipelines wrap lazy steps in
eval "$(wt step eval --shell-escape "$__WT_TPL_N")"with templates passed as env vars on the spawned process. Foreground mode (--foreground) re-expands templates in-process for structured error reporting.Detection uses
minijinja::undeclared_variables(via new sharedtemplate_references_var()helper) — no string heuristics. Syntax errors are caught at prepare time; only var resolution is deferred.--shell-escapeonwt step evalis hidden from--help(internal mechanism).Updates database examples in hook docs and tips-patterns to use the pipeline pattern.