Skip to content

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

Add {{ branch | sanitize }} filter for explicit branch sanitization (#265)

Maximilian Roos7e7b49999e43
diff --git a/.claude-plugin/skills/worktrunk/reference/hook-types-reference.md b/.claude-plugin/skills/worktrunk/reference/hook-types-reference.md
index a9f543bd6..7cc8b1c0e 100644
--- a/.claude-plugin/skills/worktrunk/reference/hook-types-reference.md
+++ b/.claude-plugin/skills/worktrunk/reference/hook-types-reference.md
@@ -12,8 +12,9 @@ Detailed behavior and use cases for all five Worktrunk hook types.
| `pre-merge` | Before merging to target | Yes | Yes | Basic + Merge | Sequential |
| `post-merge` | After successful merge | Yes | No | Basic + Merge | Sequential |
-**Basic variables**: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ repo_root }}`
+**Basic variables**: `{{ repo }}`, `{{ branch }}` (raw), `{{ worktree }}`, `{{ repo_root }}`
**Merge variables**: Basic + `{{ target }}`
+**Filter**: `{{ branch | sanitize }}` replaces `/` and `\` with `-`
## Detailed Behavior
diff --git a/.claude-plugin/skills/worktrunk/reference/project-config.md b/.claude-plugin/skills/worktrunk/reference/project-config.md
index c3c03626d..42fcab3e1 100644
--- a/.claude-plugin/skills/worktrunk/reference/project-config.md
+++ b/.claude-plugin/skills/worktrunk/reference/project-config.md
@@ -186,7 +186,8 @@ All hooks support template variables for dynamic behavior.
Available in all hook types:
- `{{ repo }}` - Repository name (e.g., "my-project")
-- `{{ branch }}` - Branch name (e.g., "feature-auth")
+- `{{ branch }}` - Raw branch name (e.g., "feature/auth")
+- `{{ branch | sanitize }}` - Branch name with `/` and `\` replaced by `-`
- `{{ worktree }}` - Absolute path to worktree
- `{{ repo_root }}` - Absolute path to repository root
diff --git a/.claude-plugin/skills/worktrunk/reference/user-config.md b/.claude-plugin/skills/worktrunk/reference/user-config.md
index 6c55f1703..f7e239c2f 100644
--- a/.claude-plugin/skills/worktrunk/reference/user-config.md
+++ b/.claude-plugin/skills/worktrunk/reference/user-config.md
@@ -107,13 +107,13 @@ Users may want different worktree organization patterns.
Default (parent siblings):
```toml
-worktree-path = "../{{ main_worktree }}.{{ branch }}"
+worktree-path = "../{{ main_worktree }}.{{ branch | sanitize }}"
```
Result: `~/code/myproject` → `~/code/myproject.feature-auth`
Inside repo:
```toml
-worktree-path = ".worktrees/{{ branch }}"
+worktree-path = ".worktrees/{{ branch | sanitize }}"
```
Result: `~/code/myproject/.worktrees/feature-auth`
@@ -130,7 +130,8 @@ Result: `~/code/myproject/.worktrees/feature-auth`
### Available Variables
- `{{ main_worktree }}` - Main worktree directory name
-- `{{ branch }}` - Branch name (slashes replaced with dashes)
+- `{{ branch }}` - Raw branch name (e.g., `feature/foo`)
+- `{{ branch | sanitize }}` - Branch name with `/` and `\` replaced by `-`
### Validation Rules
@@ -200,7 +201,7 @@ Complete reference:
```toml
# Worktree Path Template
-worktree-path = "../{{ main_worktree }}.{{ branch }}"
+worktree-path = "../{{ main_worktree }}.{{ branch | sanitize }}"
# LLM Commit Generation (Optional)
[commit-generation]
diff --git a/dev/config.example.toml b/dev/config.example.toml
index 31caf56be..bc82996d6 100644
--- a/dev/config.example.toml
+++ b/dev/config.example.toml
@@ -30,18 +30,19 @@ args = ["-m", "claude-haiku-4.5"]
# Worktree Path Template
# Variables:
-# {{ main_worktree }} - Main worktree directory name (e.g., "myproject")
-# {{ branch }} - Branch name with slashes replaced by dashes (feature/auth → feature-auth)
+# {{ main_worktree }} - Main worktree directory name (e.g., "myproject")
+# {{ branch }} - Raw branch name (e.g., "feature/auth")
+# {{ branch | sanitize }} - Branch name with / and \ replaced by - (e.g., "feature-auth")
#
# Paths are relative to the main worktree root (original repository directory).
#
# Example paths created (main worktree at /Users/dev/myproject, branch feature/auth):
-# "../{{ main_worktree }}.{{ branch }}" → /Users/dev/myproject.feature-auth
-# ".worktrees/{{ branch }}" → /Users/dev/myproject/.worktrees/feature-auth
-worktree-path = "../{{ main_worktree }}.{{ branch }}"
+# "../{{ main_worktree }}.{{ branch | sanitize }}" → /Users/dev/myproject.feature-auth
+# ".worktrees/{{ branch | sanitize }}" → /Users/dev/myproject/.worktrees/feature-auth
+worktree-path = "../{{ main_worktree }}.{{ branch | sanitize }}"
# Alternative: Inside repo (useful for bare repos)
-# worktree-path = ".worktrees/{{ branch }}"
+# worktree-path = ".worktrees/{{ branch | sanitize }}"
# List Command Defaults
# Configure default behavior for `wt list`
diff --git a/dev/wt.example.toml b/dev/wt.example.toml
index 474042ba5..978bb2e5e 100644
--- a/dev/wt.example.toml
+++ b/dev/wt.example.toml
@@ -6,10 +6,11 @@
# developers working on the project.
# Available template variables (all hooks):
-# {{ repo }} - Repository name (e.g., "my-project")
-# {{ branch }} - Branch name (slashes replaced with dashes)
-# {{ worktree }} - Absolute path to the worktree
-# {{ repo_root }} - Absolute path to the repository root
+# {{ repo }} - Repository name (e.g., "my-project")
+# {{ branch }} - Raw branch name (e.g., "feature/foo")
+# {{ branch | sanitize }} - Branch name with / and \ replaced by -
+# {{ worktree }} - Absolute path to the worktree
+# {{ repo_root }} - Absolute path to the repository root
#
# Merge-related hooks also support:
# {{ target }} - Target branch for the merge (e.g., "main")
diff --git a/docs/content/config.md b/docs/content/config.md
index 43c637881..5eb25bed0 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -53,22 +53,23 @@ Controls where new worktrees are created. The template is relative to the reposi
**Available variables:**
- `{{ main_worktree }}` — main worktree directory name
-- `{{ branch }}` — branch name (slashes replaced with dashes)
+- `{{ branch }}` — raw branch name (e.g., `feature/foo`)
+- `{{ branch | sanitize }}` — branch name with `/` and `\` replaced by `-`
**Examples** for a repo at `~/code/myproject` creating branch `feature/login`:
```toml
# Default — siblings in parent directory
# Creates: ~/code/myproject.feature-login
-worktree-path = "../{{ main_worktree }}.{{ branch }}"
+worktree-path = "../{{ main_worktree }}.{{ branch | sanitize }}"
# Inside the repository
# Creates: ~/code/myproject/.worktrees/feature-login
-worktree-path = ".worktrees/{{ branch }}"
+worktree-path = ".worktrees/{{ branch | sanitize }}"
# Namespaced (useful when multiple repos share a parent directory)
# Creates: ~/code/worktrees/myproject/feature-login
-worktree-path = "../worktrees/{{ main_worktree }}/{{ branch }}"
+worktree-path = "../worktrees/{{ main_worktree }}/{{ branch | sanitize }}"
```
### Command settings
@@ -297,18 +298,19 @@ args = ["-m", "claude-haiku-4.5"]
# Worktree Path Template
# Variables:
-# {{ main_worktree }} - Main worktree directory name (e.g., "myproject")
-# {{ branch }} - Branch name with slashes replaced by dashes (feature/auth → feature-auth)
+# {{ main_worktree }} - Main worktree directory name (e.g., "myproject")
+# {{ branch }} - Raw branch name (e.g., "feature/auth")
+# {{ branch | sanitize }} - Branch name with / and \ replaced by - (e.g., "feature-auth")
#
# Paths are relative to the main worktree root (original repository directory).
#
# Example paths created (main worktree at /Users/dev/myproject, branch feature/auth):
-# "../{{ main_worktree }}.{{ branch }}" → /Users/dev/myproject.feature-auth
-# ".worktrees/{{ branch }}" → /Users/dev/myproject/.worktrees/feature-auth
-worktree-path = "../{{ main_worktree }}.{{ branch }}"
+# "../{{ main_worktree }}.{{ branch | sanitize }}" → /Users/dev/myproject.feature-auth
+# ".worktrees/{{ branch | sanitize }}" → /Users/dev/myproject/.worktrees/feature-auth
+worktree-path = "../{{ main_worktree }}.{{ branch | sanitize }}"
# Alternative: Inside repo (useful for bare repos)
-# worktree-path = ".worktrees/{{ branch }}"
+# worktree-path = ".worktrees/{{ branch | sanitize }}"
# List Command Defaults
# Configure default behavior for `wt list`
@@ -467,10 +469,11 @@ With `--project`, creates `.config/wt.toml` in the current repository:
# developers working on the project.
# Available template variables (all hooks):
-# {{ repo }} - Repository name (e.g., "my-project")
-# {{ branch }} - Branch name (slashes replaced with dashes)
-# {{ worktree }} - Absolute path to the worktree
-# {{ repo_root }} - Absolute path to the repository root
+# {{ repo }} - Repository name (e.g., "my-project")
+# {{ branch }} - Raw branch name (e.g., "feature/foo")
+# {{ branch | sanitize }} - Branch name with / and \ replaced by -
+# {{ worktree }} - Absolute path to the worktree
+# {{ repo_root }} - Absolute path to the repository root
#
# Merge-related hooks also support:
# {{ target }} - Target branch for the merge (e.g., "main")
diff --git a/docs/content/step.md b/docs/content/step.md
index 856be2665..19aa4c62f 100644
--- a/docs/content/step.md
+++ b/docs/content/step.md
@@ -82,7 +82,8 @@ All variables are shell-escaped:
| Variable | Description |
|----------|-------------|
-| `{{ branch }}` | Branch name (slashes replaced with dashes) |
+| `{{ branch }}` | Branch name (raw, e.g., `feature/foo`) |
+| `{{ branch \| sanitize }}` | Branch name with `/` and `\` replaced by `-` |
| `{{ worktree }}` | Absolute path to the worktree |
| `{{ worktree_name }}` | Worktree directory name |
| `{{ repo }}` | Repository name |
diff --git a/src/cli.rs b/src/cli.rs
index 81921bfe2..f6decfefe 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -960,7 +960,8 @@ All variables are shell-escaped:
| Variable | Description |
|----------|-------------|
-| `{{ branch }}` | Branch name (slashes replaced with dashes) |
+| `{{ branch }}` | Branch name (raw, e.g., `feature/foo`) |
+| `{{ branch \| sanitize }}` | Branch name with `/` and `\` replaced by `-` |
| `{{ worktree }}` | Absolute path to the worktree |
| `{{ worktree_name }}` | Worktree directory name |
| `{{ repo }}` | Repository name |
@@ -1203,22 +1204,23 @@ Controls where new worktrees are created. The template is relative to the reposi
**Available variables:**
- `{{ main_worktree }}` — main worktree directory name
-- `{{ branch }}` — branch name (slashes replaced with dashes)
+- `{{ branch }}` — raw branch name (e.g., `feature/foo`)
+- `{{ branch | sanitize }}` — branch name with `/` and `\` replaced by `-`
**Examples** for a repo at `~/code/myproject` creating branch `feature/login`:
```toml
# Default — siblings in parent directory
# Creates: ~/code/myproject.feature-login
-worktree-path = "../{{ main_worktree }}.{{ branch }}"
+worktree-path = "../{{ main_worktree }}.{{ branch | sanitize }}"
# Inside the repository
# Creates: ~/code/myproject/.worktrees/feature-login
-worktree-path = ".worktrees/{{ branch }}"
+worktree-path = ".worktrees/{{ branch | sanitize }}"
# Namespaced (useful when multiple repos share a parent directory)
# Creates: ~/code/worktrees/myproject/feature-login
-worktree-path = "../worktrees/{{ main_worktree }}/{{ branch }}"
+worktree-path = "../worktrees/{{ main_worktree }}/{{ branch | sanitize }}"
```
### Command settings
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index be82fad9d..7b39d830e 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -1,9 +1,7 @@
use std::collections::HashMap;
use std::path::Path;
use worktrunk::HookType;
-use worktrunk::config::{
- Command, CommandConfig, WorktrunkConfig, expand_template, sanitize_branch_name,
-};
+use worktrunk::config::{Command, CommandConfig, WorktrunkConfig, expand_template};
use worktrunk::git::Repository;
use worktrunk::path::to_posix_path;
@@ -76,7 +74,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("branch".into(), ctx.branch_or_head().into());
map.insert("worktree".into(), worktree);
map.insert("worktree_name".into(), worktree_name.into());
map.insert(
diff --git a/src/commands/config.rs b/src/commands/config.rs
index 459b2a6b0..ea211e8a8 100644
--- a/src/commands/config.rs
+++ b/src/commands/config.rs
@@ -255,8 +255,7 @@ fn render_user_config(out: &mut String) -> anyhow::Result<()> {
))
)?;
writeln!(out)?;
- let default_config =
- "# Default configuration:\nworktree-path = \"../{{ main_worktree }}.{{ branch }}\"";
+ let default_config = "# Default configuration:\nworktree-path = \"../{{ main_worktree }}.{{ branch | sanitize }}\"";
write!(out, "{}", format_toml(default_config, ""))?;
return Ok(());
}
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 524192c76..19b37c461 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -6,7 +6,7 @@
//!
//! All templates support Jinja2 syntax including filters, conditionals, and loops.
-use minijinja::Environment;
+use minijinja::{Environment, Value};
use std::collections::HashMap;
/// Sanitize a branch name for use in filesystem paths.
@@ -30,30 +30,32 @@ pub fn sanitize_branch_name(branch: &str) -> String {
///
/// # 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.
+/// * `vars` - Variables to substitute
/// * `shell_escape` - If true, shell-escape all values for safe command execution.
/// If false, substitute values literally (for filesystem paths).
///
+/// # Filters
+/// The `sanitize` filter is available for branch names, replacing `/` and `\` with `-`:
+/// - `{{ branch }}` — raw branch name (e.g., `feature/foo`)
+/// - `{{ branch | sanitize }}` — sanitized for paths (e.g., `feature-foo`)
+///
/// # Examples
/// ```
-/// use worktrunk::config::{expand_template, sanitize_branch_name};
+/// use worktrunk::config::expand_template;
/// use std::collections::HashMap;
///
-/// // For shell commands (escaped)
-/// let branch = sanitize_branch_name("feature/foo");
+/// // Raw branch name
/// let mut vars = HashMap::new();
-/// vars.insert("branch", branch.as_str());
+/// vars.insert("branch", "feature/foo");
/// vars.insert("repo", "myrepo");
/// let cmd = expand_template("echo {{ branch }} in {{ repo }}", &vars, true).unwrap();
-/// assert_eq!(cmd, "echo feature-foo in myrepo");
+/// assert_eq!(cmd, "echo feature/foo in myrepo");
///
-/// // For filesystem paths (literal)
-/// let branch = sanitize_branch_name("feature/foo");
+/// // Sanitized branch name for filesystem paths
/// let mut vars = HashMap::new();
-/// vars.insert("branch", branch.as_str());
+/// vars.insert("branch", "feature/foo");
/// vars.insert("main_worktree", "myrepo");
-/// let path = expand_template("{{ main_worktree }}.{{ branch }}", &vars, false).unwrap();
+/// let path = expand_template("{{ main_worktree }}.{{ branch | sanitize }}", &vars, false).unwrap();
/// assert_eq!(path, "myrepo.feature-foo");
/// ```
pub fn expand_template(
@@ -81,6 +83,12 @@ pub fn expand_template(
// Preserve trailing newlines in templates (important for multiline shell commands)
env.set_keep_trailing_newline(true);
}
+
+ // Register the `sanitize` filter for branch names (replaces / and \ with -)
+ env.add_filter("sanitize", |value: Value| -> String {
+ sanitize_branch_name(value.as_str().unwrap_or_default())
+ });
+
let tmpl = env
.template_from_str(template)
.map_err(|e| format!("Template syntax error: {}", e))?;
@@ -200,6 +208,37 @@ mod tests {
);
}
+ #[test]
+ fn test_expand_template_sanitize_filter() {
+ let mut vars = HashMap::new();
+ vars.insert("branch", "feature/foo");
+ assert_eq!(
+ expand_template("{{ branch | sanitize }}", &vars, false).unwrap(),
+ "feature-foo"
+ );
+
+ // Backslashes are also sanitized
+ vars.insert("branch", "feature\\bar");
+ assert_eq!(
+ expand_template("{{ branch | sanitize }}", &vars, false).unwrap(),
+ "feature-bar"
+ );
+
+ // Multiple slashes
+ vars.insert("branch", "user/feature/task");
+ assert_eq!(
+ expand_template("{{ branch | sanitize }}", &vars, false).unwrap(),
+ "user-feature-task"
+ );
+
+ // Raw branch is unchanged
+ vars.insert("branch", "feature/foo");
+ assert_eq!(
+ expand_template("{{ branch }}", &vars, false).unwrap(),
+ "feature/foo"
+ );
+ }
+
#[test]
fn test_expand_template_trailing_newline() {
let mut vars = HashMap::new();
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 36a9999d2..8278e9a3b 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -61,14 +61,17 @@ mod tests {
let config = WorktrunkConfig::default();
let toml = toml::to_string(&config).unwrap();
assert!(toml.contains("worktree-path"));
- assert!(toml.contains("../{{ main_worktree }}.{{ branch }}"));
+ assert!(toml.contains("../{{ main_worktree }}.{{ branch | sanitize }}"));
assert!(toml.contains("commit-generation"));
}
#[test]
fn test_default_config() {
let config = WorktrunkConfig::default();
- assert_eq!(config.worktree_path, "../{{ main_worktree }}.{{ branch }}");
+ assert_eq!(
+ config.worktree_path,
+ "../{{ main_worktree }}.{{ branch | sanitize }}"
+ );
assert_eq!(config.commit_generation.command, None);
assert!(config.projects.is_empty());
}
@@ -111,9 +114,9 @@ mod tests {
#[test]
fn test_format_worktree_path_with_slashes() {
- // Slashes should be replaced with dashes to prevent directory traversal
+ // Use {{ branch | sanitize }} to replace slashes with dashes
let config = WorktrunkConfig {
- worktree_path: "{{ main_worktree }}.{{ branch }}".to_string(),
+ worktree_path: "{{ main_worktree }}.{{ branch | sanitize }}".to_string(),
..Default::default()
};
assert_eq!(
@@ -125,7 +128,7 @@ mod tests {
#[test]
fn test_format_worktree_path_with_multiple_slashes() {
let config = WorktrunkConfig {
- worktree_path: ".worktrees/{{ main_worktree }}/{{ branch }}".to_string(),
+ worktree_path: ".worktrees/{{ main_worktree }}/{{ branch | sanitize }}".to_string(),
..Default::default()
};
assert_eq!(
@@ -138,7 +141,7 @@ mod tests {
fn test_format_worktree_path_with_backslashes() {
// Windows-style path separators should also be sanitized
let config = WorktrunkConfig {
- worktree_path: ".worktrees/{{ main_worktree }}/{{ branch }}".to_string(),
+ worktree_path: ".worktrees/{{ main_worktree }}/{{ branch | sanitize }}".to_string(),
..Default::default()
};
assert_eq!(
@@ -147,6 +150,19 @@ mod tests {
);
}
+ #[test]
+ fn test_format_worktree_path_raw_branch() {
+ // {{ branch }} without filter gives raw branch name
+ let config = WorktrunkConfig {
+ worktree_path: "{{ main_worktree }}.{{ branch }}".to_string(),
+ ..Default::default()
+ };
+ assert_eq!(
+ config.format_path("myproject", "feature/foo").unwrap(),
+ "myproject.feature/foo"
+ );
+ }
+
#[test]
fn test_project_config_default() {
let config = ProjectConfig::default();
@@ -565,20 +581,24 @@ task2 = "echo 'Task 2 running' > task2.txt"
fn test_expand_template_sanitizes_branch() {
use std::collections::HashMap;
- // Caller is responsible for sanitizing branch names
- let branch = sanitize_branch_name("feature/foo");
+ // Use {{ branch | sanitize }} filter for filesystem-safe paths
+ // shell_escape=false to test filter in isolation (shell escaping tested separately)
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();
+ vars.insert("branch", "feature/foo");
+ let result =
+ expand_template("{{ main_worktree }}/{{ branch | sanitize }}", &vars, false).unwrap();
assert_eq!(result, "myrepo/feature-foo");
- 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();
+ vars.insert("branch", "feat\\bar");
+ let result = expand_template(
+ ".worktrees/{{ main_worktree }}/{{ branch | sanitize }}",
+ &vars,
+ false,
+ )
+ .unwrap();
assert_eq!(result, ".worktrees/myrepo/feat-bar");
}
diff --git a/src/config/snapshots/worktrunk__config__test__snapshot_complex_templates.snap b/src/config/snapshots/worktrunk__config__test__snapshot_complex_templates.snap
index 754f5de4f..27519f7ff 100644
--- a/src/config/snapshots/worktrunk__config__test__snapshot_complex_templates.snap
+++ b/src/config/snapshots/worktrunk__config__test__snapshot_complex_templates.snap
@@ -7,7 +7,7 @@ expression: results
- feature branch
- "cd '/path with spaces/wt' && git merge 'main; rm -rf /'"
- - npm_install
- - "cd {{ main_worktree }}/{{ branch }} && npm install"
+ - "cd {{ main_worktree }}/{{ branch | sanitize }} && npm install"
- feature/new-ui
- cd /repo/path/feature-new-ui && npm install
- - echo_vars
diff --git a/src/config/snapshots/worktrunk__config__test__snapshot_shell_escaping_special_chars.snap b/src/config/snapshots/worktrunk__config__test__snapshot_shell_escaping_special_chars.snap
index 2ed4b046f..3a2a94730 100644
--- a/src/config/snapshots/worktrunk__config__test__snapshot_shell_escaping_special_chars.snap
+++ b/src/config/snapshots/worktrunk__config__test__snapshot_shell_escaping_special_chars.snap
@@ -16,7 +16,7 @@ expression: results
- "echo 'feature`id`'"
- - semicolon
- feature;rm -rf /
- - "echo 'feature;rm -rf -'"
+ - "echo 'feature;rm -rf /'"
- - pipe
- feature|grep foo
- "echo 'feature|grep foo'"
diff --git a/src/config/test.rs b/src/config/test.rs
index f0917ba6f..befd8619e 100644
--- a/src/config/test.rs
+++ b/src/config/test.rs
@@ -3,7 +3,7 @@
//! These tests target potential shell injection vulnerabilities and
//! edge cases in template variable substitution.
-use super::{expand_template, sanitize_branch_name};
+use super::expand_template;
use std::collections::HashMap;
/// Helper to build vars with common fields
@@ -17,29 +17,33 @@ fn vars_with_branch(branch: &str) -> HashMap<&str, &str> {
#[test]
fn test_expand_template_normal() {
- let branch = sanitize_branch_name("feature");
- let vars = vars_with_branch(&branch);
+ let vars = vars_with_branch("feature");
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() {
- // 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();
+ // Use {{ branch | sanitize }} to replace slashes with dashes
+ let vars = vars_with_branch("feature/nested/branch");
+ let result = expand_template("echo {{ branch | sanitize }}", &vars, true).unwrap();
assert_eq!(result, "echo feature-nested-branch");
}
+#[test]
+fn test_expand_template_branch_raw_with_slashes() {
+ // Raw branch preserves slashes
+ let vars = vars_with_branch("feature/nested/branch");
+ let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
+ assert_eq!(result, "echo feature/nested/branch");
+}
+
// Tests with platform-specific shell escaping (Unix uses single quotes, Windows uses double quotes)
#[test]
#[cfg(unix)]
fn test_expand_template_branch_escaping() {
- let expand = |input| {
- let branch = sanitize_branch_name(input);
- expand_template("echo {{ branch }}", &vars_with_branch(&branch), true).unwrap()
- };
+ let expand =
+ |input| expand_template("echo {{ branch }}", &vars_with_branch(input), true).unwrap();
assert_eq!(expand("feature name"), "echo 'feature name'"); // spaces
assert_eq!(expand("feature$(whoami)"), "echo 'feature$(whoami)'"); // command sub
@@ -49,8 +53,7 @@ fn test_expand_template_branch_escaping() {
#[test]
#[cfg(unix)]
fn snapshot_expand_template_branch_with_quotes() {
- let branch = sanitize_branch_name("feature'test");
- let vars = vars_with_branch(&branch);
+ let vars = vars_with_branch("feature'test");
let result = expand_template("echo '{{ branch }}'", &vars, true).unwrap();
insta::assert_snapshot!(result, @"echo ''feature'\\''test''");
}
@@ -119,8 +122,7 @@ fn test_expand_template_empty_branch() {
#[cfg(unix)]
fn test_expand_template_unicode_in_branch() {
// Unicode characters in branch name are shell-escaped
- let branch = sanitize_branch_name("feature-\u{1F680}");
- let vars = vars_with_branch(&branch);
+ let vars = vars_with_branch("feature-\u{1F680}");
let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
// Unicode is preserved but quoted for shell safety
@@ -129,19 +131,18 @@ fn test_expand_template_unicode_in_branch() {
#[test]
fn test_expand_template_backslash_in_branch() {
- // 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();
+ // Use {{ branch | sanitize }} to replace backslashes with dashes
+ // Note: shell_escape=false to test sanitize filter in isolation
+ let vars = vars_with_branch("feature\\branch");
+ let result = expand_template("path/{{ branch | sanitize }}", &vars, false).unwrap();
- // Backslashes are replaced with dashes by sanitize_branch_name
- assert_eq!(result, "echo feature-branch");
+ // Backslashes are replaced with dashes by sanitize filter
+ assert_eq!(result, "path/feature-branch");
}
#[test]
fn test_expand_template_multiple_replacements() {
- let branch = sanitize_branch_name("feature");
- let mut vars = vars_with_branch(&branch);
+ let mut vars = vars_with_branch("feature");
vars.insert("worktree", "/path/to/wt");
vars.insert("target", "develop");
@@ -167,8 +168,7 @@ 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 branch = sanitize_branch_name("main");
- let vars = vars_with_branch(&branch);
+ let vars = vars_with_branch("main");
let result = expand_template("echo {{ '{' ~ branch ~ '}' }}", &vars, true).unwrap();
// Renders as {main}
@@ -200,11 +200,10 @@ fn snapshot_shell_escaping_special_chars() {
];
let mut results = Vec::new();
- for (name, branch_raw) in test_cases {
- let branch = sanitize_branch_name(branch_raw);
- let vars = vars_with_branch(&branch);
+ for (name, branch) in test_cases {
+ let vars = vars_with_branch(branch);
let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
- results.push((name, branch_raw, result));
+ results.push((name, branch, result));
}
insta::assert_yaml_snapshot!(results);
@@ -222,11 +221,10 @@ fn snapshot_shell_escaping_quotes() {
];
let mut results = Vec::new();
- for (name, branch_raw) in test_cases {
- let branch = sanitize_branch_name(branch_raw);
- let vars = vars_with_branch(&branch);
+ for (name, branch) in test_cases {
+ let vars = vars_with_branch(branch);
let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
- results.push((name, branch_raw, result));
+ results.push((name, branch, result));
}
insta::assert_yaml_snapshot!(results);
@@ -246,8 +244,7 @@ fn snapshot_shell_escaping_paths() {
let mut results = Vec::new();
for (name, path) in test_cases {
- let branch = sanitize_branch_name("main");
- let mut vars = vars_with_branch(&branch);
+ let mut vars = vars_with_branch("main");
vars.insert("worktree", path);
let result =
expand_template("cd {{ worktree }} && echo {{ branch }}", &vars, true).unwrap();
@@ -261,6 +258,7 @@ fn snapshot_shell_escaping_paths() {
#[cfg(unix)]
fn snapshot_complex_templates() {
// Test realistic complex template commands
+ // Note: {{ branch | sanitize }} is used when branch sanitization is needed
let test_cases = vec![
(
"cd_and_merge",
@@ -269,7 +267,7 @@ fn snapshot_complex_templates() {
),
(
"npm_install",
- "cd {{ main_worktree }}/{{ branch }} && npm install",
+ "cd {{ main_worktree }}/{{ branch | sanitize }} && npm install",
"feature/new-ui",
),
(
@@ -280,15 +278,14 @@ fn snapshot_complex_templates() {
];
let mut results = Vec::new();
- for (name, template, branch_raw) in test_cases {
- let branch = sanitize_branch_name(branch_raw);
+ for (name, template, branch) in test_cases {
let mut vars = HashMap::new();
- vars.insert("branch", branch.as_str());
+ vars.insert("branch", branch);
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));
+ results.push((name, template, branch, result));
}
insta::assert_yaml_snapshot!(results);
@@ -298,10 +295,9 @@ fn snapshot_complex_templates() {
#[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());
+ vars.insert("branch", "feature");
let result = expand_template("{{ main_worktree }}.{{ branch }}", &vars, false).unwrap();
assert_eq!(result, "myrepo.feature");
}
@@ -309,10 +305,9 @@ fn test_expand_template_literal_normal() {
#[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());
+ vars.insert("branch", "test-\u{2282}");
let result = expand_template("{{ main_worktree }}.{{ branch }}", &vars, false).unwrap();
// Path should contain literal unicode, NO quotes
assert_eq!(result, "myrepo.test-\u{2282}");
@@ -325,10 +320,9 @@ fn test_expand_template_literal_unicode_no_escaping() {
#[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());
+ vars.insert("branch", "feature name");
let result = expand_template("{{ main_worktree }}.{{ branch }}", &vars, false).unwrap();
// No shell quotes around spaces
assert_eq!(result, "my repo.feature name");
@@ -340,12 +334,12 @@ fn test_expand_template_literal_spaces_no_escaping() {
#[test]
fn test_expand_template_literal_sanitizes_slashes() {
- // Branch name sanitization is caller's responsibility
- let branch = sanitize_branch_name("feature/nested/branch");
+ // Use {{ branch | sanitize }} to replace slashes with dashes
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();
+ vars.insert("branch", "feature/nested/branch");
+ let result =
+ expand_template("{{ main_worktree }}.{{ branch | sanitize }}", &vars, false).unwrap();
assert_eq!(result, "myrepo.feature-nested-branch");
}
@@ -353,10 +347,9 @@ fn test_expand_template_literal_sanitizes_slashes() {
#[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());
+ vars.insert("branch", "test-\u{2282}");
let template = "{{ main_worktree }}.{{ branch }}";
let literal_result = expand_template(template, &vars, false).unwrap();
diff --git a/src/config/user.rs b/src/config/user.rs
index 3425c8ea2..074a437f9 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, sanitize_branch_name};
+use super::expansion::expand_template;
/// What to stage before committing
#[derive(
@@ -92,19 +92,20 @@ pub enum StageMode {
/// The `worktree-path` template is relative to the repository root.
/// Supported variables:
/// - `{{ main_worktree }}` - Main worktree directory name
-/// - `{{ branch }}` - Branch name (slashes replaced with dashes)
+/// - `{{ branch }}` - Raw branch name (e.g., `feature/foo`)
+/// - `{{ branch | sanitize }}` - Branch name with `/` and `\` replaced by `-`
///
/// # Examples
///
/// ```toml
/// # Default - parent directory siblings
-/// worktree-path = "../{{ main_worktree }}.{{ branch }}"
+/// worktree-path = "../{{ main_worktree }}.{{ branch | sanitize }}"
///
/// # Inside repo (clean, no redundant directory)
-/// worktree-path = ".worktrees/{{ branch }}"
+/// worktree-path = ".worktrees/{{ branch | sanitize }}"
///
/// # Repository-namespaced (useful for shared directories with multiple repos)
-/// worktree-path = "../worktrees/{{ main_worktree }}/{{ branch }}"
+/// worktree-path = "../worktrees/{{ main_worktree }}/{{ branch | sanitize }}"
///
/// # Commit generation configuration
/// [commit-generation]
@@ -327,7 +328,7 @@ pub struct MergeConfig {
/// Default worktree path template (used by serde)
fn default_worktree_path() -> String {
- "../{{ main_worktree }}.{{ branch }}".to_string()
+ "../{{ main_worktree }}.{{ branch | sanitize }}".to_string()
}
impl Default for WorktrunkConfig {
@@ -423,23 +424,23 @@ impl WorktrunkConfig {
///
/// # Arguments
/// * `main_worktree` - Main worktree directory name (replaces {{ main_worktree }} in template)
- /// * `branch` - Branch name (replaces {{ branch }} in template, slashes sanitized to dashes)
+ /// * `branch` - Branch name (replaces {{ branch }} in template; use `{{ branch | sanitize }}` for paths)
///
/// # Examples
/// ```
/// use worktrunk::config::WorktrunkConfig;
///
+ /// // Default template uses {{ branch | sanitize }} for filesystem-safe paths
/// let config = WorktrunkConfig::default();
/// let path = config.format_path("myproject", "feature/foo").unwrap();
/// assert_eq!(path, "../myproject.feature-foo");
/// ```
pub fn format_path(&self, main_worktree: &str, branch: &str) -> Result<String, String> {
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());
+ vars.insert("branch", branch);
expand_template(&self.worktree_path, &vars, false)
}
@@ -899,7 +900,10 @@ run = "npm run build"
#[test]
fn test_worktrunk_config_default() {
let config = WorktrunkConfig::default();
- assert_eq!(config.worktree_path, "../{{ main_worktree }}.{{ branch }}");
+ assert_eq!(
+ config.worktree_path,
+ "../{{ main_worktree }}.{{ branch | sanitize }}"
+ );
assert!(config.projects.is_empty());
assert!(config.list.is_none());
assert!(config.commit.is_none());
diff --git a/tests/integration_tests/approval_save.rs b/tests/integration_tests/approval_save.rs
index dda692b93..0ccfb3f5b 100644
--- a/tests/integration_tests/approval_save.rs
+++ b/tests/integration_tests/approval_save.rs
@@ -33,7 +33,7 @@ fn test_approval_saves_to_disk() {
// Verify TOML structure
let toml_content = fs::read_to_string(&config_path).unwrap();
assert_snapshot!(toml_content, @r#"
- worktree-path = "../{{ main_worktree }}.{{ branch }}"
+ worktree-path = "../{{ main_worktree }}.{{ branch | sanitize }}"
[commit-generation]
args = []
@@ -89,7 +89,7 @@ fn test_duplicate_approvals_not_saved_twice() {
// Verify file contains only one entry
let toml_content = fs::read_to_string(&config_path).unwrap();
assert_snapshot!(toml_content, @r#"
- worktree-path = "../{{ main_worktree }}.{{ branch }}"
+ worktree-path = "../{{ main_worktree }}.{{ branch | sanitize }}"
[commit-generation]
args = []
@@ -141,7 +141,7 @@ fn test_multiple_project_approvals() {
// Verify file structure
let toml_content = fs::read_to_string(&config_path).unwrap();
assert_snapshot!(toml_content, @r#"
- worktree-path = "../{{ main_worktree }}.{{ branch }}"
+ worktree-path = "../{{ main_worktree }}.{{ branch | sanitize }}"
[commit-generation]
args = []
@@ -230,7 +230,7 @@ fn test_force_flag_does_not_save_approval() {
// Load the config and verify it's still empty (no approvals added)
let saved_config = fs::read_to_string(&config_path).unwrap();
assert_snapshot!(saved_config, @r#"
- worktree-path = "../{{ main_worktree }}.{{ branch }}"
+ worktree-path = "../{{ main_worktree }}.{{ branch | sanitize }}"
[commit-generation]
args = []
@@ -264,7 +264,7 @@ fn test_force_flag_saves_to_new_config_file() {
// Verify content
let content = fs::read_to_string(&config_path).unwrap();
assert_snapshot!(content, @r#"
- worktree-path = "../{{ main_worktree }}.{{ branch }}"
+ worktree-path = "../{{ main_worktree }}.{{ branch | sanitize }}"
[commit-generation]
args = []
diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rs
index 923126737..187b731bd 100644
--- a/tests/integration_tests/post_start_commands.rs
+++ b/tests/integration_tests/post_start_commands.rs
@@ -141,7 +141,7 @@ root = "echo 'Root: {{ repo_root }}' >> info.txt"
// Pre-approve all commands in isolated test config
let repo_name = "repo";
repo.write_test_config(
- r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"
+ r#"worktree-path = "../{{ main_worktree }}.{{ branch | sanitize }}"
[projects."repo"]
approved-commands = [
@@ -182,8 +182,8 @@ approved-commands = [
contents
);
assert!(
- contents.contains("Branch: feature-test"),
- "Should contain expanded branch name (sanitized), got: {}",
+ contents.contains("Branch: feature/test"),
+ "Should contain raw branch name, got: {}",
contents
);
}
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_create.snap b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
index b86d8055c..c1e9da9c4 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_create.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
@@ -10,6 +10,7 @@ info:
CLICOLOR_FORCE: "1"
COLUMNS: "150"
GIT_EDITOR: ""
+ RUST_LOG: warn
SOURCE_DATE_EPOCH: "1735776000"
WORKTRUNK_CONFIG_PATH: /nonexistent/test/config.toml
---
@@ -75,18 +76,19 @@ Creates ~/.config/worktrunk/config.toml with the following content:

# Worktree Path Template
# Variables:
- # {{ main_worktree }} - Main worktree directory name (e.g., "myproject")
- # {{ branch }} - Branch name with slashes replaced by dashes (feature/auth → feature-auth)
+ # {{ main_worktree }} - Main worktree directory name (e.g., "myproject")
+ # {{ branch }} - Raw branch name (e.g., "feature/auth")
+ # {{ branch | sanitize }} - Branch name with / and \ replaced by - (e.g., "feature-auth")
#
# Paths are relative to the main worktree root (original repository directory).
#
# Example paths created (main worktree at /Users/dev/myproject, branch feature/auth):
- # "../{{ main_worktree }}.{{ branch }}" → /Users/dev/myproject.feature-auth
- # ".worktrees/{{ branch }}" → /Users/dev/myproject/.worktrees/feature-auth
- worktree-path = "../{{ main_worktree }}.{{ branch }}"
+ # "../{{ main_worktree }}.{{ branch | sanitize }}" → /Users/dev/myproject.feature-auth
+ # ".worktrees/{{ branch | sanitize }}" → /Users/dev/myproject/.worktrees/feature-auth
+ worktree-path = "../{{ main_worktree }}.{{ branch | sanitize }}"

# Alternative: Inside repo (useful for bare repos)
- # worktree-path = ".worktrees/{{ branch }}"
+ # worktree-path = ".worktrees/{{ branch | sanitize }}"

# List Command Defaults
# Configure default behavior for `wt list`
@@ -243,10 +245,11 @@ With --project, creates .config/wt.toml in the current repositor
# developers working on the project.

# Available template variables (all hooks):
- # {{ repo }} - Repository name (e.g., "my-project")
- # {{ branch }} - Branch name (slashes replaced with dashes)
- # {{ worktree }} - Absolute path to the worktree
- # {{ repo_root }} - Absolute path to the repository root
+ # {{ repo }} - Repository name (e.g., "my-project")
+ # {{ branch }} - Raw branch name (e.g., "feature/foo")
+ # {{ branch | sanitize }} - Branch name with / and \ replaced by -
+ # {{ worktree }} - Absolute path to the worktree
+ # {{ repo_root }} - Absolute path to the repository root
#
# Merge-related hooks also support:
# {{ target }} - Target branch for the merge (e.g., "main")
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
index d7c6efca5..e36caa581 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
@@ -9,6 +9,7 @@ info:
CLICOLOR_FORCE: "1"
COLUMNS: "150"
GIT_EDITOR: ""
+ RUST_LOG: warn
SOURCE_DATE_EPOCH: "1735776000"
WORKTRUNK_CONFIG_PATH: /nonexistent/test/config.toml
---
@@ -78,21 +79,22 @@ Controls where new worktrees are created. The template is relative to the reposi
Available variables:
- {{ main_worktree }} — main worktree directory name
-- {{ branch }} — branch name (slashes replaced with dashes)
+- {{ branch }} — raw branch name (e.g., feature/foo)
+- {{ branch | sanitize }} — branch name with / and \ replaced by -
Examples for a repo at ~/code/myproject creating branch feature/login:
# Default — siblings in parent directory
# Creates: ~/code/myproject.feature-login
- worktree-path = "../{{ main_worktree }}.{{ branch }}"
+ worktree-path = "../{{ main_worktree }}.{{ branch | sanitize }}"

# Inside the repository
# Creates: ~/code/myproject/.worktrees/feature-login
- worktree-path = ".worktrees/{{ branch }}"
+ worktree-path = ".worktrees/{{ branch | sanitize }}"

# Namespaced (useful when multiple repos share a parent directory)
# Creates: ~/code/worktrees/myproject/feature-login
- worktree-path = "../worktrees/{{ main_worktree }}/{{ branch }}"
+ worktree-path = "../worktrees/{{ main_worktree }}/{{ branch | sanitize }}"
Command settings
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_template_expansion.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_template_expansion.snap
index 7a28da131..c7f71adc2 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_template_expansion.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_template_expansion.snap
@@ -34,7 +34,7 @@ exit_code: 0
◎ Running project post-create repo:
  echo 'Repo: repo' > info.txt
◎ Running project post-create branch:
-  echo 'Branch: feature-test' >> info.txt
+  echo 'Branch: feature/test' >> info.txt
◎ Running project post-create worktree:
  echo 'Worktree: _REPO_.feature-test' >> info.txt
◎ Running project post-create root: