Skip to content

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

feat: typed TemplateExpandError with actionable error messages (#1041)

Maximilian Roosfcc802101c29
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 7df8066d8..53bce0597 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -171,14 +171,7 @@ fn expand_commands(
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
- )
- })?;
+ let expanded_str = expand_template(&cmd.template, &vars, true, ctx.repo, &template_name)?;
// Build per-command JSON with hook_type and hook_name
let mut cmd_context = base_context.clone();
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rs
index 9e05f27eb..a52f1c136 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -78,8 +78,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, "for-each command")
- .map_err(|e| anyhow::anyhow!("Template expansion failed: {e}"))?;
+ let command = expand_template(&command_template, &vars, true, &repo, "for-each command")?;
// Build JSON context for stdin
let context_json = serde_json::to_string(&context_map)
diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rs
index 67bf181bf..0abadc0bc 100644
--- a/src/commands/handle_switch.rs
+++ b/src/commands/handle_switch.rs
@@ -225,8 +225,7 @@ pub fn handle_switch(
.collect();
// Expand template variables in command (shell_escape: true for safety)
- let expanded_cmd = expand_template(cmd, &vars, true, &repo, "--execute command")
- .map_err(|e| anyhow::anyhow!("Failed to expand --execute template: {}", e))?;
+ let expanded_cmd = expand_template(cmd, &vars, true, &repo, "--execute command")?;
// Append any trailing args (after --) to the execute command
// Each arg is also expanded, then shell-escaped
@@ -235,10 +234,7 @@ pub fn handle_switch(
} else {
let expanded_args: Result<Vec<_>, _> = execute_args
.iter()
- .map(|arg| {
- expand_template(arg, &vars, false, &repo, "--execute argument")
- .map_err(|e| anyhow::anyhow!("Failed to expand argument template: {}", e))
- })
+ .map(|arg| expand_template(arg, &vars, false, &repo, "--execute argument"))
.collect();
let escaped_args: Vec<_> = expanded_args?
.iter()
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index 6b0226052..c3a791476 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -714,5 +714,5 @@ fn expand_command_template(template: &str, ctx: &CommandContext, hook_type: Hook
// Use the standard template expansion (shell-escaped)
// On any error, show both the template and error message
worktrunk::config::expand_template(template, &vars, true, ctx.repo, "hook preview")
- .unwrap_or_else(|err| format!("# Template error: {}\n{}", err, template))
+ .unwrap_or_else(|err| format!("# {}\n{}", err.message, template))
}
diff --git a/src/commands/relocate.rs b/src/commands/relocate.rs
index 463ae3a2b..6bf2ac788 100644
--- a/src/commands/relocate.rs
+++ b/src/commands/relocate.rs
@@ -156,9 +156,13 @@ pub fn gather_candidates(
}
Err(e) => {
// Template expansion failed - warn user so they can fix config
- let header = cformat!("Skipping <bold>{branch}</> due to template error:");
- let detail = format_with_gutter(&e.to_string(), None);
- eprintln!("{}\n{}", warning_message(header), detail);
+ eprintln!(
+ "{}",
+ warning_message(cformat!(
+ "Skipping <bold>{branch}</> due to template error:"
+ ))
+ );
+ eprintln!("{}", e);
template_errors += 1;
}
}
diff --git a/src/commands/worktree/resolve.rs b/src/commands/worktree/resolve.rs
index b1677ff28..f3a830a19 100644
--- a/src/commands/worktree/resolve.rs
+++ b/src/commands/worktree/resolve.rs
@@ -107,9 +107,7 @@ pub fn compute_worktree_path(
})?;
let project = repo.project_identifier().ok();
- let expanded_path = config
- .format_path(repo_name, branch, repo, project.as_deref())
- .map_err(|e| anyhow::anyhow!("Failed to format worktree path: {e}"))?;
+ let expanded_path = config.format_path(repo_name, branch, repo, project.as_deref())?;
Ok(repo_root.join(expanded_path).normalize())
}
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 477bc2359..d21987321 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -11,13 +11,15 @@
use std::borrow::Cow;
use color_print::cformat;
-use minijinja::{Environment, UndefinedBehavior, Value};
+use minijinja::{Environment, ErrorKind, UndefinedBehavior, Value};
use regex::Regex;
use shell_escape::escape;
use crate::git::Repository;
use crate::path::to_posix_path;
-use crate::styling::{eprintln, format_with_gutter, info_message, verbosity};
+use crate::styling::{
+ eprintln, error_message, format_with_gutter, hint_message, info_message, verbosity,
+};
/// Known template variables available in hook commands.
///
@@ -206,6 +208,94 @@ pub fn redact_credentials(s: &str) -> String {
CREDENTIAL_URL.with(|re| re.replace(s, "${1}[REDACTED]@").into_owned())
}
+/// Error from template expansion with rich context for diagnostics.
+///
+/// Produced by [`expand_template`] when a template fails to parse or render.
+/// Contains structured data for styled display in `main.rs` (via downcast)
+/// and a `message` field for callers that embed errors in other output.
+#[derive(Debug)]
+pub struct TemplateExpandError {
+ /// Plain-text error summary for callers that embed errors in styled messages.
+ pub message: String,
+ /// The failing template line (if identifiable).
+ pub source_line: Option<String>,
+ /// Variable names available in this template context.
+ pub available_vars: Vec<String>,
+}
+
+impl std::fmt::Display for TemplateExpandError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut parts = vec![error_message(&self.message).to_string()];
+ if let Some(ref line) = self.source_line {
+ parts.push(format_with_gutter(line, None));
+ }
+ if !self.available_vars.is_empty() {
+ parts.push(
+ hint_message(cformat!(
+ "Available variables: <bright-black>{}</>",
+ self.available_vars.join(", ")
+ ))
+ .to_string(),
+ );
+ }
+ write!(f, "{}", parts.join("\n"))
+ }
+}
+
+impl std::error::Error for TemplateExpandError {}
+
+/// Build a [`TemplateExpandError`] from a minijinja error, the original template
+/// source, the template name (for error messages), and the available variable names.
+/// the template name, and the available variable names.
+///
+/// Message format: `Failed to expand {name}: {kind}[: {detail}] [@ line {n}]`
+///
+/// ```text
+/// Failed to expand {name}: {kind}[: {detail}] [@ line {n}]
+/// │ │ │ │ │
+/// │ │ │ │ └─ e.line() from minijinja
+/// │ │ │ └─ e.detail() from minijinja (None for UndefinedError)
+/// │ │ └─ e.kind() from minijinja ("undefined value", "syntax error")
+/// │ └─ `name` param passed by caller
+/// └─ hardcoded prefix
+/// ```
+fn build_template_error(
+ e: &minijinja::Error,
+ template: &str,
+ name: &str,
+ available_vars: Vec<String>,
+) -> TemplateExpandError {
+ let lines: Vec<&str> = template.lines().collect();
+ let line_num = e.line();
+ let source_line =
+ line_num.and_then(|n| lines.get(n.saturating_sub(1)).copied().map(String::from));
+
+ // Build message: "Failed to expand {name}: {kind}[: {detail}] [@ line {n}]"
+ // e.g. "Failed to expand --execute command: undefined value @ line 1"
+ let detail = match e.detail() {
+ Some(detail) => format!("{}: {detail}", e.kind()),
+ None => e.kind().to_string(),
+ };
+ let is_undefined = e.kind() == ErrorKind::UndefinedError;
+
+ // minijinja always provides a line number for syntax and render errors
+ let message = match line_num {
+ Some(n) => format!("Failed to expand {name}: {detail} @ line {n}"),
+ None => format!("Failed to expand {name}: {detail}"),
+ };
+
+ TemplateExpandError {
+ message,
+ source_line,
+ // Only show available vars for undefined errors (actionable hint)
+ available_vars: if is_undefined {
+ available_vars
+ } else {
+ Vec::new()
+ },
+ }
+}
+
/// Expand a template with variable substitution.
///
/// # Arguments
@@ -231,7 +321,7 @@ pub fn expand_template(
shell_escape: bool,
repo: &Repository,
name: &str,
-) -> Result<String, String> {
+) -> Result<String, TemplateExpandError> {
// Build context map with raw values (shell escaping is applied at output time via formatter)
let mut context = HashMap::new();
for (key, value) in vars {
@@ -306,13 +396,18 @@ pub fn expand_template(
);
}
+ // Parse errors are always SyntaxError, never UndefinedError — no need for available_vars
let tmpl = env
.template_from_named_str(name, template)
- .map_err(|e| format!("Template syntax error: {}", e))?;
+ .map_err(|e| build_template_error(&e, template, name, Vec::new()))?;
let result = tmpl
.render(minijinja::Value::from_object(context))
- .map_err(|e| format!("Template render error: {}", e))?;
+ .map_err(|e| {
+ let mut keys: Vec<String> = vars.keys().map(|k| k.to_string()).collect();
+ keys.sort();
+ build_template_error(&e, template, name, keys)
+ })?;
// -vv: Full debug logging with result
// Redact credentials from result to prevent leaking tokens in logs
@@ -524,10 +619,12 @@ mod tests {
"static text"
);
// Undefined variables now error in SemiStrict mode
+ let err = expand_template("no {{ variables }} here", &empty, false, &test.repo, "test")
+ .unwrap_err();
assert!(
- expand_template("no {{ variables }} here", &empty, false, &test.repo, "test")
- .unwrap_err()
- .contains("undefined")
+ err.message.contains("undefined value"),
+ "got: {}",
+ err.message
);
}
@@ -556,12 +653,45 @@ mod tests {
fn test_expand_template_errors() {
let test = test_repo();
let vars = HashMap::new();
+ let err = expand_template("{{ unclosed", &vars, false, &test.repo, "test").unwrap_err();
+ assert!(err.message.contains("syntax error"), "got: {}", err.message);
+ assert!(expand_template("{{ 1 + }}", &vars, false, &test.repo, "test").is_err());
+
+ // Display impl renders source line but no available vars hint for syntax errors
+ let display = err.to_string();
+ assert!(display.contains("{{ unclosed"), "should show source line");
assert!(
- expand_template("{{ unclosed", &vars, false, &test.repo, "test")
- .unwrap_err()
- .contains("syntax error")
+ !display.contains("Available variables:"),
+ "syntax errors should not show available vars"
);
- assert!(expand_template("{{ 1 + }}", &vars, false, &test.repo, "test").is_err());
+ }
+
+ #[test]
+ fn test_expand_template_undefined_var_details() {
+ let test = test_repo();
+ let mut vars = HashMap::new();
+ vars.insert("branch", "main");
+ vars.insert("remote", "origin");
+
+ let err =
+ expand_template("echo {{ target }}", &vars, false, &test.repo, "test").unwrap_err();
+ assert!(
+ err.message.contains("undefined value"),
+ "should mention undefined value: {}",
+ err.message
+ );
+ assert!(err.available_vars.contains(&"branch".to_string()));
+ assert!(err.available_vars.contains(&"remote".to_string()));
+ assert_eq!(err.source_line.as_deref(), Some("echo {{ target }}"));
+
+ // Display impl renders source line and available vars hint
+ let display = err.to_string();
+ assert!(
+ display.contains("echo {{ target }}"),
+ "should show source line"
+ );
+ assert!(display.contains("Available variables:"), "should show hint");
+ assert!(display.contains("branch"), "should list available vars");
}
#[test]
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 4d244d408..062e7b275 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -83,8 +83,8 @@ pub use deprecation::normalize_template_vars;
pub use deprecation::write_migration_file;
pub use deprecation::{DEPRECATED_SECTION_KEYS, key_belongs_in, warn_unknown_fields};
pub use expansion::{
- DEPRECATED_TEMPLATE_VARS, TEMPLATE_VARS, expand_template, redact_credentials,
- sanitize_branch_name, sanitize_db, short_hash,
+ DEPRECATED_TEMPLATE_VARS, TEMPLATE_VARS, TemplateExpandError, expand_template,
+ redact_credentials, sanitize_branch_name, sanitize_db, short_hash,
};
pub use hooks::HooksConfig;
pub use project::{
diff --git a/src/config/test.rs b/src/config/test.rs
index 1af648184..c22ecc532 100644
--- a/src/config/test.rs
+++ b/src/config/test.rs
@@ -162,7 +162,12 @@ fn test_expand_template_missing_variable() {
let result = expand_template("echo {{ undefined }}", &vars, true, &test.repo, "test");
assert!(result.is_err());
- assert!(result.unwrap_err().contains("undefined"));
+ let err = result.unwrap_err();
+ assert!(
+ err.message.contains("undefined value"),
+ "got: {}",
+ err.message
+ );
}
#[test]
diff --git a/src/config/user/accessors.rs b/src/config/user/accessors.rs
index 8413fe927..05827d5eb 100644
--- a/src/config/user/accessors.rs
+++ b/src/config/user/accessors.rs
@@ -6,7 +6,7 @@
use std::collections::HashMap;
use crate::config::HooksConfig;
-use crate::config::expansion::expand_template;
+use crate::config::expansion::{TemplateExpandError, expand_template};
use super::UserConfig;
use super::merge::{Merge, merge_optional};
@@ -162,7 +162,7 @@ impl UserConfig {
branch: &str,
repo: &crate::git::Repository,
project: Option<&str>,
- ) -> Result<String, String> {
+ ) -> Result<String, TemplateExpandError> {
let template = match project {
Some(p) => self.worktree_path_for_project(p),
None => self.worktree_path(),
diff --git a/src/main.rs b/src/main.rs
index f0a5a8bad..6e9a4b690 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1048,6 +1048,8 @@ fn main() {
eprintln!("{}", err);
} else if let Some(err) = e.downcast_ref::<worktrunk::git::HookErrorWithHint>() {
eprintln!("{}", err);
+ } else if let Some(err) = e.downcast_ref::<worktrunk::config::TemplateExpandError>() {
+ eprintln!("{}", err);
} else {
// Anyhow error formatting:
// - With context: show context as header, root cause in gutter
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index f2c470bbf..c61885be9 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -801,7 +801,7 @@ fn test_standalone_hook_post_remove_invalid_template(repo: TestRepo) {
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
- stderr.contains("Failed to expand command template"),
+ stderr.contains("syntax error"),
"Error should mention template expansion failure, got: {stderr}"
);
}
diff --git a/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_syntax_error.snap b/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_syntax_error.snap
index 1b4e20c4e..7b1554636 100644
--- a/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_syntax_error.snap
+++ b/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_syntax_error.snap
@@ -45,5 +45,5 @@ exit_code: 0
PROJECT HOOKS _REPO_/.config/wt.toml
❯ pre-commit broken: (requires approval)
-  # Template error: Template syntax error: syntax error: unexpected end of input, expected end of variable block (in hook preview:1)
+  # Failed to expand hook preview: syntax error: unexpected end of input, expected end of variable block @ line 1
  echo {{ branch
diff --git a/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_undefined_var.snap b/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_undefined_var.snap
index 183fcedae..da708896b 100644
--- a/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_undefined_var.snap
+++ b/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_undefined_var.snap
@@ -45,5 +45,5 @@ exit_code: 0
PROJECT HOOKS _REPO_/.config/wt.toml
❯ pre-commit optional-var: (requires approval)
-  # Template error: Template render error: undefined value (in hook preview:1)
+  # Failed to expand hook preview: undefined value @ line 1
  echo {{ base }}
diff --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.snap
index 8f094f632..cce2939ce 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
@@ -40,4 +40,6 @@ exit_code: 1
----- stdout -----
----- stderr -----
-✗ Failed to expand command template 'echo 'Upstream: {{ upstream }}' > upstream.txt': Template render error: undefined value (in project post-create hook:1)
+✗ Failed to expand project post-create hook: undefined value @ line 1
+  echo 'Upstream: {{ upstream }}' > upstream.txt
+↳ Available variables: base, base_worktree_path, branch, commit, default_branch, main_worktree, main_worktree_path, primary_worktree_path, remote, remote_url, repo, repo_path, repo_root, short_commit, worktree, worktree_name, worktree_path
diff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_template_error.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_template_error.snap
index bdaca66a7..d1b42335a 100644
--- a/tests/snapshots/integration__integration_tests__step_relocate__relocate_template_error.snap
+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_template_error.snap
@@ -40,5 +40,7 @@ exit_code: 0
----- stderr -----
▲ Skipping feature due to template error:
-  Failed to format worktree path: Template render error: undefined value (in worktree-path:1)
+✗ Failed to expand worktree-path: undefined value @ line 1
+  {{ nonexistent_variable }}
+↳ Available variables: branch, main_worktree, repo, repo_path
○ No relocations performed; 1 skipped due to template error
diff --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.snap
index f0d8a3305..df96026ae 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
@@ -48,4 +48,5 @@ exit_code: 1
↳ To customize worktree locations, run wt config create
▲ Cannot change directory — shell integration not installed
↳ To enable automatic cd, run wt config shell install
-✗ Failed to expand argument template: Template syntax error: syntax error: unexpected end of input, expected end of variable block (in --execute argument:1)
+✗ Failed to expand --execute argument: syntax error: unexpected end of input, expected end of variable block @ line 1
+  invalid={{ unclosed
diff --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.snap
index 43d60e159..c8aafc9fb 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
@@ -42,4 +42,6 @@ exit_code: 1
----- stderr -----
▲ Worktree for existing @ _REPO_.existing, but cannot change directory — shell integration not installed
↳ To enable automatic cd, run wt config shell install
-✗ Failed to expand --execute template: Template render error: undefined value (in --execute command:1)
+✗ Failed to expand --execute command: undefined value @ line 1
+  echo 'base={{ base }}'
+↳ Available variables: branch, commit, default_branch, main_worktree, main_worktree_path, primary_worktree_path, remote, remote_url, repo, repo_path, repo_root, short_commit, worktree, worktree_name, worktree_path
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_template_error.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_template_error.snap
index 17124f67a..5d5e41d53 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
@@ -45,4 +45,5 @@ exit_code: 1
↳ To customize worktree locations, run wt config create
▲ Cannot change directory — shell integration not installed
↳ To enable automatic cd, run wt config shell install
-✗ Failed to expand --execute template: Template syntax error: syntax error: unexpected end of input, expected end of variable block (in --execute command:1)
+✗ Failed to expand --execute command: syntax error: unexpected end of input, expected end of variable block @ line 1
+  echo {{ unclosed