Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: add verbose output for template expansion and SemiStrict undefined behavior (#712)
Maximilian Roos1a38c2ace164
diff --git a/.claude-plugin/skills/worktrunk/reference/hook.md b/.claude-plugin/skills/worktrunk/reference/hook.mdindex c31838767..61ae997b3 100644--- a/.claude-plugin/skills/worktrunk/reference/hook.md+++ b/.claude-plugin/skills/worktrunk/reference/hook.md@@ -190,11 +190,19 @@ Hooks can use template variables that expand at runtime:| `{{ short_commit }}` | Short HEAD commit SHA (7 chars) || `{{ remote }}` | Primary remote name || `{{ remote_url }}` | Remote URL |-| `{{ upstream }}` | Upstream tracking branch |+| `{{ upstream }}` | Upstream tracking branch (if set) || `{{ target }}` | Target branch (merge hooks only) || `{{ base }}` | Base branch (creation hooks only) || `{{ base_worktree_path }}` | Base branch worktree (creation hooks only) |+Some variables may not be defined: `upstream` is only set when the branch tracks a remote; `target`, `base`, and `base_worktree_path` are hook-specific. Using an undefined variable directly errors — use conditionals for optional behavior:++```toml+[post-create]+# Rebase onto upstream if tracking a remote branch (e.g., wt switch --create feature origin/feature)+sync = "{% if upstream %}git fetch && git rebase {{ upstream }}{% endif %}"+```+### Worktrunk filtersTemplates support Jinja2 filters for transforming values:diff --git a/.claude/rules/cli-output-formatting.md b/.claude/rules/cli-output-formatting.mdindex 2e25cfacf..517680424 100644--- a/.claude/rules/cli-output-formatting.md+++ b/.claude/rules/cli-output-formatting.md@@ -738,6 +738,26 @@ std::fs::read_to_string(&path).context("Failed to read config")?See `format_error_block()` in `src/git/error.rs`.+## Verbose Output (`-v` and `-vv`)++**`-v` (verbose):** User-facing diagnostic output. Must follow these guidelines.+Shows template expansions and other details users might need for debugging config.++Format for template expansion:+```+○ Expanding name+ ┃ template → result+```++- **Info message** for header (`○` symbol, "Expanding" + bold name)+- **Gutter** for quoted content (template → result)+- Arrow `→` is dim+- For multiline: template lines, dim `→` on its own line, result lines++**`-vv` (debug):** Developer-facing logging output. MAY violate these guidelines.+Uses `log::debug!()` with structured format for deep debugging. Not intended for+regular users.+## Table Column Alignment- **Text columns** (Branch, Path): left-aligneddiff --git a/docs/content/hook.md b/docs/content/hook.mdindex f48cb742e..40f30dc7c 100644--- a/docs/content/hook.md+++ b/docs/content/hook.md@@ -198,11 +198,19 @@ Hooks can use template variables that expand at runtime:| `{{ short_commit }}` | Short HEAD commit SHA (7 chars) || `{{ remote }}` | Primary remote name || `{{ remote_url }}` | Remote URL |-| `{{ upstream }}` | Upstream tracking branch |+| `{{ upstream }}` | Upstream tracking branch (if set) || `{{ target }}` | Target branch (merge hooks only) || `{{ base }}` | Base branch (creation hooks only) || `{{ base_worktree_path }}` | Base branch worktree (creation hooks only) |+Some variables may not be defined: `upstream` is only set when the branch tracks a remote; `target`, `base`, and `base_worktree_path` are hook-specific. Using an undefined variable directly errors — use conditionals for optional behavior:++```toml+[post-create]+# Rebase onto upstream if tracking a remote branch (e.g., wt switch --create feature origin/feature)+sync = "{% if upstream %}git fetch && git rebase {{ upstream }}{% endif %}"+```+### Worktrunk filtersTemplates support Jinja2 filters for transforming values:diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 89c199e32..d235ff6c0 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -1204,11 +1204,19 @@ Hooks can use template variables that expand at runtime:| `{{ short_commit }}` | Short HEAD commit SHA (7 chars) || `{{ remote }}` | Primary remote name || `{{ remote_url }}` | Remote URL |-| `{{ upstream }}` | Upstream tracking branch |+| `{{ upstream }}` | Upstream tracking branch (if set) || `{{ target }}` | Target branch (merge hooks only) || `{{ base }}` | Base branch (creation hooks only) || `{{ base_worktree_path }}` | Base branch worktree (creation hooks only) |+Some variables may not be defined: `upstream` is only set when the branch tracks a remote; `target`, `base`, and `base_worktree_path` are hook-specific. Using an undefined variable directly errors — use conditionals for optional behavior:++```toml+[post-create]+# Rebase onto upstream if tracking a remote branch (e.g., wt switch --create feature origin/feature)+sync = "{% if upstream %}git fetch && git rebase {{ upstream }}{% endif %}"+```+### Worktrunk filtersTemplates support Jinja2 filters for transforming values:diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex fd56c2073..549784569 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -5,6 +5,8 @@ use worktrunk::config::{Command, CommandConfig, WorktrunkConfig, expand_templateuse worktrunk::git::Repository;use worktrunk::path::to_posix_path;+use super::hook_filter::HookSource;+#[derive(Debug)]pub struct PreparedCommand {pub name: Option<String>,@@ -138,6 +140,7 @@ fn expand_commands(ctx: &CommandContext<'_>,extra_vars: &[(&str, &str)],hook_type: HookType,+ source: HookSource,) -> anyhow::Result<Vec<(Command, String)>> {if commands.is_empty() {return Ok(Vec::new());@@ -154,13 +157,18 @@ fn expand_commands(let mut result = Vec::new();for cmd in commands {- let expanded_str = expand_template(&cmd.template, &vars, true, ctx.repo).map_err(|e| {- anyhow::anyhow!(- "Failed to expand command template '{}': {}",- cmd.template,- e- )- })?;+ let template_name = match &cmd.name {+ Some(name) => format!("{}:{}", source, name),+ None => format!("{} {} hook", source, hook_type),+ };+ let expanded_str = expand_template(&cmd.template, &vars, true, ctx.repo, &template_name)+ .map_err(|e| {+ anyhow::anyhow!(+ "Failed to expand command template '{}': {}",+ cmd.template,+ e+ )+ })?;// Build per-command JSON with hook_type and hook_namelet mut cmd_context = base_context.clone();@@ -193,13 +201,14 @@ pub fn prepare_commands(ctx: &CommandContext<'_>,extra_vars: &[(&str, &str)],hook_type: HookType,+ source: HookSource,) -> anyhow::Result<Vec<PreparedCommand>> {let commands = command_config.commands();if commands.is_empty() {return Ok(Vec::new());}- let expanded_with_json = expand_commands(commands, ctx, extra_vars, hook_type)?;+ let expanded_with_json = expand_commands(commands, ctx, extra_vars, hook_type, source)?;Ok(expanded_with_json.into_iter()diff --git a/src/commands/for_each.rs b/src/commands/for_each.rsindex 8bbb9724b..94ef0cf54 100644--- a/src/commands/for_each.rs+++ b/src/commands/for_each.rs@@ -86,7 +86,7 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {.collect();// Expand template with full context (shell-escaped)- let command = expand_template(&command_template, &vars, true, &repo)+ let command = expand_template(&command_template, &vars, true, &repo, "for-each command").map_err(|e| anyhow::anyhow!("Template expansion failed: {e}"))?;// Build JSON context for stdindiff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex d6e30bfe7..b09fb58ca 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -626,6 +626,7 @@ fn expand_command_template(template: &str, ctx: &CommandContext, hook_type: Hook.collect();// Use the standard template expansion (shell-escaped)- worktrunk::config::expand_template(template, &vars, true, ctx.repo)+ // Falls back to raw template if expansion fails (e.g., missing optional variable)+ worktrunk::config::expand_template(template, &vars, true, ctx.repo, "hook preview").unwrap_or_else(|_| template.to_string())}diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 8faa3f1b9..bcc8462c9 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -107,7 +107,7 @@ pub fn prepare_hook_commands(continue;}- let prepared = prepare_commands(config, ctx, extra_vars, hook_type)?;+ let prepared = prepare_commands(config, ctx, extra_vars, hook_type, source)?;let filtered = filter_by_name(prepared, parsed_filter.as_ref().map(|f| f.name));commands.extend(filtered.into_iter().map(|p| SourcedCommand {prepared: p,diff --git a/src/commands/list/collect/execution.rs b/src/commands/list/collect/execution.rsindex c743bd1ac..fd7a55df5 100644--- a/src/commands/list/collect/execution.rs+++ b/src/commands/list/collect/execution.rs@@ -150,7 +150,7 @@ pub fn work_items_for_worktree(wt.branch.as_ref().and_then(|branch| {let mut vars = std::collections::HashMap::new();vars.insert("branch", branch.as_str());- worktrunk::config::expand_template(template, &vars, false, repo).ok()+ worktrunk::config::expand_template(template, &vars, false, repo, "url-template").ok()})});diff --git a/src/config/expansion.rs b/src/config/expansion.rsindex 7f0d20203..668187c1a 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -8,10 +8,12 @@//!//! See `wt hook --help` for available filters and functions.-use minijinja::{Environment, Value};+use color_print::cformat;+use minijinja::{Environment, UndefinedBehavior, Value};use crate::git::Repository;use crate::path::to_posix_path;+use crate::styling::{eprintln, format_with_gutter, info_message, verbosity};/// Known template variables available in hook commands.///@@ -183,11 +185,14 @@ fn short_hash(s: &str) -> String {/// # Functions/// - `worktree_path_of_branch(branch)` — Look up the filesystem path of a branch's worktree/// Returns empty string if branch has no worktree.+///+/// The `name` parameter appears in error messages to help identify which template failed.pub fn expand_template(template: &str,vars: &HashMap<&str, &str>,shell_escape: bool,repo: &Repository,+ name: &str,) -> Result<String, String> {use shell_escape::escape;use std::borrow::Cow;@@ -205,6 +210,9 @@ pub fn expand_template(// Render template with minijinjalet mut env = Environment::new();+ // SemiStrict: errors on undefined variable use (printing, iteration) but allows+ // truthiness checks ({% if var %}). This catches typos while supporting optional vars.+ env.set_undefined_behavior(UndefinedBehavior::SemiStrict);if shell_escape {// Preserve trailing newlines in templates (important for multiline shell commands)env.set_keep_trailing_newline(true);@@ -230,12 +238,52 @@ pub fn expand_template(.unwrap_or_default()});+ // Cache verbosity level for consistent behavior within this call+ let verbose = verbosity();++ // -vv: Full debug logging with vars+ if verbose >= 2 {+ log::debug!("[template:{name}] template={template:?}");+ // Sort keys for deterministic output in tests+ let mut sorted_vars: Vec<_> = vars.iter().collect();+ sorted_vars.sort_by_key(|(k, _)| *k);+ log::debug!(+ "[template:{name}] vars={{{}}}",+ sorted_vars+ .iter()+ .map(|(k, v)| format!("{k}={v:?}"))+ .collect::<Vec<_>>()+ .join(", ")+ );+ }+let tmpl = env- .template_from_str(template)+ .template_from_named_str(name, template).map_err(|e| format!("Template syntax error: {}", e))?;- tmpl.render(minijinja::Value::from_object(context))- .map_err(|e| format!("Template render error: {}", e))+ let result = tmpl+ .render(minijinja::Value::from_object(context))+ .map_err(|e| format!("Template render error: {}", e))?;++ // -vv: Full debug logging with result+ if verbose >= 2 {+ log::debug!("[template:{name}] result={result:?}");+ }++ // -v: Nice styled output showing template expansion+ // Info message for header, gutter for quoted content (template → result)+ if verbose == 1 {+ eprintln!("{}", info_message(cformat!("Expanding <bold>{name}</>")));+ let content = if template.contains('\n') || result.contains('\n') {+ // Multiline: template lines, dim →, result lines+ cformat!("{template}\n<dim>→</>\n{result}")+ } else {+ // Single line: template → result+ cformat!("{template} <dim>→</> {result}")+ };+ eprintln!("{}", format_with_gutter(&content, None));+ }+ Ok(result)}#[cfg(test)]@@ -402,27 +450,32 @@ mod tests {let mut vars = HashMap::new();vars.insert("name", "world");assert_eq!(- expand_template("Hello {{ name }}", &vars, false, &test.repo).unwrap(),+ expand_template("Hello {{ name }}", &vars, false, &test.repo, "test").unwrap(),"Hello world");// Multiple variablesvars.insert("repo", "myrepo");assert_eq!(- expand_template("{{ repo }}/{{ name }}", &vars, false, &test.repo).unwrap(),+ expand_template("{{ repo }}/{{ name }}", &vars, false, &test.repo, "test").unwrap(),"myrepo/world");// Empty/static caseslet empty: HashMap<&str, &str> = HashMap::new();- assert_eq!(expand_template("", &empty, false, &test.repo).unwrap(), "");assert_eq!(- expand_template("static text", &empty, false, &test.repo).unwrap(),- "static text"+ expand_template("", &empty, false, &test.repo, "test").unwrap(),+ "");assert_eq!(- expand_template("no {{ variables }} here", &empty, false, &test.repo).unwrap(),- "no here"+ expand_template("static text", &empty, false, &test.repo, "test").unwrap(),+ "static text"+ );+ // Undefined variables now error in SemiStrict mode+ assert!(+ expand_template("no {{ variables }} here", &empty, false, &test.repo, "test")+ .unwrap_err()+ .contains("undefined"));}@@ -431,18 +484,18 @@ mod tests {let test = test_repo();let mut vars = HashMap::new();vars.insert("path", "my path");- let expanded = expand_template("cd {{ path }}", &vars, true, &test.repo).unwrap();+ let expanded = expand_template("cd {{ path }}", &vars, true, &test.repo, "test").unwrap();assert!(expanded.contains("'my path'") || expanded.contains("my\\ path"));// Command injection preventionvars.insert("arg", "test;rm -rf");- let expanded = expand_template("echo {{ arg }}", &vars, true, &test.repo).unwrap();+ let expanded = expand_template("echo {{ arg }}", &vars, true, &test.repo, "test").unwrap();assert!(!expanded.contains(";rm") || expanded.contains("'"));// No escape for literal modevars.insert("branch", "feature/foo");assert_eq!(- expand_template("{{ branch }}", &vars, false, &test.repo).unwrap(),+ expand_template("{{ branch }}", &vars, false, &test.repo, "test").unwrap(),"feature/foo");}@@ -452,11 +505,11 @@ mod tests {let test = test_repo();let vars = HashMap::new();assert!(- expand_template("{{ unclosed", &vars, false, &test.repo)+ expand_template("{{ unclosed", &vars, false, &test.repo, "test").unwrap_err().contains("syntax error"));- assert!(expand_template("{{ 1 + }}", &vars, false, &test.repo).is_err());+ assert!(expand_template("{{ 1 + }}", &vars, false, &test.repo, "test").is_err());}#[test]@@ -465,13 +518,27 @@ mod tests {let mut vars = HashMap::new();vars.insert("debug", "true");assert_eq!(- expand_template("{% if debug %}DEBUG{% endif %}", &vars, false, &test.repo).unwrap(),+ expand_template(+ "{% if debug %}DEBUG{% endif %}",+ &vars,+ false,+ &test.repo,+ "test"+ )+ .unwrap(),"DEBUG");vars.insert("debug", "");assert_eq!(- expand_template("{% if debug %}DEBUG{% endif %}", &vars, false, &test.repo).unwrap(),+ expand_template(+ "{% if debug %}DEBUG{% endif %}",+ &vars,+ false,+ &test.repo,+ "test"+ )+ .unwrap(),"");@@ -481,7 +548,8 @@ mod tests {"{{ missing | default('fallback') }}",&empty,false,- &test.repo+ &test.repo,+ "test",).unwrap(),"fallback"@@ -489,7 +557,7 @@ mod tests {vars.insert("name", "hello");assert_eq!(- expand_template("{{ name | upper }}", &vars, false, &test.repo).unwrap(),+ expand_template("{{ name | upper }}", &vars, false, &test.repo, "test").unwrap(),"HELLO");}@@ -500,28 +568,28 @@ mod tests {let mut vars = HashMap::new();vars.insert("branch", "feature/foo");assert_eq!(- expand_template("{{ branch | sanitize }}", &vars, false, &test.repo).unwrap(),+ expand_template("{{ branch | sanitize }}", &vars, false, &test.repo, "test").unwrap(),"feature-foo");// Backslashes are also sanitizedvars.insert("branch", "feature\\bar");assert_eq!(- expand_template("{{ branch | sanitize }}", &vars, false, &test.repo).unwrap(),+ expand_template("{{ branch | sanitize }}", &vars, false, &test.repo, "test").unwrap(),"feature-bar");// Multiple slashesvars.insert("branch", "user/feature/task");assert_eq!(- expand_template("{{ branch | sanitize }}", &vars, false, &test.repo).unwrap(),+ expand_template("{{ branch | sanitize }}", &vars, false, &test.repo, "test").unwrap(),"user-feature-task");// Raw branch is unchangedvars.insert("branch", "feature/foo");assert_eq!(- expand_template("{{ branch }}", &vars, false, &test.repo).unwrap(),+ expand_template("{{ branch }}", &vars, false, &test.repo, "test").unwrap(),"feature/foo");}@@ -533,26 +601,44 @@ mod tests {// Basic transformation (with hash suffix)vars.insert("branch", "feature/auth-oauth2");- let result =- expand_template("{{ branch | sanitize_db }}", &vars, false, &test.repo).unwrap();+ let result = expand_template(+ "{{ branch | sanitize_db }}",+ &vars,+ false,+ &test.repo,+ "test",+ )+ .unwrap();assert!(result.starts_with("feature_auth_oauth2_"), "got: {result}");// Leading digit gets underscore prefixvars.insert("branch", "123-bug-fix");- let result =- expand_template("{{ branch | sanitize_db }}", &vars, false, &test.repo).unwrap();+ let result = expand_template(+ "{{ branch | sanitize_db }}",+ &vars,+ false,+ &test.repo,+ "test",+ )+ .unwrap();assert!(result.starts_with("_123_bug_fix_"), "got: {result}");// Uppercase conversionvars.insert("branch", "UPPERCASE.Branch");- let result =- expand_template("{{ branch | sanitize_db }}", &vars, false, &test.repo).unwrap();+ let result = expand_template(+ "{{ branch | sanitize_db }}",+ &vars,+ false,+ &test.repo,+ "test",+ )+ .unwrap();assert!(result.starts_with("uppercase_branch_"), "got: {result}");// Raw branch is unchangedvars.insert("branch", "feature/foo");assert_eq!(- expand_template("{{ branch }}", &vars, false, &test.repo).unwrap(),+ expand_template("{{ branch }}", &vars, false, &test.repo, "test").unwrap(),"feature/foo");}@@ -563,7 +649,7 @@ mod tests {let mut vars = HashMap::new();vars.insert("cmd", "echo hello");assert!(- expand_template("{{ cmd }}\n", &vars, true, &test.repo)+ expand_template("{{ cmd }}\n", &vars, true, &test.repo, "test").unwrap().ends_with('\n'));@@ -587,7 +673,8 @@ mod tests {vars.insert("repo", "myrepo");// Filter produces a number in range- let result = expand_template("{{ branch | hash_port }}", &vars, false, &test.repo).unwrap();+ let result =+ expand_template("{{ branch | hash_port }}", &vars, false, &test.repo, "test").unwrap();let port: u16 = result.parse().expect("should be a number");assert!((10000..20000).contains(&port));@@ -597,6 +684,7 @@ mod tests {&vars,false,&test.repo,+ "test",).unwrap();let r1_port: u16 = r1.parse().expect("should be a number");@@ -605,6 +693,7 @@ mod tests {&vars,false,&test.repo,+ "test",).unwrap();let r2_port: u16 = r2.parse().expect("should be a number");diff --git a/src/config/mod.rs b/src/config/mod.rsindex 0da85fb9f..cfa0340c3 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -598,6 +598,7 @@ task2 = "echo 'Task 2 running' > task2.txt"&vars,true,&test.repo,+ "test",).unwrap();assert_eq!(result, "../myrepo.feature-x");@@ -619,6 +620,7 @@ task2 = "echo 'Task 2 running' > task2.txt"&vars,false,&test.repo,+ "test",).unwrap();assert_eq!(result, "myrepo/feature-foo");@@ -631,6 +633,7 @@ task2 = "echo 'Task 2 running' > task2.txt"&vars,false,&test.repo,+ "test",).unwrap();assert_eq!(result, ".worktrees/myrepo/feat-bar");@@ -649,6 +652,7 @@ task2 = "echo 'Task 2 running' > task2.txt"&vars,true,&test_repo().repo,+ "test",).unwrap();assert_eq!(result, "/path/to/repo/target -> /path/to/worktree/target");diff --git a/src/config/test.rs b/src/config/test.rsindex 3faf74aa6..206f16b26 100644--- a/src/config/test.rs+++ b/src/config/test.rs@@ -48,6 +48,7 @@ fn test_expand_template_normal() {&vars,true,&test.repo,+ "test",).unwrap();assert_eq!(result, "echo feature myrepo");@@ -58,7 +59,14 @@ fn test_expand_template_branch_with_slashes() {let test = test_repo();// Use {{ branch | sanitize }} to replace slashes with dasheslet vars = vars_with_branch("feature/nested/branch");- let result = expand_template("echo {{ branch | sanitize }}", &vars, true, &test.repo).unwrap();+ let result = expand_template(+ "echo {{ branch | sanitize }}",+ &vars,+ true,+ &test.repo,+ "test",+ )+ .unwrap();assert_eq!(result, "echo feature-nested-branch");}@@ -67,7 +75,7 @@ fn test_expand_template_branch_raw_with_slashes() {let test = test_repo();// Raw branch preserves slasheslet vars = vars_with_branch("feature/nested/branch");- let result = expand_template("echo {{ branch }}", &vars, true, &test.repo).unwrap();+ let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();assert_eq!(result, "echo feature/nested/branch");}@@ -82,6 +90,7 @@ fn test_expand_template_branch_escaping() {&vars_with_branch(input),true,&test.repo,+ "test",).unwrap()};@@ -96,7 +105,7 @@ fn test_expand_template_branch_escaping() {fn snapshot_expand_template_branch_with_quotes() {let test = test_repo();let vars = vars_with_branch("feature'test");- let result = expand_template("echo '{{ branch }}'", &vars, true, &test.repo).unwrap();+ let result = expand_template("echo '{{ branch }}'", &vars, true, &test.repo, "test").unwrap();insta::assert_snapshot!(result, @r"echo ''feature'\''test''");}@@ -110,6 +119,7 @@ fn test_expand_template_extra_vars_path_escaping() {&HashMap::from([("worktree", path)]),true,&test.repo,+ "test",).unwrap()};@@ -127,7 +137,8 @@ fn snapshot_expand_template_extra_vars_with_command_substitution() {let test = test_repo();let mut extras = HashMap::new();extras.insert("target", "main; rm -rf /");- let result = expand_template("git merge {{ target }}", &extras, true, &test.repo).unwrap();+ let result =+ expand_template("git merge {{ target }}", &extras, true, &test.repo, "test").unwrap();insta::assert_snapshot!(result, @"git merge 'main; rm -rf /'");}@@ -138,7 +149,7 @@ fn test_expand_template_variable_override() {// Variables in the hashmap take precedencelet mut vars = HashMap::new();vars.insert("branch", "overridden");- let result = expand_template("echo {{ branch }}", &vars, true, &test.repo).unwrap();+ let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();assert_eq!(result, "echo overridden");}@@ -146,12 +157,12 @@ fn test_expand_template_variable_override() {#[test]fn test_expand_template_missing_variable() {let test = test_repo();- // What happens with undefined variables?+ // Undefined variables error in SemiStrict mode (catches typos)let vars: HashMap<&str, &str> = HashMap::new();- let result = expand_template("echo {{ undefined }}", &vars, true, &test.repo).unwrap();+ let result = expand_template("echo {{ undefined }}", &vars, true, &test.repo, "test");- // minijinja will render undefined variables as empty string- assert_eq!(result, "echo ");+ assert!(result.is_err());+ assert!(result.unwrap_err().contains("undefined"));}#[test]@@ -160,7 +171,7 @@ fn test_expand_template_empty_branch() {let test = test_repo();let mut vars = HashMap::new();vars.insert("branch", "");- let result = expand_template("echo {{ branch }}", &vars, true, &test.repo).unwrap();+ let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();// Empty string is shell-escaped to ''assert_eq!(result, "echo ''");@@ -172,7 +183,7 @@ fn test_expand_template_unicode_in_branch() {let test = test_repo();// Unicode characters in branch name are shell-escapedlet vars = vars_with_branch("feature-\u{1F680}");- let result = expand_template("echo {{ branch }}", &vars, true, &test.repo).unwrap();+ let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();// Unicode is preserved but quoted for shell safetyassert_eq!(result, "echo 'feature-\u{1F680}'");@@ -184,7 +195,14 @@ fn test_expand_template_backslash_in_branch() {// Use {{ branch | sanitize }} to replace backslashes with dashes// Note: shell_escape=false to test sanitize filter in isolationlet vars = vars_with_branch("feature\\branch");- let result = expand_template("path/{{ branch | sanitize }}", &vars, false, &test.repo).unwrap();+ let result = expand_template(+ "path/{{ branch | sanitize }}",+ &vars,+ false,+ &test.repo,+ "test",+ )+ .unwrap();// Backslashes are replaced with dashes by sanitize filterassert_eq!(result, "path/feature-branch");@@ -202,6 +220,7 @@ fn test_expand_template_multiple_replacements() {&vars,true,&test.repo,+ "test",).unwrap();@@ -213,7 +232,7 @@ fn test_expand_template_curly_braces_without_variables() {let test = test_repo();// Just curly braces, not variableslet vars: HashMap<&str, &str> = HashMap::new();- let result = expand_template("echo {}", &vars, true, &test.repo).unwrap();+ let result = expand_template("echo {}", &vars, true, &test.repo, "test").unwrap();assert_eq!(result, "echo {}");}@@ -223,7 +242,14 @@ fn test_expand_template_nested_curly_braces() {let test = test_repo();// Nested braces - minijinja doesn't support {{{ syntax, use literal curly braces insteadlet vars = vars_with_branch("main");- let result = expand_template("echo {{ '{' ~ branch ~ '}' }}", &vars, true, &test.repo).unwrap();+ let result = expand_template(+ "echo {{ '{' ~ branch ~ '}' }}",+ &vars,+ true,+ &test.repo,+ "test",+ )+ .unwrap();// Renders as {main}assert_eq!(result, "echo {main}");@@ -257,7 +283,7 @@ fn snapshot_shell_escaping_special_chars() {let mut results = Vec::new();for (name, branch) in test_cases {let vars = vars_with_branch(branch);- let result = expand_template("echo {{ branch }}", &vars, true, &test.repo).unwrap();+ let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();results.push((name, branch, result));}@@ -279,7 +305,7 @@ fn snapshot_shell_escaping_quotes() {let mut results = Vec::new();for (name, branch) in test_cases {let vars = vars_with_branch(branch);- let result = expand_template("echo {{ branch }}", &vars, true, &test.repo).unwrap();+ let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();results.push((name, branch, result));}@@ -308,6 +334,7 @@ fn snapshot_shell_escaping_paths() {&vars,true,&test.repo,+ "test",).unwrap();results.push((name, path, result));@@ -347,7 +374,7 @@ fn snapshot_complex_templates() {vars.insert("main_worktree", "/repo/path");vars.insert("worktree", "/path with spaces/wt");vars.insert("target", "main; rm -rf /");- let result = expand_template(template, &vars, true, &test.repo).unwrap();+ let result = expand_template(template, &vars, true, &test.repo, "test").unwrap();results.push((name, template, branch, result));}@@ -362,8 +389,14 @@ fn test_expand_template_literal_normal() {let mut vars = HashMap::new();vars.insert("main_worktree", "myrepo");vars.insert("branch", "feature");- let result =- expand_template("{{ main_worktree }}.{{ branch }}", &vars, false, &test.repo).unwrap();+ let result = expand_template(+ "{{ main_worktree }}.{{ branch }}",+ &vars,+ false,+ &test.repo,+ "test",+ )+ .unwrap();assert_eq!(result, "myrepo.feature");}@@ -374,8 +407,14 @@ fn test_expand_template_literal_unicode_no_escaping() {let mut vars = HashMap::new();vars.insert("main_worktree", "myrepo");vars.insert("branch", "test-\u{2282}");- let result =- expand_template("{{ main_worktree }}.{{ branch }}", &vars, false, &test.repo).unwrap();+ let result = expand_template(+ "{{ main_worktree }}.{{ branch }}",+ &vars,+ false,+ &test.repo,+ "test",+ )+ .unwrap();// Path should contain literal unicode, NO quotesassert_eq!(result, "myrepo.test-\u{2282}");assert!(@@ -391,8 +430,14 @@ fn test_expand_template_literal_spaces_no_escaping() {let mut vars = HashMap::new();vars.insert("main_worktree", "my repo");vars.insert("branch", "feature name");- let result =- expand_template("{{ main_worktree }}.{{ branch }}", &vars, false, &test.repo).unwrap();+ let result = expand_template(+ "{{ main_worktree }}.{{ branch }}",+ &vars,+ false,+ &test.repo,+ "test",+ )+ .unwrap();// No shell quotes around spacesassert_eq!(result, "my repo.feature name");assert!(@@ -413,6 +458,7 @@ fn test_expand_template_literal_sanitizes_slashes() {&vars,false,&test.repo,+ "test",).unwrap();assert_eq!(result, "myrepo.feature-nested-branch");@@ -428,8 +474,8 @@ fn test_expand_template_literal_vs_escaped_unicode() {vars.insert("branch", "test-\u{2282}");let template = "{{ main_worktree }}.{{ branch }}";- let literal_result = expand_template(template, &vars, false, &test.repo).unwrap();- let escaped_result = expand_template(template, &vars, true, &test.repo).unwrap();+ let literal_result = expand_template(template, &vars, false, &test.repo, "test").unwrap();+ let escaped_result = expand_template(template, &vars, true, &test.repo, "test").unwrap();// Literal has no quotesassert_eq!(literal_result, "myrepo.test-\u{2282}");diff --git a/src/config/user.rs b/src/config/user.rsindex b1b1297b3..d554c491d 100644--- a/src/config/user.rs+++ b/src/config/user.rs@@ -469,7 +469,7 @@ impl WorktrunkConfig {vars.insert("main_worktree", main_worktree);vars.insert("repo", main_worktree);vars.insert("branch", branch);- expand_template(&self.worktree_path(), &vars, false, repo)+ expand_template(&self.worktree_path(), &vars, false, repo, "worktree-path")}/// Execute a mutation under an exclusive file lock.diff --git a/src/main.rs b/src/main.rsindex 52fe89451..bdff28495 100644--- a/src/main.rs+++ b/src/main.rs@@ -145,9 +145,6 @@ fn main() {set_config_path(path);}- // Initialize verbose level for output module- output::set_verbose_level(cli.verbose);-// Configure logging based on --verbose flag or RUST_LOG env var// When -vv is set, also write logs to .git/wt-logs/verbose.logif cli.verbose >= 2 {@@ -158,7 +155,10 @@ fn main() {let verbose_level = cli.verbose;let command_line = std::env::args().collect::<Vec<_>>().join(" ");- // -vv takes precedence over RUST_LOG: use Builder::new() to ignore env var+ // Set global verbosity level for styled verbose output+ output::set_verbosity(verbose_level);++ // -vv enables debug logging via env_logger; -v uses styled output (not logging)// Otherwise, respect RUST_LOG (defaulting to off)let mut builder = if cli.verbose >= 2 {let mut b = env_logger::Builder::new();@@ -843,9 +843,10 @@ fn main() {.collect();// Expand template variables in command (shell_escape: true for safety)- let expanded_cmd = expand_template(&cmd, &vars, true, &repo).map_err(|e| {- anyhow::anyhow!("Failed to expand --execute template: {}", e)- })?;+ let expanded_cmd =+ expand_template(&cmd, &vars, true, &repo, "--execute command").map_err(+ |e| anyhow::anyhow!("Failed to expand --execute template: {}", e),+ )?;// Append any trailing args (after --) to the execute command// Each arg is also expanded, then shell-escaped@@ -855,9 +856,10 @@ fn main() {let expanded_args: Result<Vec<_>, _> = execute_args.iter().map(|arg| {- expand_template(arg, &vars, false, &repo).map_err(|e| {- anyhow::anyhow!("Failed to expand argument template: {}", e)- })+ expand_template(arg, &vars, false, &repo, "--execute argument")+ .map_err(|e| {+ anyhow::anyhow!("Failed to expand argument template: {}", e)+ })}).collect();let escaped_args: Vec<_> = expanded_args?diff --git a/src/output/global.rs b/src/output/global.rsindex 1686a8554..3b02d8eb5 100644--- a/src/output/global.rs+++ b/src/output/global.rs@@ -36,6 +36,11 @@ use worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR;use worktrunk::shell_exec::ShellConfig;use worktrunk::styling::{eprintln, stderr};+// Re-export set_verbosity from the library's styling module.+// This ensures the binary and library share the same global state.+// Library code (like expansion.rs) accesses verbosity() directly from styling.+pub use worktrunk::styling::set_verbosity;+/// Global output state, lazily initialized on first access.////// Uses `OnceLock<Mutex<T>>` pattern:@@ -47,34 +52,6 @@ use worktrunk::styling::{eprintln, stderr};/// unreachable - the lock is only held for trivial Option assignments that cannot panic.static OUTPUT_STATE: OnceLock<Mutex<OutputState>> = OnceLock::new();-/// Global verbose level, set once from CLI flag at startup.-static VERBOSE_LEVEL: OnceLock<u8> = OnceLock::new();--/// Set the global verbose level from CLI flag.-///-/// Called once from main() after parsing args. If not called, defaults to 0.-pub fn set_verbose_level(level: u8) {- VERBOSE_LEVEL.set(level).ok();-}--/// Get the verbose level (0 = default, 1 = -v, 2+ = -vv).-// TODO(verbose-output): Reserved for showing extra details in command output.-// See commit e13776c "reserve -v for future use".-#[allow(dead_code)]-pub fn verbose_level() -> u8 {- VERBOSE_LEVEL.get().copied().unwrap_or(0)-}--/// Check if single -v was passed (show extra details).-///-/// Returns true when verbose level is 1 or higher.-// TODO(verbose-output): Reserved for showing extra details in command output.-// See commit e13776c "reserve -v for future use".-#[allow(dead_code)]-pub fn is_verbose() -> bool {- verbose_level() >= 1-}-#[derive(Default)]struct OutputState {/// Path to the directive file (from WORKTRUNK_DIRECTIVE_FILE env var)diff --git a/src/output/mod.rs b/src/output/mod.rsindex 9ab599098..fe25e60d1 100644--- a/src/output/mod.rs+++ b/src/output/mod.rs@@ -33,12 +33,9 @@ pub(crate) mod handlers;pub(crate) mod shell_integration;// Re-export the public API-// TODO(verbose-output): verbose_level, is_verbose reserved per commit e13776c-#[allow(unused_imports)]pub(crate) use global::{- blank, change_directory, execute, flush, is_shell_integration_active, is_verbose,- post_hook_display_path, pre_hook_display_path, print, set_verbose_level, stdout,- terminate_output, verbose_level,+ blank, change_directory, execute, flush, is_shell_integration_active, post_hook_display_path,+ pre_hook_display_path, print, set_verbosity, stdout, terminate_output,};// Re-export output handlerspub(crate) use handlers::{diff --git a/src/styling/mod.rs b/src/styling/mod.rsindex e71b83589..3bb18bb28 100644--- a/src/styling/mod.rs+++ b/src/styling/mod.rs@@ -36,6 +36,32 @@ pub use hyperlink::{Stream, hyperlink_stdout, supports_hyperlinks};pub use line::{StyledLine, StyledString, truncate_visible};pub use suggest::suggest_command;+// ============================================================================+// Verbosity+// ============================================================================++use std::sync::atomic::{AtomicU8, Ordering};++/// Global verbosity level, set at startup.+/// 0 = normal, 1 = verbose (-v), 2+ = debug (-vv)+static VERBOSITY: AtomicU8 = AtomicU8::new(0);++/// Set the global verbosity level.+///+/// Call this once at startup after parsing CLI arguments.+pub fn set_verbosity(level: u8) {+ VERBOSITY.store(level, Ordering::Relaxed);+}++/// Get the current verbosity level.+///+/// - 0: normal (no verbose output)+/// - 1: verbose (`-v`) - nice styled output for templates, etc.+/// - 2+: debug (`-vv`) - full debug logging+pub fn verbosity() -> u8 {+ VERBOSITY.load(Ordering::Relaxed)+}+/// Get terminal width, or `usize::MAX` if detection fails.////// Prefers direct terminal size detection over COLUMNS environment variable,diff --git a/tests/integration_tests/doc_templates.rs b/tests/integration_tests/doc_templates.rsindex be4954cac..a3f4397cc 100644--- a/tests/integration_tests/doc_templates.rs+++ b/tests/integration_tests/doc_templates.rs@@ -39,19 +39,19 @@ fn test_doc_basic_variables(repo: TestRepo) {// Each variable substitutes correctlyassert_eq!(- expand_template("{{ repo }}", &vars, false, &repository).unwrap(),+ expand_template("{{ repo }}", &vars, false, &repository, "test").unwrap(),"myproject");assert_eq!(- expand_template("{{ branch }}", &vars, false, &repository).unwrap(),+ expand_template("{{ branch }}", &vars, false, &repository, "test").unwrap(),"feature/auth");assert_eq!(- expand_template("{{ worktree }}", &vars, false, &repository).unwrap(),+ expand_template("{{ worktree }}", &vars, false, &repository, "test").unwrap(),"/home/user/myproject.feature-auth");assert_eq!(- expand_template("{{ default_branch }}", &vars, false, &repository).unwrap(),+ expand_template("{{ default_branch }}", &vars, false, &repository, "test").unwrap(),"main");}@@ -69,14 +69,14 @@ fn test_doc_sanitize_filter(repo: TestRepo) {// From docs: {{ branch | sanitize }} replaces / and \ with -vars.insert("branch", "feature/foo");assert_eq!(- expand_template("{{ branch | sanitize }}", &vars, false, &repository).unwrap(),+ expand_template("{{ branch | sanitize }}", &vars, false, &repository, "test").unwrap(),"feature-foo","sanitize should replace / with -");vars.insert("branch", "user\\task");assert_eq!(- expand_template("{{ branch | sanitize }}", &vars, false, &repository).unwrap(),+ expand_template("{{ branch | sanitize }}", &vars, false, &repository, "test").unwrap(),"user-task","sanitize should replace \\ with -");@@ -84,7 +84,7 @@ fn test_doc_sanitize_filter(repo: TestRepo) {// Nested pathsvars.insert("branch", "user/feature/task");assert_eq!(- expand_template("{{ branch | sanitize }}", &vars, false, &repository).unwrap(),+ expand_template("{{ branch | sanitize }}", &vars, false, &repository, "test").unwrap(),"user-feature-task","sanitize should handle multiple slashes");@@ -103,7 +103,14 @@ fn test_doc_sanitize_db_filter(repo: TestRepo) {// From docs: {{ branch | sanitize_db }} transforms to database-safe identifier// Output includes a 3-character hash suffix for uniquenessvars.insert("branch", "feature/auth-oauth2");- let result = expand_template("{{ branch | sanitize_db }}", &vars, false, &repository).unwrap();+ let result = expand_template(+ "{{ branch | sanitize_db }}",+ &vars,+ false,+ &repository,+ "test",+ )+ .unwrap();assert!(result.starts_with("feature_auth_oauth2_"),"sanitize_db should replace non-alphanumeric with _ and lowercase, got: {result}"@@ -111,7 +118,14 @@ fn test_doc_sanitize_db_filter(repo: TestRepo) {// Leading digits get underscore prefixvars.insert("branch", "123-bug-fix");- let result = expand_template("{{ branch | sanitize_db }}", &vars, false, &repository).unwrap();+ let result = expand_template(+ "{{ branch | sanitize_db }}",+ &vars,+ false,+ &repository,+ "test",+ )+ .unwrap();assert!(result.starts_with("_123_bug_fix_"),"sanitize_db should prefix leading digits with _, got: {result}"@@ -119,7 +133,14 @@ fn test_doc_sanitize_db_filter(repo: TestRepo) {// Uppercase conversionvars.insert("branch", "UPPERCASE.Branch");- let result = expand_template("{{ branch | sanitize_db }}", &vars, false, &repository).unwrap();+ let result = expand_template(+ "{{ branch | sanitize_db }}",+ &vars,+ false,+ &repository,+ "test",+ )+ .unwrap();assert!(result.starts_with("uppercase_branch_"),"sanitize_db should convert to lowercase, got: {result}"@@ -127,7 +148,14 @@ fn test_doc_sanitize_db_filter(repo: TestRepo) {// Consecutive underscores collapsedvars.insert("branch", "a--b//c");- let result = expand_template("{{ branch | sanitize_db }}", &vars, false, &repository).unwrap();+ let result = expand_template(+ "{{ branch | sanitize_db }}",+ &vars,+ false,+ &repository,+ "test",+ )+ .unwrap();assert!(result.starts_with("a_b_c_"),"sanitize_db should collapse consecutive underscores, got: {result}"@@ -135,9 +163,23 @@ fn test_doc_sanitize_db_filter(repo: TestRepo) {// Different inputs that would otherwise collide get different suffixesvars.insert("branch", "a-b");- let result1 = expand_template("{{ branch | sanitize_db }}", &vars, false, &repository).unwrap();+ let result1 = expand_template(+ "{{ branch | sanitize_db }}",+ &vars,+ false,+ &repository,+ "test",+ )+ .unwrap();vars.insert("branch", "a_b");- let result2 = expand_template("{{ branch | sanitize_db }}", &vars, false, &repository).unwrap();+ let result2 = expand_template(+ "{{ branch | sanitize_db }}",+ &vars,+ false,+ &repository,+ "test",+ )+ .unwrap();assert_ne!(result1, result2,"a-b and a_b should produce different outputs"@@ -152,7 +194,14 @@ fn test_doc_sanitize_db_truncation(repo: TestRepo) {// Truncates to 63 characters (PostgreSQL limit)let long_branch = "a".repeat(100);vars.insert("branch", long_branch.as_str());- let result = expand_template("{{ branch | sanitize_db }}", &vars, false, &repository).unwrap();+ let result = expand_template(+ "{{ branch | sanitize_db }}",+ &vars,+ false,+ &repository,+ "test",+ )+ .unwrap();assert_eq!(result.len(),63,@@ -171,7 +220,14 @@ fn test_doc_hash_port_filter(repo: TestRepo) {vars.insert("branch", "feature-foo");let repository = Repository::at(repo.root_path()).unwrap();- let result = expand_template("{{ branch | hash_port }}", &vars, false, &repository).unwrap();+ let result = expand_template(+ "{{ branch | hash_port }}",+ &vars,+ false,+ &repository,+ "test",+ )+ .unwrap();let port: u16 = result.parse().expect("hash_port should produce a number");assert!(@@ -180,7 +236,14 @@ fn test_doc_hash_port_filter(repo: TestRepo) {);// Deterministic- let result2 = expand_template("{{ branch | hash_port }}", &vars, false, &repository).unwrap();+ let result2 = expand_template(+ "{{ branch | hash_port }}",+ &vars,+ false,+ &repository,+ "test",+ )+ .unwrap();assert_eq!(result, result2, "hash_port should be deterministic");}@@ -207,6 +270,7 @@ fn test_doc_hash_port_concatenation_precedence(repo: TestRepo) {&vars,false,&repository,+ "test",).unwrap();let port_with_parens: u16 = with_parens.parse().unwrap();@@ -224,6 +288,7 @@ fn test_doc_hash_port_concatenation_precedence(repo: TestRepo) {&vars,false,&repository,+ "test",).unwrap();@@ -258,6 +323,7 @@ fn test_doc_hash_port_repo_branch_concatenation(repo: TestRepo) {&vars,false,&repository,+ "test",).unwrap();let port: u16 = result.parse().unwrap();@@ -290,7 +356,7 @@ fn test_doc_example_docker_postgres(repo: TestRepo) {-p {{ ('db-' ~ branch) | hash_port }}:5432 \postgres:16"#;- let result = expand_template(template, &vars, false, &repository).unwrap();+ let result = expand_template(template, &vars, false, &repository, "test").unwrap();// Check the container name uses sanitized branchassert!(@@ -318,7 +384,7 @@ fn test_doc_example_database_url(repo: TestRepo) {let template = "DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ repo }}";- let result = expand_template(template, &vars, false, &repository).unwrap();+ let result = expand_template(template, &vars, false, &repository, "test").unwrap();let expected_port = hash_port("db-feature");assert_eq!(@@ -338,7 +404,7 @@ fn test_doc_example_dev_server(repo: TestRepo) {let template = "npm run dev -- --host {{ branch }}.lvh.me --port {{ branch | hash_port }}";- let result = expand_template(template, &vars, false, &repository).unwrap();+ let result = expand_template(template, &vars, false, &repository, "test").unwrap();let expected_port = hash_port("feature-auth");assert_eq!(@@ -359,7 +425,7 @@ fn test_doc_example_worktree_path_sanitize(repo: TestRepo) {let template = "{{ main_worktree }}.{{ branch | sanitize }}";- let result = expand_template(template, &vars, false, &repository).unwrap();+ let result = expand_template(template, &vars, false, &repository, "test").unwrap();assert_eq!(result, "/home/user/project.feature-user-auth");}@@ -373,7 +439,14 @@ fn test_doc_hash_port_empty_string(repo: TestRepo) {let mut vars = HashMap::new();vars.insert("branch", "");- let result = expand_template("{{ branch | hash_port }}", &vars, false, &repository).unwrap();+ let result = expand_template(+ "{{ branch | hash_port }}",+ &vars,+ false,+ &repository,+ "test",+ )+ .unwrap();let port: u16 = result.parse().unwrap();assert!(@@ -388,7 +461,8 @@ fn test_doc_sanitize_no_slashes(repo: TestRepo) {let mut vars = HashMap::new();vars.insert("branch", "simple-branch");- let result = expand_template("{{ branch | sanitize }}", &vars, false, &repository).unwrap();+ let result =+ expand_template("{{ branch | sanitize }}", &vars, false, &repository, "test").unwrap();assert_eq!(result, "simple-branch","sanitize should be no-op without slashes"@@ -407,6 +481,7 @@ fn test_doc_combined_filters(repo: TestRepo) {&vars,false,&repository,+ "test",).unwrap();let port: u16 = result.parse().unwrap();@@ -430,6 +505,7 @@ fn test_worktree_path_of_branch_function_registered(repo: TestRepo) {&vars,false,&repository,+ "test",);assert_eq!(result.unwrap(), "");}diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rsindex 628157dc4..58cfc63c9 100644--- a/tests/integration_tests/post_start_commands.rs+++ b/tests/integration_tests/post_start_commands.rs@@ -1,7 +1,7 @@use crate::common::{- TestRepo, make_snapshot_cmd, repo, repo_with_remote, resolve_git_common_dir, set_temp_home_env,- setup_snapshot_settings, wait_for_file, wait_for_file_content, wait_for_file_count,- wait_for_file_lines, wait_for_valid_json,+ TestRepo, make_snapshot_cmd, make_snapshot_cmd_with_global_flags, repo, repo_with_remote,+ resolve_git_common_dir, set_temp_home_env, setup_snapshot_settings, wait_for_file,+ wait_for_file_content, wait_for_file_count, wait_for_file_lines, wait_for_valid_json,};use insta::assert_snapshot;use insta_cmd::assert_cmd_snapshot;@@ -198,6 +198,45 @@ approved-commands = [);}+#[rstest]+fn test_post_create_verbose_template_expansion(repo: TestRepo) {+ // Test that -v shows template expansion for post-create hooks+ repo.write_project_config(+ r#"[post-create]+setup = "echo 'Setting up {{ branch | sanitize }} in {{ worktree_path }}'"+"#,+ );++ repo.commit("Add config with templates");++ // Pre-approve commands+ repo.write_test_config(+ r#"worktree-path = "../{{ repo }}.{{ branch | sanitize }}"++[projects."../origin"]+approved-commands = [+ "echo 'Setting up {{ branch | sanitize }} in {{ worktree_path }}'",+]+"#,+ );++ // Create isolated HOME to ensure test determinism+ let temp_home = tempfile::TempDir::new().unwrap();++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd_with_global_flags(+ &repo,+ "switch",+ &["--create", "verbose-hooks"],+ None,+ &["-v"],+ );+ set_temp_home_env(&mut cmd, temp_home.path());+ assert_cmd_snapshot!("post_create_verbose_template_expansion", cmd);+ });+}+#[rstest]fn test_post_create_default_branch_template(repo: TestRepo) {// Create project config with default_branch template variable@@ -320,33 +359,75 @@ fn test_post_create_upstream_template(#[from(repo_with_remote)] repo: TestRepo).expect("failed to push main");// Create project config with upstream template variable+ // Note: {{ upstream }} errors when the new branch has no upstream tracking.+ // The new feature branch won't have an upstream until it's pushed with -u.+ // This test verifies the error case - see test_post_create_upstream_conditional for the fix.repo.write_project_config(r#"post-create = "echo 'Upstream: {{ upstream }}' > upstream.txt""#);repo.commit("Add config with upstream template");- // Create a feature branch based on main (which has upstream tracking)- // The new branch will inherit upstream since it's created from main+ // Create a feature branch - it won't have upstream tracking configured yetsnapshot_switch("post_create_upstream_template",&repo,&["--create", "feature", "--yes"],);- // Verify template expansion actually worked+ // Hook command should have errored due to undefined `upstream` variable+ // (new branches don't have upstream tracking until pushed with -u)+ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");+ let upstream_file = worktree_path.join("upstream.txt");++ assert!(+ !upstream_file.exists(),+ "upstream.txt should NOT have been created (command errored)"+ );+}++#[rstest]+fn test_post_create_upstream_conditional(#[from(repo_with_remote)] repo: TestRepo) {+ // Push main to set up tracking+ repo.git_command()+ .args(["push", "-u", "origin", "main"])+ .output()+ .expect("failed to push main");++ // Create project config with conditional upstream check+ // Using {% if not upstream %} allows safe handling of undefined variables+ repo.write_project_config(+ r#"post-create = "{% if not upstream %}echo 'no-upstream' > upstream.txt{% else %}echo '{{ upstream }}' > upstream.txt{% endif %}""#,+ );++ repo.commit("Add config with conditional upstream");++ // Pre-approve the command+ repo.write_test_config(+ r#"[projects."../origin"]+approved-commands = ["{% if not upstream %}echo 'no-upstream' > upstream.txt{% else %}echo '{{ upstream }}' > upstream.txt{% endif %}"]+"#,+ );++ // Create a feature branch - it won't have upstream tracking configured yet+ snapshot_switch(+ "post_create_upstream_conditional",+ &repo,+ &["--create", "feature", "--yes"],+ );++ // Verify the conditional worked - new branch has no upstream, so "no-upstream" should be writtenlet worktree_path = repo.root_path().parent().unwrap().join("repo.feature");let upstream_file = worktree_path.join("upstream.txt");assert!(upstream_file.exists(),- "upstream.txt should have been created in the worktree"+ "upstream.txt should have been created (conditional worked)");let contents = fs::read_to_string(&upstream_file).unwrap();- // New branches don't have upstream until pushed - upstream should be empty- assert!(- contents.contains("Upstream: "),- "Should have upstream line (possibly empty), got: {}",- contents+ assert_eq!(+ contents.trim(),+ "no-upstream",+ "Should contain 'no-upstream' since feature branch has no upstream tracking");}diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 932e04f73..382f9cc36 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -1,7 +1,7 @@use crate::common::{- TestRepo, configure_directive_file, directive_file, make_snapshot_cmd, repo, repo_with_remote,- set_temp_home_env, setup_home_snapshot_settings, setup_snapshot_settings, temp_home,- wt_command,+ TestRepo, configure_directive_file, directive_file, make_snapshot_cmd,+ make_snapshot_cmd_with_global_flags, repo, repo_with_remote, set_temp_home_env,+ setup_home_snapshot_settings, setup_snapshot_settings, temp_home, wt_command,};use insta_cmd::assert_cmd_snapshot;use rstest::rstest;@@ -410,7 +410,8 @@ fn test_switch_execute_template_base(repo: TestRepo) {#[rstest]fn test_switch_execute_template_base_without_create(mut repo: TestRepo) {- // Test that {{ base }} is empty when switching to existing worktree (no --create)+ // Test that {{ base }} errors when switching to existing worktree (no --create)+ // The `base` variable is only available during branch creationrepo.add_worktree("existing");snapshot_switch("switch_execute_template_base_without_create",@@ -506,6 +507,55 @@ fn test_switch_execute_arg_template_error(repo: TestRepo) {);}+// Verbose mode tests+#[rstest]+fn test_switch_execute_verbose_template_expansion(repo: TestRepo) {+ // Test that -v shows template expansion details+ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd_with_global_flags(+ &repo,+ "switch",+ &[+ "--create",+ "verbose-test",+ "--execute",+ "echo 'branch={{ branch }}'",+ ],+ None,+ &["-v"],+ );+ assert_cmd_snapshot!("switch_execute_verbose_template", cmd);+ });+}++#[rstest]+fn test_switch_execute_verbose_multiline_template(repo: TestRepo) {+ // Test that -v shows multiline template expansion with proper formatting+ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ // Multiline template with conditional+ let multiline_template = r#"{% if branch %}+echo 'branch={{ branch }}'+echo 'repo={{ repo }}'+{% endif %}"#;++ let mut cmd = make_snapshot_cmd_with_global_flags(+ &repo,+ "switch",+ &[+ "--create",+ "multiline-test",+ "--execute",+ multiline_template,+ ],+ None,+ &["-v"],+ );+ assert_cmd_snapshot!("switch_execute_verbose_multiline_template", cmd);+ });+}+// --no-verify flag tests#[rstest]fn test_switch_no_config_commands_execute_still_runs(repo: TestRepo) {diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_conditional.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_conditional.snapnew file mode 100644index 000000000..727904f31--- /dev/null+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_conditional.snap@@ -0,0 +1,44 @@+---+source: tests/integration_tests/post_start_commands.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - feature+ - "--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]"+ PATH: "[PATH]"+ RUST_LOG: warn+ SHELL: ""+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[36m◎[39m [36mRunning post-create project hook @ [1m_REPO_.feature[22m:[39m+[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'no-upstream'[0m[2m [0m[2m[36m>[0m[2m upstream.txt+[0m[32m✓[39m [32mCreated branch [1mfeature[22m from [1mmain[22m and worktree @ [1m_REPO_.feature[22m[39m+[2m↳[22m [2mTo customize worktree locations, run [90mwt config create[39m[22m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snapindex b4143d9ed..6928f448b 100644--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snap+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snap@@ -15,6 +15,7 @@ info: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@@ -30,14 +31,9 @@ info:WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"----success: true-exit_code: 0+success: false+exit_code: 1----- stdout ---------- stderr ------[36m◎[39m [36mRunning post-create project hook @ [1m_REPO_.feature[22m:[39m-[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'Upstream: '[0m[2m [0m[2m[36m>[0m[2m upstream.txt-[0m[32m✓[39m [32mCreated branch [1mfeature[22m from [1mmain[22m and worktree @ [1m_REPO_.feature[22m[39m-[2m↳[22m [2mTo customize worktree locations, run [90mwt config create[39m[22m-[33m▲[39m [33mCannot change directory — shell integration not installed[39m-[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22m+[31m✗[39m [31mFailed to expand command template 'echo 'Upstream: {{ upstream }}' > upstream.txt': Template render error: undefined value (in project post-create hook:1)[39mdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_verbose_template_expansion.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_verbose_template_expansion.snapnew file mode 100644index 000000000..9d160c718--- /dev/null+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_verbose_template_expansion.snap@@ -0,0 +1,48 @@+---+source: tests/integration_tests/post_start_commands.rs+info:+ program: wt+ args:+ - "-v"+ - switch+ - "--create"+ - verbose-hooks+ 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]"+ PATH: "[PATH]"+ RUST_LOG: warn+ SHELL: ""+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[2m○[22m Expanding [1mworktree-path[22m+[107m [0m ../{{ repo }}.{{ branch | sanitize }} [2m→[22m ../repo.verbose-hooks+[2m○[22m Expanding [1mproject:setup[22m+[107m [0m echo 'Setting up {{ branch | sanitize }} in {{ worktree_path }}' [2m→[22m echo 'Setting up verbose-hooks in _REPO_.verbose-hooks'+[36m◎[39m [36mRunning post-create [1mproject:setup[22m @ [1m_REPO_.verbose-hooks[22m:[39m+[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'Setting up verbose-hooks in _REPO_.verbose-hooks'[0m[2m+[0mSetting up verbose-hooks in _REPO_.verbose-hooks+[32m✓[39m [32mCreated branch [1mverbose-hooks[22m from [1mmain[22m and worktree @ [1m_REPO_.verbose-hooks[22m[39m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_arg_template_error.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_arg_template_error.snapindex e1b705668..5a8d803b5 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_arg_template_error.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_arg_template_error.snap@@ -44,4 +44,4 @@ exit_code: 1[2m↳[22m [2mTo customize worktree locations, run [90mwt config create[39m[22m[33m▲[39m [33mCannot change directory — shell integration not installed[39m[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22m-[31m✗[39m [31mFailed to expand argument template: Template syntax error: syntax error: unexpected end of input, expected end of variable block (in <string>:1)[39m+[31m✗[39m [31mFailed to expand argument template: Template syntax error: syntax error: unexpected end of input, expected end of variable block (in --execute argument:1)[39mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_template_base_without_create.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_template_base_without_create.snapindex 863dffcf0..d4c02a163 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_template_base_without_create.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_template_base_without_create.snap@@ -31,13 +31,11 @@ info:WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"----success: true-exit_code: 0+success: false+exit_code: 1----- stdout ------base=----- stderr -----[33m▲[39m [33mWorktree for [1mexisting[22m @ [1m_REPO_.existing[22m, but cannot change directory — shell integration not installed[39m[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22m-[36m◎[39m [36mExecuting (--execute) @ [1m_REPO_.existing[22m:[39m-[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'base='[0m[2m+[31m✗[39m [31mFailed to expand --execute template: Template render error: undefined value (in --execute command:1)[39mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_template_error.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_template_error.snapindex e5d7097c6..27e835b62 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_template_error.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_template_error.snap@@ -41,4 +41,4 @@ exit_code: 1[2m↳[22m [2mTo customize worktree locations, run [90mwt config create[39m[22m[33m▲[39m [33mCannot change directory — shell integration not installed[39m[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22m-[31m✗[39m [31mFailed to expand --execute template: Template syntax error: syntax error: unexpected end of input, expected end of variable block (in <string>:1)[39m+[31m✗[39m [31mFailed to expand --execute template: Template syntax error: syntax error: unexpected end of input, expected end of variable block (in --execute command:1)[39mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_verbose_multiline_template.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_verbose_multiline_template.snapnew file mode 100644index 000000000..1c17eff93--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_verbose_multiline_template.snap@@ -0,0 +1,61 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - "-v"+ - switch+ - "--create"+ - multiline-test+ - "--execute"+ - "{% if branch %}\necho 'branch={{ branch }}'\necho 'repo={{ repo }}'\n{% endif %}"+ 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]"+ PATH: "[PATH]"+ RUST_LOG: warn+ SHELL: ""+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----+branch=multiline-test+repo=repo++----- stderr -----+[2m○[22m Expanding [1mworktree-path[22m+[107m [0m ../{{ repo }}.{{ branch | sanitize }} [2m→[22m ../repo.multiline-test+[32m✓[39m [32mCreated branch [1mmultiline-test[22m from [1mmain[22m and worktree @ [1m_REPO_.multiline-test[22m[39m+[2m↳[22m [2mTo customize worktree locations, run [90mwt config create[39m[22m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22m+[2m○[22m Expanding [1m--execute command[22m+[107m [0m {% if branch %}+[107m [0m echo 'branch={{ branch }}'+[107m [0m echo 'repo={{ repo }}'+[107m [0m {% endif %}+[107m [0m [2m→[22m+[107m [0m+[107m [0m echo 'branch=multiline-test'+[107m [0m echo 'repo=repo'+[36m◎[39m [36mExecuting (--execute) @ [1m_REPO_.multiline-test[22m:[39m+[107m [0m [2m+[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'branch=multiline-test'[0m[2m+[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'repo=repo'[0m[2mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_verbose_template.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_verbose_template.snapnew file mode 100644index 000000000..5af5ca1c4--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_verbose_template.snap@@ -0,0 +1,51 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - "-v"+ - switch+ - "--create"+ - verbose-test+ - "--execute"+ - "echo 'branch={{ branch }}'"+ 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]"+ PATH: "[PATH]"+ RUST_LOG: warn+ SHELL: ""+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----+branch=verbose-test++----- stderr -----+[2m○[22m Expanding [1mworktree-path[22m+[107m [0m ../{{ repo }}.{{ branch | sanitize }} [2m→[22m ../repo.verbose-test+[32m✓[39m [32mCreated branch [1mverbose-test[22m from [1mmain[22m and worktree @ [1m_REPO_.verbose-test[22m[39m+[2m↳[22m [2mTo customize worktree locations, run [90mwt config create[39m[22m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22m+[2m○[22m Expanding [1m--execute command[22m+[107m [0m echo 'branch={{ branch }}' [2m→[22m echo 'branch=verbose-test'+[36m◎[39m [36mExecuting (--execute) @ [1m_REPO_.verbose-test[22m:[39m+[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'branch=verbose-test'[0m[2m