Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(switch): validate templates before worktree creation (#1500)
Maximilian Roos0d4ddd1ab56a
diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rsindex 99e986f6b..49c2a4a66 100644--- a/src/commands/handle_switch.rs+++ b/src/commands/handle_switch.rs@@ -5,7 +5,7 @@ use std::path::Path;use anyhow::Context;use worktrunk::HookType;-use worktrunk::config::{UserConfig, expand_template};+use worktrunk::config::{UserConfig, expand_template, validate_template};use worktrunk::git::{GitError, Repository, SwitchSuggestionCtx, current_or_recover};use worktrunk::styling::{eprintln, info_message};@@ -221,6 +221,11 @@ pub fn handle_switch(// If user declines, skip hooks but continue with worktree operationlet hooks_approved = approve_switch_hooks(&repo, config, &plan, yes, verify)?;+ // Pre-flight: validate all templates before mutation (worktree creation).+ // Catches syntax errors and undefined variables early so a broken template+ // doesn't leave behind a half-created worktree that blocks re-running.+ validate_switch_templates(&repo, config, &plan, execute, execute_args, hooks_approved)?;+// Execute the validated planlet (result, branch_info) = execute_switch(&repo, plan, config, yes, hooks_approved)?;@@ -318,3 +323,76 @@ pub fn handle_switch(Ok(())}++/// Validate all templates that will be expanded after worktree creation.+///+/// Catches syntax errors and undefined variable references *before* the+/// irreversible worktree creation, so a broken template doesn't leave behind+/// a worktree that blocks re-running the command.+///+/// This is a best-effort pre-flight check: it catches definite errors (syntax,+/// unknown variables) but cannot catch failures from conditional variables that+/// are absent at expansion time (e.g., `upstream` when no tracking is configured).+/// Such late failures propagate as normal errors — no panics.+///+/// Validates:+/// - `--execute` command template (if present)+/// - `--execute` trailing arg templates (if present)+/// - Hook templates (post-create, post-start, post-switch) from user and project config+fn validate_switch_templates(+ repo: &Repository,+ config: &UserConfig,+ plan: &SwitchPlan,+ execute: Option<&str>,+ execute_args: &[String],+ hooks_approved: bool,+) -> anyhow::Result<()> {+ // Validate --execute template and trailing args+ if let Some(cmd) = execute {+ validate_template(cmd, repo, "--execute command")?;+ for arg in execute_args {+ validate_template(arg, repo, "--execute argument")?;+ }+ }++ // Validate hook templates only when hooks will actually run+ if !hooks_approved {+ return Ok(());+ }++ let project_config = repo.load_project_config()?;+ let user_hooks = config.hooks(repo.project_identifier().ok().as_deref());++ let hook_types: &[HookType] = if plan.is_create() {+ &[+ HookType::PostCreate,+ HookType::PostStart,+ HookType::PostSwitch,+ ]+ } else {+ &[HookType::PostSwitch]+ };++ for &hook_type in hook_types {+ let configs = [+ ("user", user_hooks.get(hook_type)),+ (+ "project",+ project_config.as_ref().and_then(|c| c.hooks.get(hook_type)),+ ),+ ];+ for (source, cfg) in configs {+ if let Some(cfg) = cfg {+ for cmd in cfg.commands() {+ let name = match &cmd.name {+ Some(n) => format!("{source} {hook_type}:{n}"),+ None => format!("{source} {hook_type} hook"),+ };+ validate_template(&cmd.template, repo, &name)?;+ }+ }+ }+ }++ Ok(())+}diff --git a/src/config/expansion.rs b/src/config/expansion.rsindex 1eb8bf988..9a89e416b 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -298,6 +298,84 @@ fn build_template_error(}}+/// Set up a minijinja environment with worktrunk's custom filters and functions.+///+/// Shared by [`expand_template`] and [`validate_template`] to ensure both use+/// the same filters, functions, and undefined-behavior settings.+fn setup_template_env(repo: &Repository) -> Environment<'static> {+ let 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);++ // Register custom filters+ env.add_filter("sanitize", |value: Value| -> String {+ sanitize_branch_name(value.as_str().unwrap_or_default())+ });+ env.add_filter("sanitize_db", |value: Value| -> String {+ sanitize_db(value.as_str().unwrap_or_default())+ });+ env.add_filter("hash_port", |value: String| string_to_port(&value));++ // Register worktree_path_of_branch function for looking up branch worktree paths.+ // Returns raw paths — shell escaping is applied by the formatter at output time.+ let repo_clone = repo.clone();+ env.add_function("worktree_path_of_branch", move |branch: String| -> String {+ repo_clone+ .worktree_for_branch(&branch)+ .ok()+ .flatten()+ .map(|p| to_posix_path(&p.to_string_lossy()))+ .unwrap_or_default()+ });++ env+}++/// Validate that a template can be expanded without errors.+///+/// Performs a trial expansion with placeholder values for all known template variables+/// ([`TEMPLATE_VARS`] + [`DEPRECATED_TEMPLATE_VARS`]). Catches syntax errors and+/// undefined variable references *before* irreversible operations like worktree creation.+///+/// This is deliberately more permissive than real expansion: all known variables are+/// provided, even conditional ones (`upstream`, `commit`, etc.) that may be absent at+/// expansion time. This means a template like `{{ upstream }}` passes validation but+/// could fail later if no upstream tracking is configured. This is an acceptable+/// trade-off — the alternative (predicting which optional variables will be available)+/// would be fragile and context-dependent.+///+/// No verbose logging is performed — this is a pre-flight check, not the real expansion.+pub fn validate_template(+ template: &str,+ repo: &Repository,+ name: &str,+) -> Result<(), TemplateExpandError> {+ let all_vars = TEMPLATE_VARS.iter().chain(DEPRECATED_TEMPLATE_VARS.iter());+ let context: HashMap<String, minijinja::Value> = all_vars+ .map(|&k| (k.to_string(), minijinja::Value::from("PLACEHOLDER")))+ .collect();++ let env = setup_template_env(repo);++ let tmpl = env+ .template_from_named_str(name, template)+ .map_err(|e| build_template_error(&e, template, name, Vec::new()))?;++ tmpl.render(minijinja::Value::from_object(context))+ .map_err(|e| {+ let mut keys: Vec<String> = TEMPLATE_VARS+ .iter()+ .chain(DEPRECATED_TEMPLATE_VARS.iter())+ .map(|k| k.to_string())+ .collect();+ keys.sort();+ build_template_error(&e, template, name, keys)+ })?;++ Ok(())+}+/// Expand a template with variable substitution.////// # Arguments@@ -333,11 +411,7 @@ pub fn expand_template();}- // Render template with minijinja- let 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);+ let mut env = setup_template_env(repo);if shell_escape {// Preserve trailing newlines in templates (important for multiline shell commands)env.set_keep_trailing_newline(true);@@ -357,27 +431,6 @@ pub fn expand_template(});}- // Register custom filters- env.add_filter("sanitize", |value: Value| -> String {- sanitize_branch_name(value.as_str().unwrap_or_default())- });- env.add_filter("sanitize_db", |value: Value| -> String {- sanitize_db(value.as_str().unwrap_or_default())- });- env.add_filter("hash_port", |value: String| string_to_port(&value));-- // Register worktree_path_of_branch function for looking up branch worktree paths.- // Returns raw paths — shell escaping is applied by the formatter at output time.- let repo_clone = repo.clone();- env.add_function("worktree_path_of_branch", move |branch: String| -> String {- repo_clone- .worktree_for_branch(&branch)- .ok()- .flatten()- .map(|p| to_posix_path(&p.to_string_lossy()))- .unwrap_or_default()- });-// Cache verbosity level for consistent behavior within this calllet verbose = verbosity();@@ -1053,4 +1106,57 @@ mod tests {"https://[REDACTED]@github.com/owner/repo.git?ref=main");}++ #[test]+ fn test_validate_template_valid() {+ let test = test_repo();++ // Static text+ assert!(validate_template("echo hello", &test.repo, "test").is_ok());++ // Known variables+ assert!(validate_template("{{ branch }}", &test.repo, "test").is_ok());+ assert!(validate_template("{{ repo }}/{{ branch }}", &test.repo, "test").is_ok());++ // Filters+ assert!(validate_template("{{ branch | sanitize }}", &test.repo, "test").is_ok());+ assert!(validate_template("{{ branch | sanitize_db }}", &test.repo, "test").is_ok());+ assert!(validate_template("{{ branch | hash_port }}", &test.repo, "test").is_ok());++ // Conditionals with optional vars+ assert!(+ validate_template(+ "{% if upstream %}{{ upstream }}{% endif %}",+ &test.repo,+ "test"+ )+ .is_ok()+ );++ // Deprecated vars still valid+ assert!(validate_template("{{ main_worktree }}", &test.repo, "test").is_ok());+ }++ #[test]+ fn test_validate_template_syntax_error() {+ let test = test_repo();++ let err = validate_template("{{ unclosed", &test.repo, "test").unwrap_err();+ assert!(err.message.contains("syntax error"), "got: {}", err.message);+ }++ #[test]+ fn test_validate_template_undefined_var() {+ let test = test_repo();++ let err = validate_template("{{ nonexistent_var }}", &test.repo, "test").unwrap_err();+ assert!(+ err.message.contains("undefined value"),+ "got: {}",+ err.message+ );+ // Should list available vars in hint+ assert!(!err.available_vars.is_empty(), "should list available vars");+ assert!(err.available_vars.contains(&"branch".to_string()));+ }}diff --git a/src/config/mod.rs b/src/config/mod.rsindex fce9b3904..d7d73cd1b 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -86,7 +86,7 @@ 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, TemplateExpandError, expand_template,- redact_credentials, sanitize_branch_name, sanitize_db, short_hash,+ redact_credentials, sanitize_branch_name, sanitize_db, short_hash, validate_template,};pub use hooks::HooksConfig;pub use project::{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.snapindex b2890a302..bd474af49 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,9 +48,5 @@ exit_code: 1----- stdout ---------- stderr ------[32m✓[39m [32mCreated branch [1marg-error-test[22m from [1mmain[22m and worktree @ [1m_REPO_.arg-error-test[22m[39m-[2m↳[22m [2mTo customize worktree locations, run [4mwt config create[24m[22m-[33m▲[39m [33mCannot change directory — shell integration not installed[39m-[2m↳[22m [2mTo enable automatic cd, run [4mwt config shell install[24m[22m[31m✗[39m [31mFailed to expand --execute argument: syntax error: unexpected end of input, expected end of variable block @ line 1[39m[107m [0m invalid={{ uncloseddiff --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 09c819154..e495779ac 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,9 +45,5 @@ exit_code: 1----- stdout ---------- stderr ------[32m✓[39m [32mCreated branch [1merror-test[22m from [1mmain[22m and worktree @ [1m_REPO_.error-test[22m[39m-[2m↳[22m [2mTo customize worktree locations, run [4mwt config create[24m[22m-[33m▲[39m [33mCannot change directory — shell integration not installed[39m-[2m↳[22m [2mTo enable automatic cd, run [4mwt config shell install[24m[22m[31m✗[39m [31mFailed to expand --execute command: syntax error: unexpected end of input, expected end of variable block @ line 1[39m[107m [0m echo {{ unclosed