Skip to content

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

Refactor template expansion to use unified function signature

Maximilian Roosaca5523c96a4
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 6dfdb0a39..1d1fca8c5 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -72,6 +72,7 @@ pub fn build_hook_context(
let mut map = HashMap::new();
map.insert("repo".into(), repo_name.into());
+ map.insert("main_worktree".into(), repo_name.into()); // Alias for repo
map.insert("branch".into(), sanitize_branch_name(ctx.branch_or_head()));
map.insert("worktree".into(), worktree.into());
map.insert("worktree_name".into(), worktree_name.into());
@@ -125,14 +126,8 @@ fn expand_commands(
let base_context = build_hook_context(ctx, extra_vars);
- let repo_name = ctx
- .repo_root
- .file_name()
- .and_then(|n| n.to_str())
- .unwrap_or("unknown");
-
// Convert to &str references for expand_template
- let extras_ref: HashMap<&str, &str> = base_context
+ let vars: HashMap<&str, &str> = base_context
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
@@ -140,16 +135,13 @@ fn expand_commands(
let mut result = Vec::new();
for cmd in commands {
- let expanded_str =
- expand_template(&cmd.template, repo_name, ctx.branch_or_head(), &extras_ref).map_err(
- |e| {
- anyhow::anyhow!(
- "Failed to expand command template '{}': {}",
- cmd.template,
- e
- )
- },
- )?;
+ let expanded_str = expand_template(&cmd.template, &vars, true).map_err(|e| {
+ anyhow::anyhow!(
+ "Failed to expand command template '{}': {}",
+ cmd.template,
+ e
+ )
+ })?;
// 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 e91fc3e4d..3efb9d3ae 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -71,18 +71,13 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {
let context_map = build_hook_context(&ctx, &[]);
// Convert to &str references for expand_template
- let extras_ref: HashMap<&str, &str> = context_map
+ let vars: HashMap<&str, &str> = context_map
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
- let repo_name = repo_root
- .file_name()
- .and_then(|n| n.to_str())
- .unwrap_or("unknown");
-
- // Expand template with full context
- let command = expand_template(&command_template, repo_name, branch, &extras_ref)
+ // Expand template with full context (shell-escaped)
+ let command = expand_template(&command_template, &vars, true)
.map_err(|e| anyhow::anyhow!("Template expansion failed: {e}"))?;
// Build JSON context for stdin
diff --git a/src/commands/standalone.rs b/src/commands/standalone.rs
index 9cf611c5e..8975c18c9 100644
--- a/src/commands/standalone.rs
+++ b/src/commands/standalone.rs
@@ -900,19 +900,12 @@ fn expand_command_template(template: &str, ctx: &CommandContext, hook_type: Hook
_ => Vec::new(),
};
let template_ctx = build_hook_context(ctx, &extra_vars);
-
- // Use the standard template expansion
- worktrunk::config::expand_template(
- template,
- ctx.repo_root
- .file_name()
- .and_then(|n| n.to_str())
- .unwrap_or("unknown"),
- ctx.branch_or_head(),
- &template_ctx
- .iter()
- .map(|(k, v)| (k.as_str(), v.as_str()))
- .collect(),
- )
- .unwrap_or_else(|_| template.to_string())
+ let vars: std::collections::HashMap<&str, &str> = template_ctx
+ .iter()
+ .map(|(k, v)| (k.as_str(), v.as_str()))
+ .collect();
+
+ // Use the standard template expansion (shell-escaped)
+ worktrunk::config::expand_template(template, &vars, true)
+ .unwrap_or_else(|_| template.to_string())
}
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 295e1fef7..cba7eb34e 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -1,9 +1,13 @@
//! Template expansion utilities for worktrunk
//!
-//! Uses minijinja for all template rendering with automatic shell escaping.
+//! Uses minijinja for template rendering. Single generic function with escaping flag:
+//! - `shell_escape: true` — Shell-escaped for safe command execution
+//! - `shell_escape: false` — Literal values for filesystem paths
+//!
//! All templates support Jinja2 syntax including filters, conditionals, and loops.
use minijinja::Environment;
+use std::collections::HashMap;
/// Sanitize a branch name for use in filesystem paths.
///
@@ -22,67 +26,61 @@ pub fn sanitize_branch_name(branch: &str) -> String {
branch.replace(['/', '\\'], "-")
}
-/// Expand template variables using minijinja
-///
-/// All templates support:
-/// - `{{ main_worktree }}` - Main worktree directory name
-/// - `{{ branch }}` - Branch name (sanitized: slashes → dashes)
-/// - `{{ repo }}` - Repository name (alias for main_worktree for consistency)
+/// Expand a template with variable substitution.
///
-/// Additional variables can be provided via the `extra` parameter.
-///
-/// Variables are automatically shell-escaped for safe use in commands.
-/// Use the `|e` or `|escape` filter for additional escaping if needed.
+/// # Arguments
+/// * `template` - Template string using Jinja2 syntax (e.g., `{{ branch }}`)
+/// * `vars` - Variables to substitute. Callers should sanitize branch names with
+/// [`sanitize_branch_name`] before inserting.
+/// * `shell_escape` - If true, shell-escape all values for safe command execution.
+/// If false, substitute values literally (for filesystem paths).
///
/// # Examples
/// ```
-/// use worktrunk::config::expand_template;
+/// use worktrunk::config::{expand_template, sanitize_branch_name};
/// use std::collections::HashMap;
///
-/// // Simple variable substitution
-/// let result = expand_template("path/{{ main_worktree }}/{{ branch }}", "myrepo", "feature/foo", &HashMap::new()).unwrap();
-/// assert_eq!(result, "path/myrepo/feature-foo");
+/// // For shell commands (escaped)
+/// let branch = sanitize_branch_name("feature/foo");
+/// let mut vars = HashMap::new();
+/// vars.insert("branch", branch.as_str());
+/// vars.insert("repo", "myrepo");
+/// let cmd = expand_template("echo {{ branch }} in {{ repo }}", &vars, true).unwrap();
+/// assert_eq!(cmd, "echo feature-foo in myrepo");
///
-/// // Using conditionals
-/// let result = expand_template("{% if branch == 'main' %}production{% else %}development{% endif %}", "myrepo", "main", &HashMap::new()).unwrap();
-/// assert_eq!(result, "production");
+/// // For filesystem paths (literal)
+/// let branch = sanitize_branch_name("feature/foo");
+/// let mut vars = HashMap::new();
+/// vars.insert("branch", branch.as_str());
+/// vars.insert("main_worktree", "myrepo");
+/// let path = expand_template("{{ main_worktree }}.{{ branch }}", &vars, false).unwrap();
+/// assert_eq!(path, "myrepo.feature-foo");
/// ```
pub fn expand_template(
template: &str,
- main_worktree: &str,
- branch: &str,
- extra: &std::collections::HashMap<&str, &str>,
+ vars: &HashMap<&str, &str>,
+ shell_escape: bool,
) -> Result<String, String> {
use shell_escape::escape;
use std::borrow::Cow;
- // Sanitize branch name by replacing path separators
- let safe_branch = sanitize_branch_name(branch);
-
- // Shell-escape all variables
- let escaped_worktree = escape(Cow::Borrowed(main_worktree)).to_string();
- let escaped_branch = escape(Cow::Borrowed(safe_branch.as_str())).to_string();
-
- // Build context map with shell-escaped values
- let mut context = std::collections::HashMap::new();
- context.insert("branch".to_string(), minijinja::Value::from(escaped_branch));
- context.insert(
- "main_worktree".to_string(),
- minijinja::Value::from(escaped_worktree.clone()),
- );
- context.insert("repo".to_string(), minijinja::Value::from(escaped_worktree));
-
- for (key, value) in extra {
- context.insert(
- key.to_string(),
- minijinja::Value::from(escape(Cow::Borrowed(*value)).to_string()),
- );
+ // Build context map, optionally shell-escaping values
+ let mut context = HashMap::new();
+ for (key, value) in vars {
+ let val = if shell_escape {
+ escape(Cow::Borrowed(*value)).to_string()
+ } else {
+ (*value).to_string()
+ };
+ context.insert(key.to_string(), minijinja::Value::from(val));
}
// Render template with minijinja
let mut env = Environment::new();
- // Preserve trailing newlines in templates (important for multiline shell commands)
- env.set_keep_trailing_newline(true);
+ if shell_escape {
+ // Preserve trailing newlines in templates (important for multiline shell commands)
+ env.set_keep_trailing_newline(true);
+ }
let tmpl = env
.template_from_str(template)
.map_err(|e| format!("Template syntax error: {}", e))?;
@@ -94,6 +92,7 @@ pub fn expand_template(
/// Expand command template variables using minijinja
///
/// Convenience function for expanding command templates with common variables.
+/// Shell-escapes all values for safe command execution.
///
/// Supported variables:
/// - `{{ repo }}` - Repository name
@@ -130,14 +129,18 @@ pub fn expand_command_template(
repo_root: &std::path::Path,
target_branch: Option<&str>,
) -> Result<String, String> {
- let mut extra = std::collections::HashMap::new();
+ let safe_branch = sanitize_branch_name(branch);
let worktree_str = worktree_path.to_string_lossy();
let repo_root_str = repo_root.to_string_lossy();
- extra.insert("worktree", worktree_str.as_ref());
- extra.insert("repo_root", repo_root_str.as_ref());
+
+ let mut vars = HashMap::new();
+ vars.insert("repo", repo_name);
+ vars.insert("branch", safe_branch.as_str());
+ vars.insert("worktree", worktree_str.as_ref());
+ vars.insert("repo_root", repo_root_str.as_ref());
if let Some(target) = target_branch {
- extra.insert("target", target);
+ vars.insert("target", target);
}
- expand_template(command, repo_name, branch, &extra)
+ expand_template(command, &vars, true)
}
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 554a50c47..c6371d931 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -554,13 +554,10 @@ task2 = "echo 'Task 2 running' > task2.txt"
fn test_expand_template_basic() {
use std::collections::HashMap;
- let result = expand_template(
- "../{{ main_worktree }}.{{ branch }}",
- "myrepo",
- "feature-x",
- &HashMap::new(),
- )
- .unwrap();
+ let mut vars = HashMap::new();
+ vars.insert("main_worktree", "myrepo");
+ vars.insert("branch", "feature-x");
+ let result = expand_template("../{{ main_worktree }}.{{ branch }}", &vars, true).unwrap();
assert_eq!(result, "../myrepo.feature-x");
}
@@ -568,22 +565,20 @@ task2 = "echo 'Task 2 running' > task2.txt"
fn test_expand_template_sanitizes_branch() {
use std::collections::HashMap;
- let result = expand_template(
- "{{ main_worktree }}/{{ branch }}",
- "myrepo",
- "feature/foo",
- &HashMap::new(),
- )
- .unwrap();
+ // Caller is responsible for sanitizing branch names
+ let branch = sanitize_branch_name("feature/foo");
+ let mut vars = HashMap::new();
+ vars.insert("main_worktree", "myrepo");
+ vars.insert("branch", branch.as_str());
+ let result = expand_template("{{ main_worktree }}/{{ branch }}", &vars, true).unwrap();
assert_eq!(result, "myrepo/feature-foo");
- let result = expand_template(
- ".worktrees/{{ main_worktree }}/{{ branch }}",
- "myrepo",
- "feat\\bar",
- &HashMap::new(),
- )
- .unwrap();
+ let branch = sanitize_branch_name("feat\\bar");
+ let mut vars = HashMap::new();
+ vars.insert("main_worktree", "myrepo");
+ vars.insert("branch", branch.as_str());
+ let result =
+ expand_template(".worktrees/{{ main_worktree }}/{{ branch }}", &vars, true).unwrap();
assert_eq!(result, ".worktrees/myrepo/feat-bar");
}
@@ -591,15 +586,14 @@ task2 = "echo 'Task 2 running' > task2.txt"
fn test_expand_template_with_extra_vars() {
use std::collections::HashMap;
- let mut extra = HashMap::new();
- extra.insert("worktree", "/path/to/worktree");
- extra.insert("repo_root", "/path/to/repo");
+ let mut vars = HashMap::new();
+ vars.insert("worktree", "/path/to/worktree");
+ vars.insert("repo_root", "/path/to/repo");
let result = expand_template(
"{{ repo_root }}/target -> {{ worktree }}/target",
- "myrepo",
- "main",
- &extra,
+ &vars,
+ true,
)
.unwrap();
assert_eq!(result, "/path/to/repo/target -> /path/to/worktree/target");
diff --git a/src/config/test.rs b/src/config/test.rs
index bb49b5bc0..25764e182 100644
--- a/src/config/test.rs
+++ b/src/config/test.rs
@@ -3,35 +3,32 @@
//! These tests target potential shell injection vulnerabilities and
//! edge cases in template variable substitution.
-use super::expand_template;
+use super::{expand_template, sanitize_branch_name};
use std::collections::HashMap;
+/// Helper to build vars with common fields
+fn vars_with_branch(branch: &str) -> HashMap<&str, &str> {
+ let mut vars = HashMap::new();
+ vars.insert("branch", branch);
+ vars.insert("main_worktree", "myrepo");
+ vars.insert("repo", "myrepo");
+ vars
+}
+
#[test]
fn test_expand_template_normal() {
- let extras = HashMap::new();
- let result = expand_template(
- "echo {{ branch }} {{ main_worktree }}",
- "myrepo",
- "feature",
- &extras,
- )
- .unwrap();
+ let branch = sanitize_branch_name("feature");
+ let vars = vars_with_branch(&branch);
+ let result = expand_template("echo {{ branch }} {{ main_worktree }}", &vars, true).unwrap();
assert_eq!(result, "echo feature myrepo");
}
#[test]
fn test_expand_template_branch_with_slashes() {
- // Bug hypothesis: Branch names with slashes are sanitized to dashes
- let extras = HashMap::new();
- let result = expand_template(
- "echo {{ branch }}",
- "myrepo",
- "feature/nested/branch",
- &extras,
- )
- .unwrap();
-
- // Line 459: safe_branch = branch.replace(['/', '\\'], "-")
+ // Caller is responsible for sanitizing branch names
+ let branch = sanitize_branch_name("feature/nested/branch");
+ let vars = vars_with_branch(&branch);
+ let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
assert_eq!(result, "echo feature-nested-branch");
}
@@ -40,8 +37,9 @@ fn test_expand_template_branch_with_slashes() {
#[cfg(unix)]
fn test_expand_template_branch_with_spaces() {
// Branch names with spaces are shell-escaped
- let extras = HashMap::new();
- let result = expand_template("echo {{ branch }}", "myrepo", "feature name", &extras).unwrap();
+ let branch = sanitize_branch_name("feature name");
+ let vars = vars_with_branch(&branch);
+ let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
// Shell-escaped with single quotes
assert_eq!(result, "echo 'feature name'");
@@ -51,9 +49,9 @@ fn test_expand_template_branch_with_spaces() {
#[cfg(unix)]
fn test_expand_template_branch_with_special_shell_chars() {
// Special shell characters are escaped
- let extras = HashMap::new();
- let result =
- expand_template("echo {{ branch }}", "myrepo", "feature$(whoami)", &extras).unwrap();
+ let branch = sanitize_branch_name("feature$(whoami)");
+ let vars = vars_with_branch(&branch);
+ let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
// Shell-escaped, prevents command substitution
assert_eq!(result, "echo 'feature$(whoami)'");
@@ -64,8 +62,9 @@ fn test_expand_template_branch_with_special_shell_chars() {
#[cfg(unix)]
fn test_expand_template_branch_with_backticks() {
// Backticks are escaped
- let extras = HashMap::new();
- let result = expand_template("echo {{ branch }}", "myrepo", "feature`id`", &extras).unwrap();
+ let branch = sanitize_branch_name("feature`id`");
+ let vars = vars_with_branch(&branch);
+ let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
assert_eq!(result, "echo 'feature`id`'");
}
@@ -74,8 +73,9 @@ fn test_expand_template_branch_with_backticks() {
#[cfg(unix)]
fn test_expand_template_branch_with_quotes() {
// Quotes are shell-escaped to prevent injection
- let extras = HashMap::new();
- let result = expand_template("echo '{{ branch }}'", "myrepo", "feature'test", &extras).unwrap();
+ let branch = sanitize_branch_name("feature'test");
+ let vars = vars_with_branch(&branch);
+ let result = expand_template("echo '{{ branch }}'", &vars, true).unwrap();
// Shell escapes single quotes as '\''
assert_eq!(result, "echo ''feature'\\''test''");
@@ -85,9 +85,10 @@ fn test_expand_template_branch_with_quotes() {
#[cfg(unix)]
fn test_expand_template_extra_vars_with_spaces() {
// Extra variables with spaces are shell-escaped
- let mut extras = HashMap::new();
- extras.insert("worktree", "/path with spaces/to/worktree");
- let result = expand_template("cd {{ worktree }}", "myrepo", "main", &extras).unwrap();
+ let branch = sanitize_branch_name("main");
+ let mut vars = vars_with_branch(&branch);
+ vars.insert("worktree", "/path with spaces/to/worktree");
+ let result = expand_template("cd {{ worktree }}", &vars, true).unwrap();
assert_eq!(result, "cd '/path with spaces/to/worktree'");
}
@@ -96,9 +97,10 @@ fn test_expand_template_extra_vars_with_spaces() {
#[cfg(unix)]
fn test_expand_template_extra_vars_with_dollar_sign() {
// Dollar signs are shell-escaped to prevent variable expansion
- let mut extras = HashMap::new();
- extras.insert("worktree", "/path/$USER/worktree");
- let result = expand_template("cd {{ worktree }}", "myrepo", "main", &extras).unwrap();
+ let branch = sanitize_branch_name("main");
+ let mut vars = vars_with_branch(&branch);
+ vars.insert("worktree", "/path/$USER/worktree");
+ let result = expand_template("cd {{ worktree }}", &vars, true).unwrap();
assert_eq!(result, "cd '/path/$USER/worktree'");
// Shell-escaped, prevents $USER from being expanded
@@ -108,47 +110,30 @@ fn test_expand_template_extra_vars_with_dollar_sign() {
#[cfg(unix)]
fn test_expand_template_extra_vars_with_command_substitution() {
// Special shell characters are shell-escaped to prevent injection
- let mut extras = HashMap::new();
- extras.insert("target", "main; rm -rf /");
- let result = expand_template("git merge {{ target }}", "myrepo", "feature", &extras).unwrap();
+ let branch = sanitize_branch_name("feature");
+ let mut vars = vars_with_branch(&branch);
+ vars.insert("target", "main; rm -rf /");
+ let result = expand_template("git merge {{ target }}", &vars, true).unwrap();
assert_eq!(result, "git merge 'main; rm -rf /'");
// Shell-escaped, prevents semicolon from being executed as command separator
}
#[test]
-fn test_expand_template_variable_collision() {
- // What if extra vars contain "branch"? With minijinja, extra vars added later override built-ins
- let mut extras = HashMap::new();
- extras.insert("branch", "hacked");
- let result = expand_template("echo {{ branch }}", "myrepo", "feature", &extras).unwrap();
-
- // Extra vars are added to context after built-ins, so they override
- assert_eq!(result, "echo hacked");
-}
+fn test_expand_template_variable_override() {
+ // Variables in the hashmap take precedence
+ let mut vars = HashMap::new();
+ vars.insert("branch", "overridden");
+ let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
-#[test]
-fn test_expand_template_extra_var_named_branch() {
- // What if we have both {{ branch }} in template and "branch" in extras?
- let mut extras = HashMap::new();
- extras.insert("branch", "extra-branch");
- let result = expand_template(
- "echo {{ branch }} from {{ branch }}",
- "myrepo",
- "main",
- &extras,
- )
- .unwrap();
-
- // Extra vars override built-ins, so both occurrences use "extra-branch"
- assert_eq!(result, "echo extra-branch from extra-branch");
+ assert_eq!(result, "echo overridden");
}
#[test]
fn test_expand_template_missing_variable() {
// What happens with undefined variables?
- let extras = HashMap::new();
- let result = expand_template("echo {{ undefined }}", "myrepo", "main", &extras).unwrap();
+ let vars: HashMap<&str, &str> = HashMap::new();
+ let result = expand_template("echo {{ undefined }}", &vars, true).unwrap();
// minijinja will render undefined variables as empty string
assert_eq!(result, "echo ");
@@ -157,8 +142,9 @@ fn test_expand_template_missing_variable() {
#[test]
#[cfg(unix)]
fn test_expand_template_empty_branch() {
- let extras = HashMap::new();
- let result = expand_template("echo {{ branch }}", "myrepo", "", &extras).unwrap();
+ let mut vars = HashMap::new();
+ vars.insert("branch", "");
+ let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
// Empty string is shell-escaped to ''
assert_eq!(result, "echo ''");
@@ -168,35 +154,36 @@ fn test_expand_template_empty_branch() {
#[cfg(unix)]
fn test_expand_template_unicode_in_branch() {
// Unicode characters in branch name are shell-escaped
- let extras = HashMap::new();
- let result = expand_template("echo {{ branch }}", "myrepo", "feature-🚀", &extras).unwrap();
+ let branch = sanitize_branch_name("feature-\u{1F680}");
+ let vars = vars_with_branch(&branch);
+ let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
// Unicode is preserved but quoted for shell safety
- assert_eq!(result, "echo 'feature-🚀'");
+ assert_eq!(result, "echo 'feature-\u{1F680}'");
}
#[test]
fn test_expand_template_backslash_in_branch() {
- // Windows-style path separators
- let extras = HashMap::new();
- let result =
- expand_template("echo {{ branch }}", "myrepo", "feature\\branch", &extras).unwrap();
+ // Windows-style path separators - caller sanitizes
+ let branch = sanitize_branch_name("feature\\branch");
+ let vars = vars_with_branch(&branch);
+ let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
- // Line 459: backslashes also replaced with dashes
+ // Backslashes are replaced with dashes by sanitize_branch_name
assert_eq!(result, "echo feature-branch");
}
#[test]
fn test_expand_template_multiple_replacements() {
- let mut extras = HashMap::new();
- extras.insert("worktree", "/path/to/wt");
- extras.insert("target", "develop");
+ let branch = sanitize_branch_name("feature");
+ let mut vars = vars_with_branch(&branch);
+ vars.insert("worktree", "/path/to/wt");
+ vars.insert("target", "develop");
let result = expand_template(
"cd {{ worktree }} && git merge {{ target }} from {{ branch }}",
- "myrepo",
- "feature",
- &extras,
+ &vars,
+ true,
)
.unwrap();
@@ -206,8 +193,8 @@ fn test_expand_template_multiple_replacements() {
#[test]
fn test_expand_template_curly_braces_without_variables() {
// Just curly braces, not variables
- let extras = HashMap::new();
- let result = expand_template("echo {}", "myrepo", "main", &extras).unwrap();
+ let vars: HashMap<&str, &str> = HashMap::new();
+ let result = expand_template("echo {}", &vars, true).unwrap();
assert_eq!(result, "echo {}");
}
@@ -215,9 +202,9 @@ fn test_expand_template_curly_braces_without_variables() {
#[test]
fn test_expand_template_nested_curly_braces() {
// Nested braces - minijinja doesn't support {{{ syntax, use literal curly braces instead
- let extras = HashMap::new();
- let result =
- expand_template("echo {{ '{' ~ branch ~ '}' }}", "myrepo", "main", &extras).unwrap();
+ let branch = sanitize_branch_name("main");
+ let vars = vars_with_branch(&branch);
+ let result = expand_template("echo {{ '{' ~ branch ~ '}' }}", &vars, true).unwrap();
// Renders as {main}
assert_eq!(result, "echo {main}");
@@ -232,8 +219,6 @@ fn test_expand_template_nested_curly_braces() {
#[test]
#[cfg(unix)]
fn snapshot_shell_escaping_special_chars() {
- let extras = HashMap::new();
-
// Test various shell special characters
let test_cases = vec![
("spaces", "feature name"),
@@ -250,9 +235,11 @@ fn snapshot_shell_escaping_special_chars() {
];
let mut results = Vec::new();
- for (name, branch) in test_cases {
- let result = expand_template("echo {{ branch }}", "myrepo", branch, &extras).unwrap();
- results.push((name, branch, result));
+ for (name, branch_raw) in test_cases {
+ let branch = sanitize_branch_name(branch_raw);
+ let vars = vars_with_branch(&branch);
+ let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
+ results.push((name, branch_raw, result));
}
insta::assert_yaml_snapshot!(results);
@@ -261,8 +248,6 @@ fn snapshot_shell_escaping_special_chars() {
#[test]
#[cfg(unix)]
fn snapshot_shell_escaping_quotes() {
- let extras = HashMap::new();
-
// Test quote handling
let test_cases = vec![
("single_quote", "feature'test"),
@@ -272,9 +257,11 @@ fn snapshot_shell_escaping_quotes() {
];
let mut results = Vec::new();
- for (name, branch) in test_cases {
- let result = expand_template("echo {{ branch }}", "myrepo", branch, &extras).unwrap();
- results.push((name, branch, result));
+ for (name, branch_raw) in test_cases {
+ let branch = sanitize_branch_name(branch_raw);
+ let vars = vars_with_branch(&branch);
+ let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
+ results.push((name, branch_raw, result));
}
insta::assert_yaml_snapshot!(results);
@@ -283,28 +270,22 @@ fn snapshot_shell_escaping_quotes() {
#[test]
#[cfg(unix)]
fn snapshot_shell_escaping_paths() {
- let mut extras = HashMap::new();
-
// Test path escaping with various special characters
let test_cases = vec![
("spaces", "/path with spaces/to/worktree"),
("dollar", "/path/$USER/worktree"),
("tilde", "~/worktree"),
("special_chars", "/path/to/worktree (new)"),
- ("unicode", "/path/to/🚀/worktree"),
+ ("unicode", "/path/to/\u{1F680}/worktree"),
];
let mut results = Vec::new();
for (name, path) in test_cases {
- extras.clear();
- extras.insert("worktree", path);
- let result = expand_template(
- "cd {{ worktree }} && echo {{ branch }}",
- "myrepo",
- "main",
- &extras,
- )
- .unwrap();
+ let branch = sanitize_branch_name("main");
+ let mut vars = vars_with_branch(&branch);
+ vars.insert("worktree", path);
+ let result =
+ expand_template("cd {{ worktree }} && echo {{ branch }}", &vars, true).unwrap();
results.push((name, path, result));
}
@@ -314,10 +295,6 @@ fn snapshot_shell_escaping_paths() {
#[test]
#[cfg(unix)]
fn snapshot_complex_templates() {
- let mut extras = HashMap::new();
- extras.insert("worktree", "/path with spaces/wt");
- extras.insert("target", "main; rm -rf /");
-
// Test realistic complex template commands
let test_cases = vec![
(
@@ -338,10 +315,91 @@ fn snapshot_complex_templates() {
];
let mut results = Vec::new();
- for (name, template, branch) in test_cases {
- let result = expand_template(template, "/repo/path", branch, &extras).unwrap();
- results.push((name, template, branch, result));
+ for (name, template, branch_raw) in test_cases {
+ let branch = sanitize_branch_name(branch_raw);
+ let mut vars = HashMap::new();
+ vars.insert("branch", branch.as_str());
+ 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).unwrap();
+ results.push((name, template, branch_raw, result));
}
insta::assert_yaml_snapshot!(results);
}
+
+// Tests for literal expansion (shell_escape=false)
+
+#[test]
+fn test_expand_template_literal_normal() {
+ let branch = sanitize_branch_name("feature");
+ let mut vars = HashMap::new();
+ vars.insert("main_worktree", "myrepo");
+ vars.insert("branch", branch.as_str());
+ let result = expand_template("{{ main_worktree }}.{{ branch }}", &vars, false).unwrap();
+ assert_eq!(result, "myrepo.feature");
+}
+
+#[test]
+fn test_expand_template_literal_unicode_no_escaping() {
+ // Unicode should NOT be shell-escaped in filesystem paths
+ let branch = sanitize_branch_name("test-\u{2282}");
+ let mut vars = HashMap::new();
+ vars.insert("main_worktree", "myrepo");
+ vars.insert("branch", branch.as_str());
+ let result = expand_template("{{ main_worktree }}.{{ branch }}", &vars, false).unwrap();
+ // Path should contain literal unicode, NO quotes
+ assert_eq!(result, "myrepo.test-\u{2282}");
+ assert!(
+ !result.contains('\''),
+ "Path should not contain shell quotes"
+ );
+}
+
+#[test]
+fn test_expand_template_literal_spaces_no_escaping() {
+ // Spaces should NOT be shell-escaped (filesystem paths can have spaces)
+ let branch = sanitize_branch_name("feature name");
+ let mut vars = HashMap::new();
+ vars.insert("main_worktree", "my repo");
+ vars.insert("branch", branch.as_str());
+ let result = expand_template("{{ main_worktree }}.{{ branch }}", &vars, false).unwrap();
+ // No shell quotes around spaces
+ assert_eq!(result, "my repo.feature name");
+ assert!(
+ !result.contains('\''),
+ "Path should not contain shell quotes"
+ );
+}
+
+#[test]
+fn test_expand_template_literal_sanitizes_slashes() {
+ // Branch name sanitization is caller's responsibility
+ let branch = sanitize_branch_name("feature/nested/branch");
+ let mut vars = HashMap::new();
+ vars.insert("main_worktree", "myrepo");
+ vars.insert("branch", branch.as_str());
+ let result = expand_template("{{ main_worktree }}.{{ branch }}", &vars, false).unwrap();
+ assert_eq!(result, "myrepo.feature-nested-branch");
+}
+
+#[test]
+#[cfg(unix)]
+fn test_expand_template_literal_vs_escaped_unicode() {
+ // Demonstrate the difference between literal and escaped expansion
+ let branch = sanitize_branch_name("test-\u{2282}");
+ let mut vars = HashMap::new();
+ vars.insert("main_worktree", "myrepo");
+ vars.insert("branch", branch.as_str());
+ let template = "{{ main_worktree }}.{{ branch }}";
+
+ let literal_result = expand_template(template, &vars, false).unwrap();
+ let escaped_result = expand_template(template, &vars, true).unwrap();
+
+ // Literal has no quotes
+ assert_eq!(literal_result, "myrepo.test-\u{2282}");
+ // Escaped has shell quotes around the unicode part
+ // (shell_escape only quotes strings containing special chars)
+ assert_eq!(escaped_result, "myrepo.'test-\u{2282}'");
+}
diff --git a/src/config/user.rs b/src/config/user.rs
index cc2b628ea..d5c3d6904 100644
--- a/src/config/user.rs
+++ b/src/config/user.rs
@@ -59,7 +59,7 @@ pub fn set_config_path(path: PathBuf) {
CONFIG_PATH.set(path).ok();
}
-use super::expansion::expand_template;
+use super::expansion::{expand_template, sanitize_branch_name};
/// What to stage before committing
#[derive(
@@ -428,12 +428,13 @@ impl WorktrunkConfig {
/// assert_eq!(path, "../myproject.feature-foo");
/// ```
pub fn format_path(&self, main_worktree: &str, branch: &str) -> Result<String, String> {
- expand_template(
- &self.worktree_path,
- main_worktree,
- branch,
- &std::collections::HashMap::new(),
- )
+ use std::collections::HashMap;
+ let safe_branch = sanitize_branch_name(branch);
+ let mut vars = HashMap::new();
+ vars.insert("main_worktree", main_worktree);
+ vars.insert("repo", main_worktree);
+ vars.insert("branch", safe_branch.as_str());
+ expand_template(&self.worktree_path, &vars, false)
}
/// Check if a command is approved for the given project