Skip to content

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

perf(switch): compute only the template vars --execute names, and give the context a type (#3628)

Maximilian Roos835d5f0cc137
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index a321ff8c0..cbd374f02 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -48,7 +48,7 @@ use std::collections::{BTreeMap, BTreeSet};
use anyhow::{Context, bail};
use color_print::cformat;
use worktrunk::config::{
- ALIAS_ARGS_KEY, CommandConfig, ProjectConfig, UserConfig, alias_context_filter,
+ ALIAS_ARGS_KEY, CommandConfig, ProjectConfig, UserConfig, VarScope, alias_context_filter,
format_alias_variables, referenced_vars_for_config,
};
use worktrunk::git::Repository;
@@ -605,19 +605,19 @@ fn run_alias(
let referenced = alias_context_filter(referenced);
let mut context_map = {
let _span = Span::new("build_hook_context");
- build_hook_context(&ctx, &extra_refs, Some(&referenced))?
+ build_hook_context(&ctx, &extra_refs, VarScope::Referenced(&referenced))?
};
// Forward positional CLI args to templates as `{{ args }}`. Encoded as a
- // JSON list so it flows through the stable `HashMap<String, String>`
- // context — `expand_template` rehydrates it into a `ShellArgs` sequence.
+ // JSON list so it flows through the context's flat string map —
+ // `expand_template` rehydrates it into a `ShellArgs` sequence.
context_map.insert(
- ALIAS_ARGS_KEY.to_string(),
+ ALIAS_ARGS_KEY,
serde_json::to_string(&opts.positional_args)
.expect("Vec<String> serialization should never fail"),
);
if verbosity() >= 1 {
- let vars = format_alias_variables(&context_map, Some(&referenced));
+ let vars = format_alias_variables(&context_map, VarScope::Referenced(&referenced));
eprintln!(
"{}",
info_message(cformat!("<bold>{}</> template variables:", opts.name))
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 16eb66108..c936f6499 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -1,11 +1,11 @@
-use std::collections::{BTreeSet, HashMap};
+use std::collections::HashMap;
use std::path::{Path, PathBuf};
use anyhow::Result;
use color_print::cformat;
use worktrunk::HookType;
use worktrunk::config::{
- Command, CommandConfig, HookStep, UserConfig, expand_template, format_hook_variables,
+ Command, CommandConfig, HookStep, TemplateContext, UserConfig, VarScope, format_hook_variables,
template_references_var, validate_template_syntax,
};
use worktrunk::git::{ErrorExt, Repository, WorktrunkError};
@@ -31,7 +31,7 @@ pub struct PreparedCommand {
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>,
+ pub context: TemplateContext,
/// Name used in template expansion errors: `"user:foo"` for named hook
/// commands, `"user pre-merge hook"` for unnamed ones, the alias name for
/// aliases.
@@ -44,8 +44,7 @@ pub struct PreparedCommand {
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")
+ self.context.to_json()
}
}
@@ -218,25 +217,37 @@ impl<'a> CommandContext<'a> {
}
}
-/// Build hook context as a HashMap for JSON serialization and template expansion.
+/// Resolve the template variables for one command invocation.
///
-/// The resulting HashMap is passed to hook commands as JSON on stdin,
-/// and used directly for template variable expansion.
+/// The sole producer of [`TemplateContext`], which owns what happens to the
+/// result: expansion, the JSON a hook child reads on stdin, the `-v` table.
///
-/// `referenced`, when `Some`, restricts the map to keys named in the set —
-/// vars the body doesn't reference are not computed. Aliases pass their
-/// `referenced_vars_for_config` set (extended via `alias_context_filter`)
-/// so unused git lookups (`var_commit` rev-parse, `var_default_branch` cold
-/// detection, `branch().upstream()`) are skipped, and the verbose
-/// `template variables:` table only lists vars the body actually references.
-/// Hooks pass `None` so every standard var stays available — the child
-/// receives the full context as JSON on stdin and may consume keys that
-/// don't appear in the inline `{{ }}` template (e.g. via `jq`).
+/// `scope` decides how much to resolve. [`VarScope::Referenced`] skips the git
+/// lookups behind vars the templates don't name (`var_commit` rev-parse,
+/// `var_default_branch` cold detection, `branch().upstream()`), and follows
+/// from who reads the finished context, not from what kind of command is
+/// running:
+///
+/// - **`Referenced`** when only the templates read it. A var they don't name
+/// would be computed and discarded. Aliases pass `referenced_vars_for_config`
+/// (extended via `alias_context_filter`); `wt switch --execute` passes
+/// `referenced_vars_for_templates` over its command and trailing args.
+/// - **`All`** when something reads keys the `{{ }}` templates never mention.
+/// Either the child receives the whole context as JSON on stdin and may pull
+/// keys out of it (e.g. via `jq`) — hook pipelines, `wt step for-each` — or
+/// the command's output *is* the variable listing, which filtering would
+/// narrow to what the body happens to reference: `wt step eval -v`, and the
+/// hook pipeline's own `format_hook_variables` table.
+///
+/// The template-preview paths (`render_hook_commands`, `wt config alias`) fit
+/// neither case and still pass `All`: they expand and print one line per
+/// configured command, so filtering would be correct but saves nothing an
+/// interactive display would notice.
pub fn build_hook_context(
ctx: &CommandContext<'_>,
extra_vars: &[(&str, &str)],
- referenced: Option<&BTreeSet<String>>,
-) -> Result<HashMap<String, String>> {
+ scope: VarScope<'_>,
+) -> Result<TemplateContext> {
let repo_root = ctx.repo.repo_path()?;
let repo_name = repo_root
.file_name()
@@ -254,12 +265,10 @@ pub fn build_hook_context(
let repo_path = to_posix_path(&repo_root.to_string_lossy());
- let want = |key: &str| referenced.is_none_or(|r| r.contains(key));
-
// Cheap vars (already in scope, no I/O) are populated unconditionally —
// skipping them saves no work and would just turn the verbose table's
// `(unused)` label into noise. Only the expensive blocks below
- // (subprocesses, git config / remote lookups) honor `want`.
+ // (subprocesses, git config / remote lookups) consult `scope`.
let mut map = HashMap::new();
map.insert("repo".into(), repo_name.into());
map.insert("branch".into(), ctx.branch_or_head().into());
@@ -276,7 +285,7 @@ pub fn build_hook_context(
}
// Default branch
- if want("default_branch") {
+ if scope.wants("default_branch") {
let _span = Span::new("var_default_branch");
if let Some(default_branch) = ctx.repo.default_branch() {
map.insert("default_branch".into(), default_branch);
@@ -284,15 +293,15 @@ pub fn build_hook_context(
}
// Primary worktree path (where established files live)
- if want("primary_worktree_path") || want("main_worktree_path") {
+ if scope.wants("primary_worktree_path") || scope.wants("main_worktree_path") {
let _span = Span::new("var_primary_worktree");
if let Ok(Some(path)) = ctx.repo.primary_worktree() {
let path_str = to_posix_path(&path.to_string_lossy());
- if want("primary_worktree_path") {
+ if scope.wants("primary_worktree_path") {
map.insert("primary_worktree_path".into(), path_str.clone());
}
// Deprecated alias
- if want("main_worktree_path") {
+ if scope.wants("main_worktree_path") {
map.insert("main_worktree_path".into(), path_str);
}
}
@@ -306,7 +315,7 @@ pub fn build_hook_context(
// iterates over sibling worktrees, and a sibling on detached HEAD has a
// different HEAD than the worktree `wt` runs in. Branched contexts go
// through `rev-parse <branch>`, which is repo-wide.
- if want("commit") || want("short_commit") {
+ if scope.wants("commit") || scope.wants("short_commit") {
let _span = Span::new("var_commit");
let commit = match ctx.branch {
Some(branch) => ctx
@@ -322,30 +331,30 @@ pub fn build_hook_context(
.flatten(),
};
if let Some(commit) = commit {
- if want("short_commit")
+ if scope.wants("short_commit")
&& let Ok(short) = ctx.repo.short_sha(&commit)
{
map.insert("short_commit".into(), short);
}
- if want("commit") {
+ if scope.wants("commit") {
map.insert("commit".into(), commit);
}
}
}
- if want("remote") || want("remote_url") || want("upstream") {
+ if scope.wants("remote") || scope.wants("remote_url") || scope.wants("upstream") {
let _span = Span::new("var_remote");
if let Ok(remote) = ctx.repo.primary_remote() {
- if want("remote") {
+ if scope.wants("remote") {
map.insert("remote".into(), remote.to_string());
}
// Add remote URL for conditional hook execution (e.g., GitLab vs GitHub)
- if want("remote_url")
+ if scope.wants("remote_url")
&& let Some(url) = ctx.repo.remote_url(&remote)
{
map.insert("remote_url".into(), url);
}
- if want("upstream")
+ if scope.wants("upstream")
&& let Some(branch) = ctx.branch
&& let Ok(Some(upstream)) = ctx.repo.branch(branch).upstream()
{
@@ -368,7 +377,7 @@ pub fn build_hook_context(
map.insert((*k).into(), (*v).into());
}
- Ok(map)
+ Ok(TemplateContext::from_vars(map))
}
/// Drain a sequence of command results, returning the first error.
@@ -392,10 +401,9 @@ pub fn wait_first_error<E>(
first.map_or(Ok(()), Err)
}
-/// Expand a shell-command template against a context map.
+/// Expand a shell-command template against a context.
///
-/// Builds the `&str` vars map required by `expand_template` and fixes
-/// [`ShellEscapeMode::Posix`]: every caller (foreground hooks, background
+/// Fixes [`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. Every
@@ -403,21 +411,11 @@ pub fn wait_first_error<E>(
/// set `vars.*` via git config.
pub fn expand_shell_template(
template: &str,
- context: &HashMap<String, String>,
+ context: &TemplateContext,
repo: &Repository,
label: &str,
) -> Result<String> {
- let vars: HashMap<&str, &str> = context
- .iter()
- .map(|(k, v)| (k.as_str(), v.as_str()))
- .collect();
- Ok(expand_template(
- template,
- &vars,
- ShellEscapeMode::Posix,
- repo,
- label,
- )?)
+ Ok(context.expand(template, ShellEscapeMode::Posix, repo, label)?)
}
/// Resolve the shell string to execute for a prepared command.
@@ -436,7 +434,7 @@ fn resolve_command_str(cmd: &PreparedCommand, repo: &Repository) -> Result<Strin
/// real run.
pub fn render_template_preview(
template: &str,
- context: &HashMap<String, String>,
+ context: &TemplateContext,
repo: &Repository,
name: &str,
) -> Result<String> {
@@ -745,24 +743,27 @@ pub fn prepare_steps(
source: HookSource,
) -> 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)?;
+ let mut base_context = build_hook_context(ctx, extra_vars, VarScope::All)?;
// hook_type is always available as a template variable and in JSON context
- base_context.insert("hook_type".into(), hook_type.to_string());
+ base_context.insert("hook_type", 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());
+ if base_context
+ .get(worktrunk::config::ALIAS_ARGS_KEY)
+ .is_none()
+ {
+ base_context.insert(worktrunk::config::ALIAS_ARGS_KEY, "[]");
+ }
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 {
- cmd_context.insert("hook_name".into(), name.clone());
+ cmd_context.insert("hook_name", name.clone());
}
let template_name = match &cmd.name {
@@ -790,7 +791,7 @@ mod tests {
PreparedCommand {
name: name.map(String::from),
template: "echo test".to_string(),
- context: HashMap::new(),
+ context: TemplateContext::default(),
template_name: label.clone(),
label,
}
diff --git a/src/commands/config/alias.rs b/src/commands/config/alias.rs
index 945bf2440..edad53df2 100644
--- a/src/commands/config/alias.rs
+++ b/src/commands/config/alias.rs
@@ -26,7 +26,7 @@ use std::io::Write;
use anyhow::Context;
use color_print::cformat;
use worktrunk::config::{
- ALIAS_ARGS_KEY, CommandConfig, ProjectConfig, UserConfig, referenced_vars_for_config,
+ ALIAS_ARGS_KEY, CommandConfig, ProjectConfig, UserConfig, VarScope, referenced_vars_for_config,
};
use worktrunk::git::{Repository, WorktrunkError};
use worktrunk::styling::{format_bash_with_gutter, info_message, println};
@@ -185,9 +185,9 @@ pub fn handle_alias_dry_run(name: String, args: Vec<String>) -> anyhow::Result<(
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
- let mut context_map = build_hook_context(&ctx, &extra_refs, None)?;
+ let mut context_map = build_hook_context(&ctx, &extra_refs, VarScope::All)?;
context_map.insert(
- ALIAS_ARGS_KEY.to_string(),
+ ALIAS_ARGS_KEY,
serde_json::to_string(&opts.positional_args)
.expect("Vec<String> serialization should never fail"),
);
diff --git a/src/commands/eval.rs b/src/commands/eval.rs
index fb3fbd8c8..5981b84c5 100644
--- a/src/commands/eval.rs
+++ b/src/commands/eval.rs
@@ -3,10 +3,8 @@
//! Evaluates a template expression in the current worktree context and prints
//! the result to stdout.
-use std::collections::HashMap;
-
use color_print::cformat;
-use worktrunk::config::{UserConfig, expand_template, format_base_variables};
+use worktrunk::config::{UserConfig, VarScope, format_base_variables};
use worktrunk::git::Repository;
use worktrunk::shell_exec::ShellEscapeMode;
use worktrunk::styling::{eprintln, format_with_gutter, info_message, println, verbosity};
@@ -37,7 +35,7 @@ pub fn step_eval(template: &str, format: SwitchFormat) -> anyhow::Result<()> {
let worktree_path = wt.root()?;
let ctx = CommandContext::new(&repo, &config, branch.as_deref(), &worktree_path, false);
- let context_map = build_hook_context(&ctx, &[], None)?;
+ let context_map = build_hook_context(&ctx, &[], VarScope::All)?;
if verbosity() >= 1 {
eprintln!(
@@ -50,12 +48,7 @@ pub fn step_eval(template: &str, format: SwitchFormat) -> anyhow::Result<()> {
);
}
- let vars: HashMap<&str, &str> = context_map
- .iter()
- .map(|(k, v)| (k.as_str(), v.as_str()))
- .collect();
-
- let result = expand_template(template, &vars, ShellEscapeMode::Literal, &repo, EVAL_NAME)?;
+ let result = context_map.expand(template, ShellEscapeMode::Literal, &repo, EVAL_NAME)?;
// `expand_template` emitted the `source` / `result` view to stderr under
// `-v`; a trailing blank separates it from the result printed below.
if verbosity() >= 1 {
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rs
index 90cc985a4..052296a35 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -24,12 +24,11 @@
//!
//! For now, we keep `for-each` under `step` as a pragmatic choice.
-use std::collections::HashMap;
use std::io::{Write as _, stderr};
use std::process::Stdio;
use color_print::cformat;
-use worktrunk::config::{UserConfig, expand_template};
+use worktrunk::config::{UserConfig, VarScope};
use worktrunk::git::{ErrorExt, Repository, WorktreeInfo, WorktrunkError};
use worktrunk::shell_exec::{Cmd, ShellEscapeMode};
use worktrunk::styling::{
@@ -75,31 +74,19 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
// Build full hook context for this worktree
// Pass wt.branch directly (not the display string) so detached HEAD maps to None -> "HEAD"
let ctx = CommandContext::new(&repo, &config, wt.branch.as_deref(), &wt.path, false);
- let context_map = build_hook_context(&ctx, &[], None)?;
+ let context_map = build_hook_context(&ctx, &[], VarScope::All)?;
// Expand each argv element through the template engine without
// shell-escaping — values are interpolated directly into the argv
// element a program receives, not through `sh -c`.
- let vars: HashMap<&str, &str> = context_map
- .iter()
- .map(|(k, v)| (k.as_str(), v.as_str()))
- .collect();
let expanded: Vec<String> = args
.iter()
.map(|arg| {
- expand_template(
- arg,
- &vars,
- ShellEscapeMode::Literal,
- &repo,
- "for-each argument",
- )
+ context_map.expand(arg, ShellEscapeMode::Literal, &repo, "for-each argument")
})
.collect::<Result<_, _>>()?;
- // Build JSON context for stdin
- let context_json = serde_json::to_string(&context_map)
- .expect("HashMap<String, String> serialization should never fail");
+ let context_json = context_map.to_json();
match run_argv(&wt.path, expanded, &context_json) {
Ok(()) => {
diff --git a/src/commands/hook_announcement.rs b/src/commands/hook_announcement.rs
index 44aa4d64c..065e2d84a 100644
--- a/src/commands/hook_announcement.rs
+++ b/src/commands/hook_announcement.rs
@@ -226,7 +226,7 @@ mod tests {
PreparedCommand {
name: name.map(String::from),
template: template.to_string(),
- context: std::collections::HashMap::new(),
+ context: worktrunk::config::TemplateContext::default(),
template_name: label.clone(),
label,
}
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index 6a54de4d7..ae13fd662 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -4,7 +4,6 @@
//! - `run_hook` - Execute a specific hook type
//! - `handle_hook_show` - Display configured hooks
-use std::collections::HashMap;
use std::fmt::Write as _;
use anyhow::Context;
@@ -12,7 +11,8 @@ use color_print::cformat;
use strum::IntoEnumIterator;
use worktrunk::HookType;
use worktrunk::config::{
- ALIAS_ARGS_KEY, Approvals, CommandConfig, ProjectConfig, UserConfig, referenced_vars_for_config,
+ ALIAS_ARGS_KEY, Approvals, CommandConfig, ProjectConfig, UserConfig, VarScope,
+ referenced_vars_for_config,
};
use worktrunk::git::Repository;
use worktrunk::path::format_path_for_display;
@@ -657,29 +657,24 @@ fn expand_command_template(
let default_branch = ctx.repo.default_branch();
let template_vars = build_manual_hook_template_vars(ctx, hook_type, default_branch.as_deref());
let extra_vars = template_vars.as_extra_vars();
- let mut template_ctx = build_hook_context(ctx, &extra_vars, None)?;
- template_ctx.insert("hook_type".into(), hook_type.to_string());
+ let mut template_ctx = build_hook_context(ctx, &extra_vars, VarScope::All)?;
+ template_ctx.insert("hook_type", hook_type.to_string());
if let Some(name) = hook_name {
- template_ctx.insert("hook_name".into(), name.into());
+ template_ctx.insert("hook_name", name);
}
// 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()))
- .collect();
-
- // Standard template expansion. Hooks always run through `Cmd::shell`
- // (POSIX), so the preview is POSIX-escaped.
- // On any error, show both the template and error message
- Ok(worktrunk::config::expand_template(
- template,
- &vars,
- worktrunk::shell_exec::ShellEscapeMode::Posix,
- ctx.repo,
- "hook preview",
- )
- .unwrap_or_else(|err| format!("# {}\n{}", err.message, template)))
+ template_ctx.insert(ALIAS_ARGS_KEY, "[]");
+
+ // Hooks always run through `Cmd::shell` (POSIX), so the preview is
+ // POSIX-escaped. On any error, show both the template and error message.
+ Ok(template_ctx
+ .expand(
+ template,
+ worktrunk::shell_exec::ShellEscapeMode::Posix,
+ ctx.repo,
+ "hook preview",
+ )
+ .unwrap_or_else(|err| format!("# {}\n{}", err.message, template)))
}
diff --git a/src/commands/pipeline_spec.rs b/src/commands/pipeline_spec.rs
index 48d9314b8..2f4d6fa31 100644
--- a/src/commands/pipeline_spec.rs
+++ b/src/commands/pipeline_spec.rs
@@ -1,8 +1,8 @@
use serde::{Deserialize, Serialize};
-use std::collections::HashMap;
use std::path::PathBuf;
use worktrunk::HookType;
+use worktrunk::config::TemplateContext;
use super::hook_filter::HookSource;
@@ -18,7 +18,7 @@ pub struct PipelineSpec {
pub hook_type: HookType,
pub source: HookSource,
/// Base context variables for template expansion.
- pub context: HashMap<String, String>,
+ pub context: TemplateContext,
pub steps: Vec<PipelineStepSpec>,
/// Directory for per-command log files.
///
@@ -58,14 +58,14 @@ mod tests {
#[test]
fn test_pipeline_spec_roundtrip() {
+ let mut context = TemplateContext::default();
+ context.insert("branch", "feature/auth");
let spec = PipelineSpec {
worktree_path: "/tmp/test-worktree".into(),
branch: "feature/auth".into(),
hook_type: HookType::PostCreate,
source: HookSource::User,
- context: [("branch".into(), "feature/auth".into())]
- .into_iter()
- .collect(),
+ context,
log_dir: "/tmp/test-worktree/.git/wt/logs".into(),
steps: vec![
PipelineStepSpec::Single {
diff --git a/src/commands/run_pipeline.rs b/src/commands/run_pipeline.rs
index 50229311e..f9b02efb1 100644
--- a/src/commands/run_pipeline.rs
+++ b/src/commands/run_pipeline.rs
@@ -55,7 +55,6 @@
//! since the expanded string is passed to a shell for interpretation.
use std::borrow::Cow;
-use std::collections::HashMap;
use std::fs;
use std::io::Read as _;
use std::path::Path;
@@ -63,6 +62,7 @@ use std::process::{Child, ExitStatus, Stdio};
use anyhow::Context;
+use worktrunk::config::TemplateContext;
use worktrunk::git::{Repository, WorktrunkError};
use worktrunk::shell_exec::{ShellConfig, scrub_git_discovery_env_vars};
use worktrunk::trace::CommandTrace;
@@ -108,8 +108,7 @@ pub fn run_pipeline() -> anyhow::Result<()> {
let log_file = create_command_log(&spec, &log_name)?;
let step_ctx = step_context(&spec.context, name.as_deref());
let expanded = expand_shell_template(template, &step_ctx, &repo, template_name)?;
- let step_json = serde_json::to_string(&*step_ctx)
- .context("failed to serialize step context")?;
+ let step_json = step_ctx.to_json();
let (mut child, mut trace) =
spawn_shell_command(&expanded, &spec.worktree_path, &step_json, log_file)?;
let status = wait_resolving(&mut child, &mut trace, &expanded)?;
@@ -131,14 +130,11 @@ pub fn run_pipeline() -> anyhow::Result<()> {
///
/// The shared pipeline context has `hook_name` stripped (it varies per step).
/// Returns a `Cow` so unnamed steps borrow the base context without cloning.
-fn step_context<'a>(
- base: &'a HashMap<String, String>,
- name: Option<&str>,
-) -> Cow<'a, HashMap<String, String>> {
+fn step_context<'a>(base: &'a TemplateContext, name: Option<&str>) -> Cow<'a, TemplateContext> {
match name {
Some(n) => {
let mut ctx = base.clone();
- ctx.insert("hook_name".into(), n.into());
+ ctx.insert("hook_name", n);
Cow::Owned(ctx)
}
None => Cow::Borrowed(base),
@@ -246,8 +242,7 @@ fn run_concurrent_group(
let cmd_ctx = step_context(&spec.context, cmd.name.as_deref());
let expanded =
expand_shell_template(&cmd.template, &cmd_ctx, repo, &cmd.template_name)?;
- let cmd_json =
- serde_json::to_string(&*cmd_ctx).context("failed to serialize step context")?;
+ let cmd_json = cmd_ctx.to_json();
let (mut child, mut trace) =
spawn_shell_command(&expanded, &spec.worktree_path, &cmd_json, log_file)?;
*cmd_index += 1;
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index bf686ac46..ce73ac6eb 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -4,7 +4,6 @@
//! full switch sequence (bare-repo fix-up, hooks, approval, execution, output)
//! shared by the `wt switch` argument path and the interactive picker.
-use std::collections::HashMap;
use std::path::{Path, PathBuf};
use crate::display::format_relative_time_short;
@@ -14,7 +13,8 @@ use dunce::canonicalize;
use serde::Serialize;
use worktrunk::HookType;
use worktrunk::config::{
- UserConfig, ValidationScope, expand_template, template_references_var, validate_template,
+ UserConfig, ValidationScope, VarScope, referenced_vars_for_templates, template_references_var,
+ validate_template,
};
use worktrunk::git::remote_ref::{
self, AzureDevOpsProvider, GitHubProvider, GitLabProvider, GiteaProvider, RemoteRefInfo,
@@ -1752,11 +1752,24 @@ impl SwitchPipeline<'_> {
result.path(),
yes,
);
- let template_vars = build_hook_context(&ctx, &extra_vars, None)?;
- let vars: HashMap<&str, &str> = template_vars
- .iter()
- .map(|(k, v)| (k.as_str(), v.as_str()))
- .collect();
+ // Compute only the vars the command actually names. The map is
+ // consumed by `expand_template` and nothing else — the child
+ // receives a shell string through the EXEC directive file (or
+ // `sh -c`), never the context as JSON on stdin, and `--execute`
+ // renders no `-v` variables table. So a var the templates don't
+ // reference is a git subprocess whose result is thrown away.
+ //
+ // The union is complete: `validate_switch_templates` already
+ // parsed both positions against `ValidationScope::SwitchExecute`
+ // before the switch ran, so nothing reaching here is unparsable.
+ // No `alias_context_filter` — `args` is alias scope only, and
+ // `branch` (the implicit read behind `{{ vars.X }}`) is in
+ // `build_hook_context`'s unconditional cheap block.
+ let referenced = referenced_vars_for_templates(
+ std::iter::once(cmd).chain(execute_args.iter().map(String::as_str)),
+ );
+ let template_vars =
+ build_hook_context(&ctx, &extra_vars, VarScope::Referenced(&referenced))?;
// The `--execute` payload is parsed by the active directive shell:
// the PowerShell wrapper `Invoke-Expression`s the EXEC directive
@@ -1767,7 +1780,7 @@ impl SwitchPipeline<'_> {
let escape_mode = directive_shell_escape_mode();
// Expand template variables in command, escaped for the directive shell.
- let expanded_cmd = expand_template(cmd, &vars, escape_mode, repo, "--execute command")?;
+ let expanded_cmd = template_vars.expand(cmd, escape_mode, repo, "--execute command")?;
// Append any trailing args (after --) to the execute command.
// Each arg is template-expanded literally, then escaped for the
@@ -1778,9 +1791,8 @@ impl SwitchPipeline<'_> {
let expanded_args: Result<Vec<_>, _> = execute_args
.iter()
.map(|arg| {
- expand_template(
+ template_vars.expand(
arg,
- &vars,
ShellEscapeMode::Literal,
repo,
"--execute argument",
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 056f777b3..bbb2b84b7 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -21,6 +21,7 @@ use color_print::cformat;
use minijinja::value::{Enumerator, Object, ObjectRepr};
use minijinja::{Environment, ErrorKind, UndefinedBehavior, Value};
use regex::Regex;
+use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::git::{Diagnostic, HookType, Repository};
@@ -79,7 +80,7 @@ pub fn base_vars() -> Vec<&'static str> {
/// Reserved context key carrying a JSON-encoded `Vec<String>` of positional
/// CLI args forwarded to an alias. The key flows through
-/// `HashMap<String, String>` — stable for stdin JSON — and
+/// [`TemplateContext`]'s flat string map — stable for stdin JSON — and
/// [`expand_template`] rehydrates it as a `ShellArgs` object so bare
/// `{{ args }}` renders as a space-joined, shell-escaped string while
/// indexing, iteration, and `length` behave like a sequence.
@@ -106,6 +107,92 @@ pub const DEPRECATED_TEMPLATE_VARS: &[&str] = &[
/// already in memory at that point is offered.
pub const LIST_COLUMN_VARS: &[&str] = &["branch", "worktree_path", "worktree_name"];
+/// The resolved template variables for one command invocation.
+///
+/// Wraps the map `build_hook_context` produces and owns every operation on
+/// it: expansion, the JSON a hook child reads on stdin, and the `-v` variables
+/// table. Callers hold this rather than a bare map so the borrow
+/// [`expand_template`] needs, the `serde_json` call, and the `(unset)` /
+/// `(unused)` rendering each have one home.
+///
+/// Serializes transparently, so the JSON a child reads and the pipeline spec a
+/// background runner deserializes are both the flat `{"branch": "…", …}`
+/// object the [`ALIAS_ARGS_KEY`] contract describes.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct TemplateContext(HashMap<String, String>);
+
+impl TemplateContext {
+ /// Wrap a resolved variable map. `build_hook_context` is the producer;
+ /// nothing else assembles a context from scratch.
+ pub fn from_vars(vars: HashMap<String, String>) -> Self {
+ Self(vars)
+ }
+
+ /// Bind `key`, replacing any existing value.
+ pub fn insert(&mut self, key: impl Into<String>, value: impl Into<String>) {
+ self.0.insert(key.into(), value.into());
+ }
+
+ /// The value bound to `key`.
+ pub fn get(&self, key: &str) -> Option<&str> {
+ self.0.get(key).map(String::as_str)
+ }
+
+ /// Unbind `key`, so it renders as `(unset)` and is absent from the JSON.
+ pub fn remove(&mut self, key: &str) {
+ self.0.remove(key);
+ }
+
+ /// Expand `template` against these variables, escaping interpolated values
+ /// per `escape_mode`. `name` labels the template in errors.
+ pub fn expand(
+ &self,
+ template: &str,
+ escape_mode: ShellEscapeMode,
+ repo: &Repository,
+ name: &str,
+ ) -> Result<String, TemplateExpandError> {
+ let vars: HashMap<&str, &str> = self
+ .0
+ .iter()
+ .map(|(k, v)| (k.as_str(), v.as_str()))
+ .collect();
+ expand_template(template, &vars, escape_mode, repo, name)
+ }
+
+ /// The JSON form piped to a child's stdin.
+ pub fn to_json(&self) -> String {
+ serde_json::to_string(&self.0)
+ .expect("HashMap<String, String> serialization should never fail")
+ }
+}
+
+/// Which template variables a context build has to resolve.
+///
+/// The choice follows from who reads the finished [`TemplateContext`], not
+/// from what kind of command is running — see `build_hook_context`.
+#[derive(Debug, Clone, Copy)]
+pub enum VarScope<'a> {
+ /// Only the templates read the map, so a var they don't name is never
+ /// looked up. The set comes from `referenced_vars_for_config` or
+ /// [`referenced_vars_for_templates`].
+ Referenced(&'a BTreeSet<String>),
+ /// Something reads keys the templates never mention: a child consuming
+ /// the JSON on stdin, or a command whose output is the variable listing.
+ All,
+}
+
+impl VarScope<'_> {
+ /// Whether `key` has to be resolved.
+ pub fn wants(&self, key: &str) -> bool {
+ match self {
+ VarScope::All => true,
+ VarScope::Referenced(referenced) => referenced.contains(key),
+ }
+ }
+}
+
/// The context in which a template will be expanded.
///
/// Validation uses this to answer "which variables are available here?" —
@@ -219,16 +306,14 @@ pub fn vars_available_in(scope: ValidationScope) -> Vec<&'static str> {
/// distinction here.
fn format_variables_table(
vars: &[&'static str],
- ctx: &HashMap<String, String>,
- referenced: Option<&BTreeSet<String>>,
+ ctx: &TemplateContext,
+ scope: VarScope<'_>,
) -> String {
let max_name = vars.iter().map(|v| v.len()).max().unwrap_or(0);
vars.iter()
- .map(|var| match ctx.get(*var) {
+ .map(|var| match ctx.get(var) {
Some(value) => format!("{var:<max_name$} = {value}"),
- None if referenced.is_some_and(|r| !r.contains(*var)) => {
- cformat!("<dim>{var:<max_name$} = (unused)</>")
- }
+ None if !scope.wants(var) => cformat!("<dim>{var:<max_name$} = (unused)</>"),
None => format!("{var:<max_name$} = (unset)"),
})
.collect::<Vec<_>>()
@@ -241,7 +326,7 @@ fn format_variables_table(
/// active, operation, repo, exec, infrastructure.
///
/// Deprecated aliases and `vars.*` (user state) are intentionally omitted.
-pub fn format_hook_variables(hook_type: HookType, ctx: &HashMap<String, String>) -> String {
+pub fn format_hook_variables(hook_type: HookType, ctx: &TemplateContext) -> String {
let vars: Vec<&'static str> = ACTIVE_VARS
.iter()
.chain(hook_extras(hook_type))
@@ -250,7 +335,7 @@ pub fn format_hook_variables(hook_type: HookType, ctx: &HashMap<String, String>)
.chain(HOOK_INFRASTRUCTURE_VARS)
.copied()
.collect();
- format_variables_table(&vars, ctx, None)
+ format_variables_table(&vars, ctx, VarScope::All)
}
/// Format the resolved template variables for an alias invocation.
@@ -263,14 +348,10 @@ pub fn format_hook_variables(hook_type: HookType, ctx: &HashMap<String, String>)
/// contract; the table displays it space-joined and shell-escaped so it
/// matches what `{{ args }}` substitutes in templates.
///
-/// `referenced` (the set of vars the body actually substitutes) controls
-/// the dim `(unused)` marker for vars the operation skipped computing —
-/// the reader sees what's reachable without paying for values the body
-/// won't substitute.
-pub fn format_alias_variables(
- ctx: &HashMap<String, String>,
- referenced: Option<&BTreeSet<String>>,
-) -> String {
+/// `scope` is the one the context was built with, so vars it skipped render as
+/// dim `(unused)` — the reader sees what's reachable without paying for values
+/// the body won't substitute.
+pub fn format_alias_variables(ctx: &TemplateContext, scope: VarScope<'_>) -> String {
let vars: Vec<&'static str> = ACTIVE_VARS
.iter()
.copied()
@@ -282,9 +363,9 @@ pub fn format_alias_variables(
if let Some(json) = ctx.get(ALIAS_ARGS_KEY) {
let args: Vec<String> = serde_json::from_str(json)
.expect("ALIAS_ARGS_KEY is always serialized from a Vec<String>");
- display_ctx.insert(ALIAS_ARGS_KEY.into(), shell_join(&args));
+ display_ctx.insert(ALIAS_ARGS_KEY, shell_join(&args));
}
- format_variables_table(&vars, &display_ctx, referenced)
+ format_variables_table(&vars, &display_ctx, scope)
}
/// Format the resolved template variables for a bare template expansion
@@ -294,8 +375,8 @@ pub fn format_alias_variables(
/// Same curated ordering and `(unset)` treatment as [`format_hook_variables`],
/// so the four `-v` variable listings (hook foreground, hook background, alias,
/// eval) render one family.
-pub fn format_base_variables(ctx: &HashMap<String, String>) -> String {
- format_variables_table(&base_vars(), ctx, None)
+pub fn format_base_variables(ctx: &TemplateContext) -> String {
+ format_variables_table(&base_vars(), ctx, VarScope::All)
}
/// Extend `referenced` with the implicit context-map keys an alias dispatch
@@ -789,10 +870,10 @@ pub fn template_environment(repo: &Repository) -> Environment<'static> {
/// positives from literal text like `template_vars.txt`. Templates that fail
/// to parse contribute nothing — a syntax error surfaces later at expansion
/// time with a richer message.
-fn referenced_vars(template: &str) -> std::collections::HashSet<String> {
+fn referenced_vars(template: &str) -> BTreeSet<String> {
minijinja::Environment::new()
.template_from_str(template)
- .map(|tmpl| tmpl.undeclared_variables(false))
+ .map(|tmpl| tmpl.undeclared_variables(false).into_iter().collect())
.unwrap_or_default()
}
@@ -801,6 +882,25 @@ pub fn template_references_var(template: &str, var: &str) -> bool {
referenced_vars(template).contains(var)
}
+/// Union of top-level variables referenced across `templates`.
+///
+/// Builds the `referenced` filter for `build_hook_context` at sites that expand
+/// bare template strings rather than a
+/// [`CommandConfig`](super::CommandConfig) — currently `wt switch --execute`,
+/// whose command and trailing args are two separate expansion positions over
+/// one shared context map.
+///
+/// Non-erroring, unlike `referenced_vars_for_config`: an unparsable template
+/// contributes nothing, and its syntax error surfaces from the caller's own
+/// validation, which names the position at fault. Under-collecting is
+/// therefore harmless — the vars a broken template named are ones it never
+/// gets to read.
+pub fn referenced_vars_for_templates<'a>(
+ templates: impl IntoIterator<Item = &'a str>,
+) -> BTreeSet<String> {
+ templates.into_iter().flat_map(referenced_vars).collect()
+}
+
/// Union of top-level variables referenced across every command in `cfg`.
///
/// Drives alias-arg routing in `AliasOptions::parse`: a `--KEY=VALUE` token
@@ -2881,6 +2981,30 @@ mod tests {
assert!(err.message.contains("syntax error"), "got: {}", err.message);
}
+ /// The `--execute` filter unions across the command and its trailing args,
+ /// which are separate expansion positions over one context map — a var
+ /// named only in an arg still has to be computed.
+ #[test]
+ fn test_referenced_vars_for_templates_unions_positions() {
+ let refs = referenced_vars_for_templates(["echo {{ commit }}", "--onto={{ branch }}"]);
+ assert_eq!(
+ refs.iter().map(String::as_str).collect::<Vec<_>>(),
+ ["branch", "commit"]
+ );
+ }
+
+ /// Unparsable templates contribute nothing rather than erroring — the
+ /// caller's own validation reports the syntax error, naming which position
+ /// was at fault.
+ #[test]
+ fn test_referenced_vars_for_templates_skips_unparsable() {
+ let refs = referenced_vars_for_templates(["{{ unclosed", "echo {{ commit }}"]);
+ assert_eq!(
+ refs.iter().map(String::as_str).collect::<Vec<_>>(),
+ ["commit"]
+ );
+ }
+
#[test]
fn test_referenced_vars_for_config_syntax_error_propagates() {
let cfg = super::super::CommandConfig::single("echo {{ unclosed");
@@ -2913,19 +3037,19 @@ mod tests {
#[test]
fn test_format_hook_variables_groups_and_unset() {
- let mut ctx: HashMap<String, String> = HashMap::new();
- ctx.insert("branch".into(), "feature".into());
- ctx.insert("worktree_path".into(), "/tmp/feature".into());
- ctx.insert("worktree_name".into(), "feature".into());
- ctx.insert("base".into(), "main".into());
- ctx.insert("base_worktree_path".into(), "/tmp/main".into());
- ctx.insert("target".into(), "-".into());
+ let mut ctx = TemplateContext::default();
+ ctx.insert("branch", "feature");
+ ctx.insert("worktree_path", "/tmp/feature");
+ ctx.insert("worktree_name", "feature");
+ ctx.insert("base", "main");
+ ctx.insert("base_worktree_path", "/tmp/main");
+ ctx.insert("target", "-");
// target_worktree_path deliberately absent — mimics `wt switch -`
- ctx.insert("repo".into(), "demo".into());
- ctx.insert("repo_path".into(), "/tmp/demo".into());
- ctx.insert("cwd".into(), "/tmp/feature".into());
- ctx.insert("hook_type".into(), "pre-switch".into());
- ctx.insert("hook_name".into(), "show-variables".into());
+ ctx.insert("repo", "demo");
+ ctx.insert("repo_path", "/tmp/demo");
+ ctx.insert("cwd", "/tmp/feature");
+ ctx.insert("hook_type", "pre-switch");
+ ctx.insert("hook_name", "show-variables");
assert_snapshot!(format_hook_variables(HookType::PreSwitch, &ctx), @r"
branch = feature
@@ -2956,8 +3080,8 @@ mod tests {
#[test]
fn test_format_hook_variables_filters_operation() {
// pre-commit only has `target` in operation scope — no base*, pr_*, etc.
- let mut ctx: HashMap<String, String> = HashMap::new();
- ctx.insert("target".into(), "main".into());
+ let mut ctx = TemplateContext::default();
+ ctx.insert("target", "main");
let out = format_hook_variables(HookType::PreCommit, &ctx);
assert!(out.contains("target = main"), "got: {out}");
assert!(
@@ -2972,18 +3096,18 @@ mod tests {
#[test]
fn test_format_alias_variables_includes_args_no_hook_keys() {
- let mut ctx: HashMap<String, String> = HashMap::new();
- ctx.insert("branch".into(), "feature".into());
- ctx.insert("worktree_path".into(), "/tmp/feature".into());
- ctx.insert("worktree_name".into(), "feature".into());
- ctx.insert("repo".into(), "demo".into());
- ctx.insert("repo_path".into(), "/tmp/demo".into());
- ctx.insert("cwd".into(), "/tmp/feature".into());
+ let mut ctx = TemplateContext::default();
+ ctx.insert("branch", "feature");
+ ctx.insert("worktree_path", "/tmp/feature");
+ ctx.insert("worktree_name", "feature");
+ ctx.insert("repo", "demo");
+ ctx.insert("repo_path", "/tmp/demo");
+ ctx.insert("cwd", "/tmp/feature");
// args is JSON-encoded per `ALIAS_ARGS_KEY` contract; the table
// decodes and shell-renders it to match `{{ args }}` substitution.
- ctx.insert(ALIAS_ARGS_KEY.into(), r#"["a","b c"]"#.into());
+ ctx.insert(ALIAS_ARGS_KEY, r#"["a","b c"]"#);
- let out = format_alias_variables(&ctx, None);
+ let out = format_alias_variables(&ctx, VarScope::All);
assert!(
out.contains("args = a 'b c'"),
"got: {out}"
@@ -2996,9 +3120,9 @@ mod tests {
#[test]
fn test_format_alias_variables_args_empty() {
- let mut ctx: HashMap<String, String> = HashMap::new();
- ctx.insert(ALIAS_ARGS_KEY.into(), "[]".into());
- let out = format_alias_variables(&ctx, None);
+ let mut ctx = TemplateContext::default();
+ ctx.insert(ALIAS_ARGS_KEY, "[]");
+ let out = format_alias_variables(&ctx, VarScope::All);
// Empty args render as an empty string after the `=` — distinct from
// `(unset)`, which means the key was absent entirely. `args` sits last
// in alias ordering, so the output ends with it.
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 4742f21b9..3e690be40 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -161,9 +161,10 @@ pub use deprecation::{
pub use deprecation::{DeprecationKind, Deprecations};
pub use expansion::{
ACTIVE_VARS, ALIAS_ARGS_KEY, DEPRECATED_TEMPLATE_VARS, EXEC_BASE_VARS, REPO_VARS,
- TemplateExpandError, ValidationScope, alias_context_filter, base_vars, expand_template,
- format_alias_variables, format_base_variables, format_hook_variables, redact_credentials,
- referenced_vars_for_config, sanitize_branch_name, sanitize_db, short_hash,
+ TemplateContext, TemplateExpandError, ValidationScope, VarScope, alias_context_filter,
+ base_vars, expand_template, format_alias_variables, format_base_variables,
+ format_hook_variables, redact_credentials, referenced_vars_for_config,
+ referenced_vars_for_templates, sanitize_branch_name, sanitize_db, short_hash,
template_environment, template_references_var, validate_list_column_template,
validate_template, validate_template_syntax, vars_available_in, vars_map_to_value,
};
diff --git a/src/llm.rs b/src/llm.rs
index 935a687ee..469a3f95f 100644
--- a/src/llm.rs
+++ b/src/llm.rs
@@ -391,7 +391,7 @@ pub(crate) fn prepare_diff(diff: String, stat: String) -> PreparedDiff {
///
/// All fields are available to both commit and squash templates.
/// Squash-specific fields (`commit_details`, `target_branch`) are empty/None for regular commits.
-struct TemplateContext<'a> {
+struct PromptContext<'a> {
/// The diff to describe (staged changes for commit, combined diff for squash)
git_diff: &'a str,
/// Diff statistics summary (output of git diff --stat)
@@ -616,7 +616,7 @@ fn load_template(
fn build_prompt(
config: &CommitGenerationConfig,
template_type: TemplateType,
- context: &TemplateContext<'_>,
+ context: &PromptContext<'_>,
) -> anyhow::Result<String> {
// Get template source based on type
let (template, type_name) = match template_type {
@@ -883,7 +883,7 @@ pub(crate) fn build_commit_prompt(
let recent_commits = repo.recent_commit_subjects(None, 5);
- let context = TemplateContext {
+ let context = PromptContext {
git_diff: &prepared.diff,
git_diff_stat: &prepared.stat,
branch: &current_branch,
@@ -970,7 +970,7 @@ pub(crate) fn build_squash_prompt(
let prepared = prepare_diff(diff_output, diff_stat);
let recent_commits = repo.recent_commit_subjects(Some(merge_base), 5);
- let context = TemplateContext {
+ let context = PromptContext {
git_diff: &prepared.diff,
git_diff_stat: &prepared.stat,
branch: current_branch,
@@ -1022,7 +1022,7 @@ pub(crate) fn test_commit_generation(
"fix: Handle edge case in parser".to_string(),
"docs: Update README".to_string(),
];
- let context = TemplateContext {
+ let context = PromptContext {
git_diff: SYNTHETIC_DIFF,
git_diff_stat: SYNTHETIC_DIFF_STAT,
branch: "feature/example",
@@ -1165,8 +1165,8 @@ mod tests {
branch: &'a str,
recent_commits: Option<&'a Vec<String>>,
repo_name: &'a str,
- ) -> TemplateContext<'a> {
- TemplateContext {
+ ) -> PromptContext<'a> {
+ PromptContext {
git_diff,
git_diff_stat: "",
branch,
@@ -1186,8 +1186,8 @@ mod tests {
repo_name: &'a str,
commit_details: &'a [CommitMessageDetail],
target_branch: &'a str,
- ) -> TemplateContext<'a> {
- TemplateContext {
+ ) -> PromptContext<'a> {
+ PromptContext {
git_diff,
git_diff_stat: "",
branch,
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index d007811b6..5b01e1172 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -638,6 +638,62 @@ fn test_switch_execute_fallback_does_not_inherit_git_discovery_vars(mut repo: Te
);
}
+/// `--execute` computes only the template variables its command names.
+///
+/// The context map built at that call site feeds `expand_template` and nothing
+/// else — the payload reaches the child as a shell string, never as JSON on
+/// stdin, and `--execute` renders no `-v` variables table — so a var the
+/// templates don't reference is a git subprocess whose result is discarded.
+/// `var_default_branch` is the one with teeth: on a clone with no
+/// `refs/remotes/origin/HEAD` and no cached `worktrunk.default-branch` it falls
+/// through to `git ls-remote`, so an unfiltered context puts a variable-free
+/// `wt switch -x` on the network.
+///
+/// The `var_*` spans in the `-vv` trace are that work made observable. The
+/// second case is the control: it proves the trace captures spans from this
+/// call site, so the first case's empty set is the filter working rather than
+/// the trace missing them.
+#[rstest]
+fn test_switch_execute_computes_only_referenced_vars(mut repo: TestRepo) {
+ repo.add_worktree("exec-vars");
+ let trace = repo.root_path().join(".git/wt/logs/trace.jsonl");
+
+ // Each `-vv` run replaces trace.jsonl, so the two cases don't accumulate.
+ let var_spans = |execute: &str| -> Vec<String> {
+ let output = repo
+ .wt_command()
+ .args(["-vv", "switch", "exec-vars", "--execute", execute])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "switch --execute '{execute}' failed:\nstderr: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let raw = fs::read_to_string(&trace).expect("-vv should write trace.jsonl");
+ let mut spans: Vec<String> = raw
+ .lines()
+ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
+ .filter(|record| record["kind"] == "span")
+ .filter_map(|record| record["span"].as_str().map(str::to_owned))
+ .filter(|span| span.starts_with("var_"))
+ .collect();
+ spans.sort();
+ spans
+ };
+
+ let none_referenced = var_spans("echo hi");
+ assert!(
+ none_referenced.is_empty(),
+ "a --execute command naming no variables should compute none, got {none_referenced:?}"
+ );
+ assert_eq!(
+ var_spans("echo {{ commit }}"),
+ ["var_commit"],
+ "a --execute command naming commit should compute exactly that"
+ );
+}
+
/// `--execute` with trailing `-- args` containing shell metacharacters: the
/// constructed command appended to the exec directive file must POSIX-escape
/// each trailing arg so the user's shell wrapper (`sh -c`, `bash -c`, …)