Skip to content

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

feat: add worktree_path(branch) template function (#609)

Maximilian Roos45aafe3b2609
diff --git a/.claude-plugin/skills/worktrunk/reference/hook.md b/.claude-plugin/skills/worktrunk/reference/hook.md
index 23a6b5b93..2dba00202 100644
--- a/.claude-plugin/skills/worktrunk/reference/hook.md
+++ b/.claude-plugin/skills/worktrunk/reference/hook.md
@@ -150,7 +150,7 @@ Hooks can use template variables that expand at runtime:
See [Designing effective hooks](#designing-effective-hooks) for `main_worktree_path` patterns.
-### Filters
+### Worktrunk Filters
Templates support Jinja2 filters for transforming values:
@@ -174,6 +174,22 @@ Hash any string, including concatenations:
dev = "npm run dev --port {{ (repo ~ '-' ~ branch) | hash_port }}"
```
+### Worktrunk Functions
+
+Templates also support functions for dynamic lookups:
+
+| Function | Example | Description |
+|----------|---------|-------------|
+| `worktree_path(branch)` | `{{ worktree_path("main") }}` | Look up the path of a branch's worktree |
+
+The `worktree_path` function returns the filesystem path of a worktree given a branch name, or an empty string if no worktree exists for that branch. This is useful for referencing files in other worktrees:
+
+```toml
+[post-create]
+# Copy config from main worktree
+setup = "cp {{ worktree_path('main') }}/config.local {{ worktree_path }}"
+```
+
### JSON context
Hooks also receive context as JSON on stdin, enabling hooks in any language:
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index fdebda33c..53a221922 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -73,7 +73,8 @@ repos:
# shell_exec.rs: defines Cmd which legitimately calls .output()
# select.rs: skim API's selected.output() is not Command::output()
# tests/benches: test utilities run commands directly
- exclude: '^(src/shell_exec\.rs|src/commands/select\.rs|tests/|benches/)'
+ # src/config/{test,expansion,mod,user}.rs: TestRepo test fixtures use git init directly
+ exclude: '^(src/shell_exec\.rs|src/commands/select\.rs|src/config/(test|expansion|mod|user)\.rs|tests/|benches/)'
ci:
# pre-commit.ci doesn't have Rust toolchain, so skip Rust-specific hooks.
diff --git a/CLAUDE.md b/CLAUDE.md
index 515befac6..7f3a2bb40 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -104,12 +104,38 @@ When changing:
- CLI flags or their defaults
- Error conditions or messages
-Ask: "Does `--help` still describe what the code does?" If not, update `src/cli.rs` first.
+Ask: "Does `--help` still describe what the code does?" If not, update `src/cli/mod.rs` first.
-After modifying `cli.rs`, sync the doc pages:
+### Auto-generated docs
+
+Documentation has three categories:
+
+1. **Command pages** (config, hook, list, merge, remove, select, step, switch):
+ ```
+ src/cli/mod.rs (PRIMARY SOURCE)
+ ↓ test_command_pages_are_in_sync
+ docs/content/{command}.md
+ ↓ test_skill_files_are_in_sync_with_docs
+ .claude-plugin/skills/worktrunk/reference/{command}.md
+ ```
+ Edit `src/cli/mod.rs` (`after_long_help` attributes), never the docs directly.
+
+2. **Non-command docs** (claude-code, faq, llm-commits, tips-patterns, worktrunk):
+ ```
+ docs/content/*.md (PRIMARY SOURCE)
+ ↓ test_skill_files_are_in_sync_with_docs
+ .claude-plugin/skills/worktrunk/reference/*.md
+ ```
+ Edit the docs file directly. Skill reference is auto-synced.
+
+3. **Skill-only files** (shell-integration.md, troubleshooting.md):
+ Edit `.claude-plugin/skills/worktrunk/reference/` directly — no docs equivalent.
+
+After any doc changes, run tests to sync:
```bash
cargo test --test integration test_command_pages_are_in_sync
+cargo test --test integration test_skill_files_are_in_sync_with_docs
```
## Data Safety
diff --git a/docs/content/hook.md b/docs/content/hook.md
index 693f30f24..f034229d8 100644
--- a/docs/content/hook.md
+++ b/docs/content/hook.md
@@ -158,7 +158,7 @@ Hooks can use template variables that expand at runtime:
See [Designing effective hooks](#designing-effective-hooks) for `main_worktree_path` patterns.
-### Filters
+### Worktrunk Filters
Templates support Jinja2 filters for transforming values:
@@ -182,6 +182,22 @@ Hash any string, including concatenations:
dev = "npm run dev --port {{ (repo ~ '-' ~ branch) | hash_port }}"
```
+### Worktrunk Functions
+
+Templates also support functions for dynamic lookups:
+
+| Function | Example | Description |
+|----------|---------|-------------|
+| `worktree_path(branch)` | `{{ worktree_path("main") }}` | Look up the path of a branch's worktree |
+
+The `worktree_path` function returns the filesystem path of a worktree given a branch name, or an empty string if no worktree exists for that branch. This is useful for referencing files in other worktrees:
+
+```toml
+[post-create]
+# Copy config from main worktree
+setup = "cp {{ worktree_path('main') }}/config.local {{ worktree_path }}"
+```
+
### JSON context
Hooks also receive context as JSON on stdin, enabling hooks in any language:
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 311ad085f..cb6af2998 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1186,7 +1186,7 @@ Hooks can use template variables that expand at runtime:
See [Designing effective hooks](#designing-effective-hooks) for `main_worktree_path` patterns.
-### Filters
+### Worktrunk Filters
Templates support Jinja2 filters for transforming values:
@@ -1210,6 +1210,22 @@ Hash any string, including concatenations:
dev = "npm run dev --port {{ (repo ~ '-' ~ branch) | hash_port }}"
```
+### Worktrunk Functions
+
+Templates also support functions for dynamic lookups:
+
+| Function | Example | Description |
+|----------|---------|-------------|
+| `worktree_path(branch)` | `{{ worktree_path("main") }}` | Look up the path of a branch's worktree |
+
+The `worktree_path` function returns the filesystem path of a worktree given a branch name, or an empty string if no worktree exists for that branch. This is useful for referencing files in other worktrees:
+
+```toml
+[post-create]
+# Copy config from main worktree
+setup = "cp {{ worktree_path('main') }}/config.local {{ worktree_path }}"
+```
+
### JSON context
Hooks also receive context as JSON on stdin, enabling hooks in any language:
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index f3d700182..1c48e9904 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -154,7 +154,7 @@ fn expand_commands(
let mut result = Vec::new();
for cmd in commands {
- let expanded_str = expand_template(&cmd.template, &vars, true).map_err(|e| {
+ let expanded_str = expand_template(&cmd.template, &vars, true, ctx.repo).map_err(|e| {
anyhow::anyhow!(
"Failed to expand command template '{}': {}",
cmd.template,
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rs
index 2a0cc1523..b35978447 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -86,7 +86,7 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {
.collect();
// Expand template with full context (shell-escaped)
- let command = expand_template(&command_template, &vars, true)
+ let command = expand_template(&command_template, &vars, true, &repo)
.map_err(|e| anyhow::anyhow!("Template expansion failed: {e}"))?;
// Build JSON context for stdin
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index 07a92dd8a..d1ddfac8f 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -626,6 +626,6 @@ fn expand_command_template(template: &str, ctx: &CommandContext, hook_type: Hook
.collect();
// Use the standard template expansion (shell-escaped)
- worktrunk::config::expand_template(template, &vars, true)
+ worktrunk::config::expand_template(template, &vars, true, ctx.repo)
.unwrap_or_else(|_| template.to_string())
}
diff --git a/src/commands/list/collect_progressive_impl.rs b/src/commands/list/collect_progressive_impl.rs
index 15ddfaa3c..cfc27f138 100644
--- a/src/commands/list/collect_progressive_impl.rs
+++ b/src/commands/list/collect_progressive_impl.rs
@@ -261,7 +261,7 @@ pub fn work_items_for_worktree(
wt.branch.as_ref().and_then(|branch| {
let mut vars = std::collections::HashMap::new();
vars.insert("branch", branch.as_str());
- worktrunk::config::expand_template(template, &vars, false).ok()
+ worktrunk::config::expand_template(template, &vars, false, repo).ok()
})
});
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 24e3b1d6f..98600bc42 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -220,7 +220,7 @@ pub fn compute_worktree_path(
})?;
let relative_path = config
- .format_path(repo_name, branch)
+ .format_path(repo_name, branch, repo)
.map_err(|e| anyhow::anyhow!("Failed to format worktree path: {e}"))?;
Ok(repo_root.join(relative_path).normalize())
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 7ac9482ad..9112ffc80 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -6,26 +6,13 @@
//!
//! All templates support Jinja2 syntax including filters, conditionals, and loops.
//!
-//! # Custom Filters
-//!
-//! - `sanitize` — Replace `/` and `\` with `-` for filesystem-safe names
-//! ```text
-//! {{ branch | sanitize }} → feature-foo
-//! ```
-//!
-//! - `sanitize_db` — Transform to database-safe identifier (`[a-z0-9_]`, max 63 chars)
-//! ```text
-//! {{ branch | sanitize_db }} → feature_auth_oauth2
-//! ```
-//!
-//! - `hash_port` — Hash a string to a deterministic port number (10000-19999)
-//! ```text
-//! {{ branch | hash_port }} → 12472
-//! {{ (repo ~ "-" ~ branch) | hash_port }} → 15839
-//! ```
+//! See `wt hook --help` for available filters and functions.
use minijinja::{Environment, Value};
+use crate::git::Repository;
+use crate::path::to_posix_path;
+
/// Known template variables available in hook commands.
///
/// These are populated by `build_hook_context()` in `command_executor.rs`.
@@ -178,35 +165,21 @@ fn short_hash(s: &str) -> String {
/// * `vars` - Variables to substitute
/// * `shell_escape` - If true, shell-escape all values for safe command execution.
/// If false, substitute values literally (for filesystem paths).
+/// * `repo` - Repository for looking up worktree paths
///
/// # Filters
/// - `sanitize` — Replace `/` and `\` with `-` for filesystem-safe paths
/// - `sanitize_db` — Transform to database-safe identifier (`[a-z0-9_]`, max 63 chars)
/// - `hash_port` — Hash to deterministic port number (10000-19999)
///
-/// # Examples
-/// ```
-/// use worktrunk::config::expand_template;
-/// use std::collections::HashMap;
-///
-/// // Raw branch name
-/// let mut vars = HashMap::new();
-/// 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");
-///
-/// // Sanitized branch name for filesystem paths
-/// let mut vars = HashMap::new();
-/// vars.insert("branch", "feature/foo");
-/// vars.insert("main_worktree", "myrepo");
-/// let path = expand_template("{{ main_worktree }}.{{ branch | sanitize }}", &vars, false).unwrap();
-/// assert_eq!(path, "myrepo.feature-foo");
-/// ```
+/// # Functions
+/// - `worktree_path(branch)` — Look up the filesystem path of a branch's worktree
+/// Returns empty string if branch has no worktree.
pub fn expand_template(
template: &str,
vars: &HashMap<&str, &str>,
shell_escape: bool,
+ repo: &Repository,
) -> Result<String, String> {
use shell_escape::escape;
use std::borrow::Cow;
@@ -238,6 +211,17 @@ pub fn expand_template(
});
env.add_filter("hash_port", |value: String| string_to_port(&value));
+ // Register worktree_path function for looking up branch worktree paths
+ let repo_clone = repo.clone();
+ env.add_function("worktree_path", move |branch: String| -> String {
+ repo_clone
+ .worktree_for_branch(&branch)
+ .ok()
+ .flatten()
+ .map(|p| to_posix_path(&p.to_string_lossy()))
+ .unwrap_or_default()
+ });
+
let tmpl = env
.template_from_str(template)
.map_err(|e| format!("Template syntax error: {}", e))?;
@@ -250,6 +234,29 @@ pub fn expand_template(
mod tests {
use super::*;
+ /// Test fixture that creates a real temporary git repository.
+ struct TestRepo {
+ _dir: tempfile::TempDir,
+ repo: Repository,
+ }
+
+ impl TestRepo {
+ fn new() -> Self {
+ let dir = tempfile::tempdir().unwrap();
+ std::process::Command::new("git")
+ .args(["init"])
+ .current_dir(dir.path())
+ .output()
+ .unwrap();
+ let repo = Repository::at(dir.path()).unwrap();
+ Self { _dir: dir, repo }
+ }
+ }
+
+ fn test_repo() -> TestRepo {
+ TestRepo::new()
+ }
+
#[test]
fn test_sanitize_branch_name() {
let cases = [
@@ -381,157 +388,174 @@ mod tests {
#[test]
fn test_expand_template_basic() {
+ let test = test_repo();
+
// Single variable
let mut vars = HashMap::new();
vars.insert("name", "world");
assert_eq!(
- expand_template("Hello {{ name }}", &vars, false).unwrap(),
+ expand_template("Hello {{ name }}", &vars, false, &test.repo).unwrap(),
"Hello world"
);
// Multiple variables
vars.insert("repo", "myrepo");
assert_eq!(
- expand_template("{{ repo }}/{{ name }}", &vars, false).unwrap(),
+ expand_template("{{ repo }}/{{ name }}", &vars, false, &test.repo).unwrap(),
"myrepo/world"
);
// Empty/static cases
let empty: HashMap<&str, &str> = HashMap::new();
- assert_eq!(expand_template("", &empty, false).unwrap(), "");
+ assert_eq!(expand_template("", &empty, false, &test.repo).unwrap(), "");
assert_eq!(
- expand_template("static text", &empty, false).unwrap(),
+ expand_template("static text", &empty, false, &test.repo).unwrap(),
"static text"
);
assert_eq!(
- expand_template("no {{ variables }} here", &empty, false).unwrap(),
+ expand_template("no {{ variables }} here", &empty, false, &test.repo).unwrap(),
"no here"
);
}
#[test]
fn test_expand_template_shell_escape() {
+ let test = test_repo();
let mut vars = HashMap::new();
vars.insert("path", "my path");
- let expanded = expand_template("cd {{ path }}", &vars, true).unwrap();
+ let expanded = expand_template("cd {{ path }}", &vars, true, &test.repo).unwrap();
assert!(expanded.contains("'my path'") || expanded.contains("my\\ path"));
// Command injection prevention
vars.insert("arg", "test;rm -rf");
- let expanded = expand_template("echo {{ arg }}", &vars, true).unwrap();
+ let expanded = expand_template("echo {{ arg }}", &vars, true, &test.repo).unwrap();
assert!(!expanded.contains(";rm") || expanded.contains("'"));
// No escape for literal mode
vars.insert("branch", "feature/foo");
assert_eq!(
- expand_template("{{ branch }}", &vars, false).unwrap(),
+ expand_template("{{ branch }}", &vars, false, &test.repo).unwrap(),
"feature/foo"
);
}
#[test]
fn test_expand_template_errors() {
+ let test = test_repo();
let vars = HashMap::new();
assert!(
- expand_template("{{ unclosed", &vars, false)
+ expand_template("{{ unclosed", &vars, false, &test.repo)
.unwrap_err()
.contains("syntax error")
);
- assert!(expand_template("{{ 1 + }}", &vars, false).is_err());
+ assert!(expand_template("{{ 1 + }}", &vars, false, &test.repo).is_err());
}
#[test]
fn test_expand_template_jinja_features() {
+ let test = test_repo();
let mut vars = HashMap::new();
vars.insert("debug", "true");
assert_eq!(
- expand_template("{% if debug %}DEBUG{% endif %}", &vars, false).unwrap(),
+ expand_template("{% if debug %}DEBUG{% endif %}", &vars, false, &test.repo).unwrap(),
"DEBUG"
);
vars.insert("debug", "");
assert_eq!(
- expand_template("{% if debug %}DEBUG{% endif %}", &vars, false).unwrap(),
+ expand_template("{% if debug %}DEBUG{% endif %}", &vars, false, &test.repo).unwrap(),
""
);
let empty: HashMap<&str, &str> = HashMap::new();
assert_eq!(
- expand_template("{{ missing | default('fallback') }}", &empty, false).unwrap(),
+ expand_template(
+ "{{ missing | default('fallback') }}",
+ &empty,
+ false,
+ &test.repo
+ )
+ .unwrap(),
"fallback"
);
vars.insert("name", "hello");
assert_eq!(
- expand_template("{{ name | upper }}", &vars, false).unwrap(),
+ expand_template("{{ name | upper }}", &vars, false, &test.repo).unwrap(),
"HELLO"
);
}
#[test]
fn test_expand_template_sanitize_filter() {
+ let test = test_repo();
let mut vars = HashMap::new();
vars.insert("branch", "feature/foo");
assert_eq!(
- expand_template("{{ branch | sanitize }}", &vars, false).unwrap(),
+ expand_template("{{ branch | sanitize }}", &vars, false, &test.repo).unwrap(),
"feature-foo"
);
// Backslashes are also sanitized
vars.insert("branch", "feature\\bar");
assert_eq!(
- expand_template("{{ branch | sanitize }}", &vars, false).unwrap(),
+ expand_template("{{ branch | sanitize }}", &vars, false, &test.repo).unwrap(),
"feature-bar"
);
// Multiple slashes
vars.insert("branch", "user/feature/task");
assert_eq!(
- expand_template("{{ branch | sanitize }}", &vars, false).unwrap(),
+ expand_template("{{ branch | sanitize }}", &vars, false, &test.repo).unwrap(),
"user-feature-task"
);
// Raw branch is unchanged
vars.insert("branch", "feature/foo");
assert_eq!(
- expand_template("{{ branch }}", &vars, false).unwrap(),
+ expand_template("{{ branch }}", &vars, false, &test.repo).unwrap(),
"feature/foo"
);
}
#[test]
fn test_expand_template_sanitize_db_filter() {
+ let test = test_repo();
let mut vars = HashMap::new();
// Basic transformation (with hash suffix)
vars.insert("branch", "feature/auth-oauth2");
- let result = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ let result =
+ expand_template("{{ branch | sanitize_db }}", &vars, false, &test.repo).unwrap();
assert!(result.starts_with("feature_auth_oauth2_"), "got: {result}");
// Leading digit gets underscore prefix
vars.insert("branch", "123-bug-fix");
- let result = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ let result =
+ expand_template("{{ branch | sanitize_db }}", &vars, false, &test.repo).unwrap();
assert!(result.starts_with("_123_bug_fix_"), "got: {result}");
// Uppercase conversion
vars.insert("branch", "UPPERCASE.Branch");
- let result = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ let result =
+ expand_template("{{ branch | sanitize_db }}", &vars, false, &test.repo).unwrap();
assert!(result.starts_with("uppercase_branch_"), "got: {result}");
// Raw branch is unchanged
vars.insert("branch", "feature/foo");
assert_eq!(
- expand_template("{{ branch }}", &vars, false).unwrap(),
+ expand_template("{{ branch }}", &vars, false, &test.repo).unwrap(),
"feature/foo"
);
}
#[test]
fn test_expand_template_trailing_newline() {
+ let test = test_repo();
let mut vars = HashMap::new();
vars.insert("cmd", "echo hello");
assert!(
- expand_template("{{ cmd }}\n", &vars, true)
+ expand_template("{{ cmd }}\n", &vars, true, &test.repo)
.unwrap()
.ends_with('\n')
);
@@ -549,19 +573,32 @@ mod tests {
#[test]
fn test_hash_port_filter() {
+ let test = test_repo();
let mut vars = HashMap::new();
vars.insert("branch", "feature-foo");
vars.insert("repo", "myrepo");
// Filter produces a number in range
- let result = expand_template("{{ branch | hash_port }}", &vars, false).unwrap();
+ let result = expand_template("{{ branch | hash_port }}", &vars, false, &test.repo).unwrap();
let port: u16 = result.parse().expect("should be a number");
assert!((10000..20000).contains(&port));
// Concatenation produces different (but deterministic) result
- let r1 = expand_template("{{ (repo ~ '-' ~ branch) | hash_port }}", &vars, false).unwrap();
+ let r1 = expand_template(
+ "{{ (repo ~ '-' ~ branch) | hash_port }}",
+ &vars,
+ false,
+ &test.repo,
+ )
+ .unwrap();
let r1_port: u16 = r1.parse().expect("should be a number");
- let r2 = expand_template("{{ (repo ~ '-' ~ branch) | hash_port }}", &vars, false).unwrap();
+ let r2 = expand_template(
+ "{{ (repo ~ '-' ~ branch) | hash_port }}",
+ &vars,
+ false,
+ &test.repo,
+ )
+ .unwrap();
let r2_port: u16 = r2.parse().expect("should be a number");
assert!((10000..20000).contains(&r1_port));
diff --git a/src/config/mod.rs b/src/config/mod.rs
index e9c52ef6e..1689de67e 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -44,6 +44,30 @@ pub use user::{
#[cfg(test)]
mod tests {
use super::*;
+ use crate::git::Repository;
+
+ /// Test fixture that creates a real temporary git repository.
+ struct TestRepo {
+ _dir: tempfile::TempDir,
+ repo: Repository,
+ }
+
+ impl TestRepo {
+ fn new() -> Self {
+ let dir = tempfile::tempdir().unwrap();
+ std::process::Command::new("git")
+ .args(["init"])
+ .current_dir(dir.path())
+ .output()
+ .unwrap();
+ let repo = Repository::at(dir.path()).unwrap();
+ Self { _dir: dir, repo }
+ }
+ }
+
+ fn test_repo() -> TestRepo {
+ TestRepo::new()
+ }
#[test]
fn test_config_serialization() {
@@ -80,55 +104,68 @@ mod tests {
#[test]
fn test_format_worktree_path() {
+ let test = test_repo();
let config = WorktrunkConfig {
worktree_path: Some("{{ main_worktree }}.{{ branch }}".to_string()),
..Default::default()
};
assert_eq!(
- config.format_path("myproject", "feature-x").unwrap(),
+ config
+ .format_path("myproject", "feature-x", &test.repo)
+ .unwrap(),
"myproject.feature-x"
);
}
#[test]
fn test_format_worktree_path_custom_template() {
+ let test = test_repo();
let config = WorktrunkConfig {
worktree_path: Some("{{ main_worktree }}-{{ branch }}".to_string()),
..Default::default()
};
assert_eq!(
- config.format_path("myproject", "feature-x").unwrap(),
+ config
+ .format_path("myproject", "feature-x", &test.repo)
+ .unwrap(),
"myproject-feature-x"
);
}
#[test]
fn test_format_worktree_path_only_branch() {
+ let test = test_repo();
let config = WorktrunkConfig {
worktree_path: Some(".worktrees/{{ main_worktree }}/{{ branch }}".to_string()),
..Default::default()
};
assert_eq!(
- config.format_path("myproject", "feature-x").unwrap(),
+ config
+ .format_path("myproject", "feature-x", &test.repo)
+ .unwrap(),
".worktrees/myproject/feature-x"
);
}
#[test]
fn test_format_worktree_path_with_slashes() {
+ let test = test_repo();
// Use {{ branch | sanitize }} to replace slashes with dashes
let config = WorktrunkConfig {
worktree_path: Some("{{ main_worktree }}.{{ branch | sanitize }}".to_string()),
..Default::default()
};
assert_eq!(
- config.format_path("myproject", "feature/foo").unwrap(),
+ config
+ .format_path("myproject", "feature/foo", &test.repo)
+ .unwrap(),
"myproject.feature-foo"
);
}
#[test]
fn test_format_worktree_path_with_multiple_slashes() {
+ let test = test_repo();
let config = WorktrunkConfig {
worktree_path: Some(
".worktrees/{{ main_worktree }}/{{ branch | sanitize }}".to_string(),
@@ -136,13 +173,16 @@ mod tests {
..Default::default()
};
assert_eq!(
- config.format_path("myproject", "feature/sub/task").unwrap(),
+ config
+ .format_path("myproject", "feature/sub/task", &test.repo)
+ .unwrap(),
".worktrees/myproject/feature-sub-task"
);
}
#[test]
fn test_format_worktree_path_with_backslashes() {
+ let test = test_repo();
// Windows-style path separators should also be sanitized
let config = WorktrunkConfig {
worktree_path: Some(
@@ -151,20 +191,25 @@ mod tests {
..Default::default()
};
assert_eq!(
- config.format_path("myproject", "feature\\foo").unwrap(),
+ config
+ .format_path("myproject", "feature\\foo", &test.repo)
+ .unwrap(),
".worktrees/myproject/feature-foo"
);
}
#[test]
fn test_format_worktree_path_raw_branch() {
+ let test = test_repo();
// {{ branch }} without filter gives raw branch name
let config = WorktrunkConfig {
worktree_path: Some("{{ main_worktree }}.{{ branch }}".to_string()),
..Default::default()
};
assert_eq!(
- config.format_path("myproject", "feature/foo").unwrap(),
+ config
+ .format_path("myproject", "feature/foo", &test.repo)
+ .unwrap(),
"myproject.feature/foo"
);
}
@@ -553,10 +598,17 @@ task2 = "echo 'Task 2 running' > task2.txt"
fn test_expand_template_basic() {
use std::collections::HashMap;
+ let test = test_repo();
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();
+ let result = expand_template(
+ "../{{ main_worktree }}.{{ branch }}",
+ &vars,
+ true,
+ &test.repo,
+ )
+ .unwrap();
assert_eq!(result, "../myrepo.feature-x");
}
@@ -564,13 +616,20 @@ task2 = "echo 'Task 2 running' > task2.txt"
fn test_expand_template_sanitizes_branch() {
use std::collections::HashMap;
+ let test = test_repo();
+
// 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", "feature/foo");
- let result =
- expand_template("{{ main_worktree }}/{{ branch | sanitize }}", &vars, false).unwrap();
+ let result = expand_template(
+ "{{ main_worktree }}/{{ branch | sanitize }}",
+ &vars,
+ false,
+ &test.repo,
+ )
+ .unwrap();
assert_eq!(result, "myrepo/feature-foo");
let mut vars = HashMap::new();
@@ -580,6 +639,7 @@ task2 = "echo 'Task 2 running' > task2.txt"
".worktrees/{{ main_worktree }}/{{ branch | sanitize }}",
&vars,
false,
+ &test.repo,
)
.unwrap();
assert_eq!(result, ".worktrees/myrepo/feat-bar");
@@ -597,6 +657,7 @@ task2 = "echo 'Task 2 running' > task2.txt"
"{{ repo_root }}/target -> {{ worktree }}/target",
&vars,
true,
+ &test_repo().repo,
)
.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 7fc0d10a0..3faf74aa6 100644
--- a/src/config/test.rs
+++ b/src/config/test.rs
@@ -4,8 +4,32 @@
//! edge cases in template variable substitution.
use super::expand_template;
+use crate::git::Repository;
use std::collections::HashMap;
+/// Test fixture that creates a real temporary git repository.
+struct TestRepo {
+ _dir: tempfile::TempDir,
+ repo: Repository,
+}
+
+impl TestRepo {
+ fn new() -> Self {
+ let dir = tempfile::tempdir().unwrap();
+ std::process::Command::new("git")
+ .args(["init"])
+ .current_dir(dir.path())
+ .output()
+ .unwrap();
+ let repo = Repository::at(dir.path()).unwrap();
+ Self { _dir: dir, repo }
+ }
+}
+
+fn test_repo() -> TestRepo {
+ TestRepo::new()
+}
+
/// Helper to build vars with common fields
fn vars_with_branch(branch: &str) -> HashMap<&str, &str> {
let mut vars = HashMap::new();
@@ -17,24 +41,33 @@ fn vars_with_branch(branch: &str) -> HashMap<&str, &str> {
#[test]
fn test_expand_template_normal() {
+ let test = test_repo();
let vars = vars_with_branch("feature");
- let result = expand_template("echo {{ branch }} {{ main_worktree }}", &vars, true).unwrap();
+ let result = expand_template(
+ "echo {{ branch }} {{ main_worktree }}",
+ &vars,
+ true,
+ &test.repo,
+ )
+ .unwrap();
assert_eq!(result, "echo feature myrepo");
}
#[test]
fn test_expand_template_branch_with_slashes() {
+ let test = test_repo();
// 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();
+ let result = expand_template("echo {{ branch | sanitize }}", &vars, true, &test.repo).unwrap();
assert_eq!(result, "echo feature-nested-branch");
}
#[test]
fn test_expand_template_branch_raw_with_slashes() {
+ let test = test_repo();
// Raw branch preserves slashes
let vars = vars_with_branch("feature/nested/branch");
- let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
+ let result = expand_template("echo {{ branch }}", &vars, true, &test.repo).unwrap();
assert_eq!(result, "echo feature/nested/branch");
}
@@ -42,8 +75,16 @@ fn test_expand_template_branch_raw_with_slashes() {
#[test]
#[cfg(unix)]
fn test_expand_template_branch_escaping() {
- let expand =
- |input| expand_template("echo {{ branch }}", &vars_with_branch(input), true).unwrap();
+ let test = test_repo();
+ let expand = |input| {
+ expand_template(
+ "echo {{ branch }}",
+ &vars_with_branch(input),
+ true,
+ &test.repo,
+ )
+ .unwrap()
+ };
assert_eq!(expand("feature name"), "echo 'feature name'"); // spaces
assert_eq!(expand("feature$(whoami)"), "echo 'feature$(whoami)'"); // command sub
@@ -53,19 +94,22 @@ fn test_expand_template_branch_escaping() {
#[test]
#[cfg(unix)]
fn snapshot_expand_template_branch_with_quotes() {
+ let test = test_repo();
let vars = vars_with_branch("feature'test");
- let result = expand_template("echo '{{ branch }}'", &vars, true).unwrap();
+ let result = expand_template("echo '{{ branch }}'", &vars, true, &test.repo).unwrap();
insta::assert_snapshot!(result, @r"echo ''feature'\''test''");
}
#[test]
#[cfg(unix)]
fn test_expand_template_extra_vars_path_escaping() {
+ let test = test_repo();
let expand = |path| {
expand_template(
"cd {{ worktree }}",
&HashMap::from([("worktree", path)]),
true,
+ &test.repo,
)
.unwrap()
};
@@ -80,28 +124,31 @@ fn test_expand_template_extra_vars_path_escaping() {
#[test]
#[cfg(unix)]
fn snapshot_expand_template_extra_vars_with_command_substitution() {
+ let test = test_repo();
let mut extras = HashMap::new();
extras.insert("target", "main; rm -rf /");
- let result = expand_template("git merge {{ target }}", &extras, true).unwrap();
+ let result = expand_template("git merge {{ target }}", &extras, true, &test.repo).unwrap();
insta::assert_snapshot!(result, @"git merge 'main; rm -rf /'");
}
#[test]
fn test_expand_template_variable_override() {
+ let test = test_repo();
// Variables in the hashmap take precedence
let mut vars = HashMap::new();
vars.insert("branch", "overridden");
- let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
+ let result = expand_template("echo {{ branch }}", &vars, true, &test.repo).unwrap();
assert_eq!(result, "echo overridden");
}
#[test]
fn test_expand_template_missing_variable() {
+ let test = test_repo();
// What happens with undefined variables?
let vars: HashMap<&str, &str> = HashMap::new();
- let result = expand_template("echo {{ undefined }}", &vars, true).unwrap();
+ let result = expand_template("echo {{ undefined }}", &vars, true, &test.repo).unwrap();
// minijinja will render undefined variables as empty string
assert_eq!(result, "echo ");
@@ -110,9 +157,10 @@ fn test_expand_template_missing_variable() {
#[test]
#[cfg(unix)]
fn test_expand_template_empty_branch() {
+ let test = test_repo();
let mut vars = HashMap::new();
vars.insert("branch", "");
- let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
+ let result = expand_template("echo {{ branch }}", &vars, true, &test.repo).unwrap();
// Empty string is shell-escaped to ''
assert_eq!(result, "echo ''");
@@ -121,9 +169,10 @@ fn test_expand_template_empty_branch() {
#[test]
#[cfg(unix)]
fn test_expand_template_unicode_in_branch() {
+ let test = test_repo();
// Unicode characters in branch name are shell-escaped
let vars = vars_with_branch("feature-\u{1F680}");
- let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
+ let result = expand_template("echo {{ branch }}", &vars, true, &test.repo).unwrap();
// Unicode is preserved but quoted for shell safety
assert_eq!(result, "echo 'feature-\u{1F680}'");
@@ -131,10 +180,11 @@ fn test_expand_template_unicode_in_branch() {
#[test]
fn test_expand_template_backslash_in_branch() {
+ let test = test_repo();
// 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();
+ let result = expand_template("path/{{ branch | sanitize }}", &vars, false, &test.repo).unwrap();
// Backslashes are replaced with dashes by sanitize filter
assert_eq!(result, "path/feature-branch");
@@ -142,6 +192,7 @@ fn test_expand_template_backslash_in_branch() {
#[test]
fn test_expand_template_multiple_replacements() {
+ let test = test_repo();
let mut vars = vars_with_branch("feature");
vars.insert("worktree", "/path/to/wt");
vars.insert("target", "develop");
@@ -150,6 +201,7 @@ fn test_expand_template_multiple_replacements() {
"cd {{ worktree }} && git merge {{ target }} from {{ branch }}",
&vars,
true,
+ &test.repo,
)
.unwrap();
@@ -158,18 +210,20 @@ fn test_expand_template_multiple_replacements() {
#[test]
fn test_expand_template_curly_braces_without_variables() {
+ let test = test_repo();
// Just curly braces, not variables
let vars: HashMap<&str, &str> = HashMap::new();
- let result = expand_template("echo {}", &vars, true).unwrap();
+ let result = expand_template("echo {}", &vars, true, &test.repo).unwrap();
assert_eq!(result, "echo {}");
}
#[test]
fn test_expand_template_nested_curly_braces() {
+ let test = test_repo();
// Nested braces - minijinja doesn't support {{{ syntax, use literal curly braces instead
let vars = vars_with_branch("main");
- let result = expand_template("echo {{ '{' ~ branch ~ '}' }}", &vars, true).unwrap();
+ let result = expand_template("echo {{ '{' ~ branch ~ '}' }}", &vars, true, &test.repo).unwrap();
// Renders as {main}
assert_eq!(result, "echo {main}");
@@ -199,10 +253,11 @@ fn snapshot_shell_escaping_special_chars() {
("brackets", "feature[0-9]"),
];
+ let test = test_repo();
let mut results = Vec::new();
for (name, branch) in test_cases {
let vars = vars_with_branch(branch);
- let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
+ let result = expand_template("echo {{ branch }}", &vars, true, &test.repo).unwrap();
results.push((name, branch, result));
}
@@ -220,10 +275,11 @@ fn snapshot_shell_escaping_quotes() {
("multiple_single", "don't'panic"),
];
+ let test = test_repo();
let mut results = Vec::new();
for (name, branch) in test_cases {
let vars = vars_with_branch(branch);
- let result = expand_template("echo {{ branch }}", &vars, true).unwrap();
+ let result = expand_template("echo {{ branch }}", &vars, true, &test.repo).unwrap();
results.push((name, branch, result));
}
@@ -242,12 +298,18 @@ fn snapshot_shell_escaping_paths() {
("unicode", "/path/to/\u{1F680}/worktree"),
];
+ let test = test_repo();
let mut results = Vec::new();
for (name, path) in test_cases {
let mut vars = vars_with_branch("main");
vars.insert("worktree", path);
- let result =
- expand_template("cd {{ worktree }} && echo {{ branch }}", &vars, true).unwrap();
+ let result = expand_template(
+ "cd {{ worktree }} && echo {{ branch }}",
+ &vars,
+ true,
+ &test.repo,
+ )
+ .unwrap();
results.push((name, path, result));
}
@@ -277,6 +339,7 @@ fn snapshot_complex_templates() {
),
];
+ let test = test_repo();
let mut results = Vec::new();
for (name, template, branch) in test_cases {
let mut vars = HashMap::new();
@@ -284,7 +347,7 @@ fn snapshot_complex_templates() {
vars.insert("main_worktree", "/repo/path");
vars.insert("worktree", "/path with spaces/wt");
vars.insert("target", "main; rm -rf /");
- let result = expand_template(template, &vars, true).unwrap();
+ let result = expand_template(template, &vars, true, &test.repo).unwrap();
results.push((name, template, branch, result));
}
@@ -295,20 +358,24 @@ fn snapshot_complex_templates() {
#[test]
fn test_expand_template_literal_normal() {
+ let test = test_repo();
let mut vars = HashMap::new();
vars.insert("main_worktree", "myrepo");
vars.insert("branch", "feature");
- let result = expand_template("{{ main_worktree }}.{{ branch }}", &vars, false).unwrap();
+ let result =
+ expand_template("{{ main_worktree }}.{{ branch }}", &vars, false, &test.repo).unwrap();
assert_eq!(result, "myrepo.feature");
}
#[test]
fn test_expand_template_literal_unicode_no_escaping() {
+ let test = test_repo();
// Unicode should NOT be shell-escaped in filesystem paths
let mut vars = HashMap::new();
vars.insert("main_worktree", "myrepo");
vars.insert("branch", "test-\u{2282}");
- let result = expand_template("{{ main_worktree }}.{{ branch }}", &vars, false).unwrap();
+ let result =
+ expand_template("{{ main_worktree }}.{{ branch }}", &vars, false, &test.repo).unwrap();
// Path should contain literal unicode, NO quotes
assert_eq!(result, "myrepo.test-\u{2282}");
assert!(
@@ -319,11 +386,13 @@ fn test_expand_template_literal_unicode_no_escaping() {
#[test]
fn test_expand_template_literal_spaces_no_escaping() {
+ let test = test_repo();
// Spaces should NOT be shell-escaped (filesystem paths can have spaces)
let mut vars = HashMap::new();
vars.insert("main_worktree", "my repo");
vars.insert("branch", "feature name");
- let result = expand_template("{{ main_worktree }}.{{ branch }}", &vars, false).unwrap();
+ let result =
+ expand_template("{{ main_worktree }}.{{ branch }}", &vars, false, &test.repo).unwrap();
// No shell quotes around spaces
assert_eq!(result, "my repo.feature name");
assert!(
@@ -334,26 +403,33 @@ fn test_expand_template_literal_spaces_no_escaping() {
#[test]
fn test_expand_template_literal_sanitizes_slashes() {
+ let test = test_repo();
// Use {{ branch | sanitize }} to replace slashes with dashes
let mut vars = HashMap::new();
vars.insert("main_worktree", "myrepo");
vars.insert("branch", "feature/nested/branch");
- let result =
- expand_template("{{ main_worktree }}.{{ branch | sanitize }}", &vars, false).unwrap();
+ let result = expand_template(
+ "{{ main_worktree }}.{{ branch | sanitize }}",
+ &vars,
+ false,
+ &test.repo,
+ )
+ .unwrap();
assert_eq!(result, "myrepo.feature-nested-branch");
}
#[test]
#[cfg(unix)]
fn test_expand_template_literal_vs_escaped_unicode() {
+ let test = test_repo();
// Demonstrate the difference between literal and escaped expansion
let mut vars = HashMap::new();
vars.insert("main_worktree", "myrepo");
vars.insert("branch", "test-\u{2282}");
let template = "{{ main_worktree }}.{{ branch }}";
- let literal_result = expand_template(template, &vars, false).unwrap();
- let escaped_result = expand_template(template, &vars, true).unwrap();
+ let literal_result = expand_template(template, &vars, false, &test.repo).unwrap();
+ let escaped_result = expand_template(template, &vars, true, &test.repo).unwrap();
// Literal has no quotes
assert_eq!(literal_result, "myrepo.test-\u{2282}");
diff --git a/src/config/user.rs b/src/config/user.rs
index 593ed4707..f597d91e9 100644
--- a/src/config/user.rs
+++ b/src/config/user.rs
@@ -429,23 +429,19 @@ impl WorktrunkConfig {
/// # Arguments
/// * `main_worktree` - Main worktree directory name (replaces {{ main_worktree }} in template)
/// * `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> {
+ /// * `repo` - Repository for template function access
+ pub fn format_path(
+ &self,
+ main_worktree: &str,
+ branch: &str,
+ repo: &crate::git::Repository,
+ ) -> Result<String, String> {
use std::collections::HashMap;
let mut vars = HashMap::new();
vars.insert("main_worktree", main_worktree);
vars.insert("repo", main_worktree);
vars.insert("branch", branch);
- expand_template(&self.worktree_path(), &vars, false)
+ expand_template(&self.worktree_path(), &vars, false, repo)
}
/// Check if a command is approved for the given project.
@@ -782,6 +778,30 @@ pub fn find_unknown_keys(contents: &str) -> Vec<String> {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::git::Repository;
+
+ /// Test fixture that creates a real temporary git repository.
+ struct TestRepo {
+ _dir: tempfile::TempDir,
+ repo: Repository,
+ }
+
+ impl TestRepo {
+ fn new() -> Self {
+ let dir = tempfile::tempdir().unwrap();
+ std::process::Command::new("git")
+ .args(["init"])
+ .current_dir(dir.path())
+ .output()
+ .unwrap();
+ let repo = Repository::at(dir.path()).unwrap();
+ Self { _dir: dir, repo }
+ }
+ }
+
+ fn test_repo() -> TestRepo {
+ TestRepo::new()
+ }
#[test]
fn test_find_unknown_keys_empty() {
@@ -1045,18 +1065,22 @@ rename-tab = "echo 'switched'"
#[test]
fn test_worktrunk_config_format_path() {
+ let test = test_repo();
let config = WorktrunkConfig::default();
- let path = config.format_path("myrepo", "feature/branch").unwrap();
+ let path = config
+ .format_path("myrepo", "feature/branch", &test.repo)
+ .unwrap();
assert_eq!(path, "../myrepo.feature-branch");
}
#[test]
fn test_worktrunk_config_format_path_custom_template() {
+ let test = test_repo();
let config = WorktrunkConfig {
worktree_path: Some(".worktrees/{{ branch }}".to_string()),
..Default::default()
};
- let path = config.format_path("myrepo", "feature").unwrap();
+ let path = config.format_path("myrepo", "feature", &test.repo).unwrap();
assert_eq!(path, ".worktrees/feature");
}
diff --git a/src/main.rs b/src/main.rs
index 4a0ea809b..861f84f8c 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1468,7 +1468,7 @@ fn main() {
.collect();
// Expand template variables in command (shell_escape: true for safety)
- let expanded_cmd = expand_template(&cmd, &vars, true).map_err(|e| {
+ let expanded_cmd = expand_template(&cmd, &vars, true, &repo).map_err(|e| {
anyhow::anyhow!("Failed to expand --execute template: {}", e)
})?;
@@ -1480,7 +1480,7 @@ fn main() {
let expanded_args: Result<Vec<_>, _> = execute_args
.iter()
.map(|arg| {
- expand_template(arg, &vars, false).map_err(|e| {
+ expand_template(arg, &vars, false, &repo).map_err(|e| {
anyhow::anyhow!("Failed to expand argument template: {}", e)
})
})
diff --git a/tests/integration_tests/doc_templates.rs b/tests/integration_tests/doc_templates.rs
index 64d20cb5e..fd7a3e4e0 100644
--- a/tests/integration_tests/doc_templates.rs
+++ b/tests/integration_tests/doc_templates.rs
@@ -7,7 +7,12 @@
//! Run with: `cargo test --test integration doc_templates`
use std::collections::HashMap;
+
+use rstest::rstest;
use worktrunk::config::expand_template;
+use worktrunk::git::Repository;
+
+use crate::common::{TestRepo, repo};
/// Helper to compute hash_port for a string.
///
@@ -23,8 +28,9 @@ fn hash_port(s: &str) -> u16 {
// Basic Variables (docs/content/hook.md: Template variables table)
// =============================================================================
-#[test]
-fn test_doc_basic_variables() {
+#[rstest]
+fn test_doc_basic_variables(repo: TestRepo) {
+ let repository = Repository::at(repo.root_path()).unwrap();
let mut vars = HashMap::new();
vars.insert("repo", "myproject");
vars.insert("branch", "feature/auth");
@@ -33,19 +39,19 @@ fn test_doc_basic_variables() {
// Each variable substitutes correctly
assert_eq!(
- expand_template("{{ repo }}", &vars, false).unwrap(),
+ expand_template("{{ repo }}", &vars, false, &repository).unwrap(),
"myproject"
);
assert_eq!(
- expand_template("{{ branch }}", &vars, false).unwrap(),
+ expand_template("{{ branch }}", &vars, false, &repository).unwrap(),
"feature/auth"
);
assert_eq!(
- expand_template("{{ worktree }}", &vars, false).unwrap(),
+ expand_template("{{ worktree }}", &vars, false, &repository).unwrap(),
"/home/user/myproject.feature-auth"
);
assert_eq!(
- expand_template("{{ default_branch }}", &vars, false).unwrap(),
+ expand_template("{{ default_branch }}", &vars, false, &repository).unwrap(),
"main"
);
}
@@ -55,21 +61,22 @@ fn test_doc_basic_variables() {
// "Replace `/` and `\` with `-`"
// =============================================================================
-#[test]
-fn test_doc_sanitize_filter() {
+#[rstest]
+fn test_doc_sanitize_filter(repo: TestRepo) {
let mut vars = HashMap::new();
+ let repository = Repository::at(repo.root_path()).unwrap();
// From docs: {{ branch | sanitize }} replaces / and \ with -
vars.insert("branch", "feature/foo");
assert_eq!(
- expand_template("{{ branch | sanitize }}", &vars, false).unwrap(),
+ expand_template("{{ branch | sanitize }}", &vars, false, &repository).unwrap(),
"feature-foo",
"sanitize should replace / with -"
);
vars.insert("branch", "user\\task");
assert_eq!(
- expand_template("{{ branch | sanitize }}", &vars, false).unwrap(),
+ expand_template("{{ branch | sanitize }}", &vars, false, &repository).unwrap(),
"user-task",
"sanitize should replace \\ with -"
);
@@ -77,7 +84,7 @@ fn test_doc_sanitize_filter() {
// Nested paths
vars.insert("branch", "user/feature/task");
assert_eq!(
- expand_template("{{ branch | sanitize }}", &vars, false).unwrap(),
+ expand_template("{{ branch | sanitize }}", &vars, false, &repository).unwrap(),
"user-feature-task",
"sanitize should handle multiple slashes"
);
@@ -88,14 +95,15 @@ fn test_doc_sanitize_filter() {
// "Transform to database-safe identifier ([a-z0-9_], max 63 chars)"
// =============================================================================
-#[test]
-fn test_doc_sanitize_db_filter() {
+#[rstest]
+fn test_doc_sanitize_db_filter(repo: TestRepo) {
let mut vars = HashMap::new();
+ let repository = Repository::at(repo.root_path()).unwrap();
// From docs: {{ branch | sanitize_db }} transforms to database-safe identifier
// Output includes a 3-character hash suffix for uniqueness
vars.insert("branch", "feature/auth-oauth2");
- let result = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ let result = expand_template("{{ branch | sanitize_db }}", &vars, false, &repository).unwrap();
assert!(
result.starts_with("feature_auth_oauth2_"),
"sanitize_db should replace non-alphanumeric with _ and lowercase, got: {result}"
@@ -103,7 +111,7 @@ fn test_doc_sanitize_db_filter() {
// Leading digits get underscore prefix
vars.insert("branch", "123-bug-fix");
- let result = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ let result = expand_template("{{ branch | sanitize_db }}", &vars, false, &repository).unwrap();
assert!(
result.starts_with("_123_bug_fix_"),
"sanitize_db should prefix leading digits with _, got: {result}"
@@ -111,7 +119,7 @@ fn test_doc_sanitize_db_filter() {
// Uppercase conversion
vars.insert("branch", "UPPERCASE.Branch");
- let result = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ let result = expand_template("{{ branch | sanitize_db }}", &vars, false, &repository).unwrap();
assert!(
result.starts_with("uppercase_branch_"),
"sanitize_db should convert to lowercase, got: {result}"
@@ -119,7 +127,7 @@ fn test_doc_sanitize_db_filter() {
// Consecutive underscores collapsed
vars.insert("branch", "a--b//c");
- let result = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ let result = expand_template("{{ branch | sanitize_db }}", &vars, false, &repository).unwrap();
assert!(
result.starts_with("a_b_c_"),
"sanitize_db should collapse consecutive underscores, got: {result}"
@@ -127,23 +135,24 @@ fn test_doc_sanitize_db_filter() {
// Different inputs that would otherwise collide get different suffixes
vars.insert("branch", "a-b");
- let result1 = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ let result1 = expand_template("{{ branch | sanitize_db }}", &vars, false, &repository).unwrap();
vars.insert("branch", "a_b");
- let result2 = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ let result2 = expand_template("{{ branch | sanitize_db }}", &vars, false, &repository).unwrap();
assert_ne!(
result1, result2,
"a-b and a_b should produce different outputs"
);
}
-#[test]
-fn test_doc_sanitize_db_truncation() {
+#[rstest]
+fn test_doc_sanitize_db_truncation(repo: TestRepo) {
+ let repository = Repository::at(repo.root_path()).unwrap();
let mut vars = HashMap::new();
// Truncates to 63 characters (PostgreSQL limit)
let long_branch = "a".repeat(100);
vars.insert("branch", long_branch.as_str());
- let result = expand_template("{{ branch | sanitize_db }}", &vars, false).unwrap();
+ let result = expand_template("{{ branch | sanitize_db }}", &vars, false, &repository).unwrap();
assert_eq!(
result.len(),
63,
@@ -156,12 +165,13 @@ fn test_doc_sanitize_db_truncation() {
// "Hash to port 10000-19999"
// =============================================================================
-#[test]
-fn test_doc_hash_port_filter() {
+#[rstest]
+fn test_doc_hash_port_filter(repo: TestRepo) {
let mut vars = HashMap::new();
vars.insert("branch", "feature-foo");
+ let repository = Repository::at(repo.root_path()).unwrap();
- let result = expand_template("{{ branch | hash_port }}", &vars, false).unwrap();
+ let result = expand_template("{{ branch | hash_port }}", &vars, false, &repository).unwrap();
let port: u16 = result.parse().expect("hash_port should produce a number");
assert!(
@@ -170,7 +180,7 @@ fn test_doc_hash_port_filter() {
);
// Deterministic
- let result2 = expand_template("{{ branch | hash_port }}", &vars, false).unwrap();
+ let result2 = expand_template("{{ branch | hash_port }}", &vars, false, &repository).unwrap();
assert_eq!(result, result2, "hash_port should be deterministic");
}
@@ -179,8 +189,8 @@ fn test_doc_hash_port_filter() {
// CRITICAL: These test the operator precedence issue from PR #373
// =============================================================================
-#[test]
-fn test_doc_hash_port_concatenation_precedence() {
+#[rstest]
+fn test_doc_hash_port_concatenation_precedence(repo: TestRepo) {
// From docs/content/tips-patterns.md:
// "The `'db-' ~ branch` concatenation hashes differently than plain `branch`"
//
@@ -189,9 +199,16 @@ fn test_doc_hash_port_concatenation_precedence() {
let mut vars = HashMap::new();
vars.insert("branch", "feature");
+ let repository = Repository::at(repo.root_path()).unwrap();
// With parentheses (correct, as documented)
- let with_parens = expand_template("{{ ('db-' ~ branch) | hash_port }}", &vars, false).unwrap();
+ let with_parens = expand_template(
+ "{{ ('db-' ~ branch) | hash_port }}",
+ &vars,
+ false,
+ &repository,
+ )
+ .unwrap();
let port_with_parens: u16 = with_parens.parse().unwrap();
// Verify it hashes the concatenated string
@@ -202,7 +219,13 @@ fn test_doc_hash_port_concatenation_precedence() {
);
// Without parentheses (what the bug was) - this hashes just "branch" and prepends "db-"
- let without_parens = expand_template("{{ 'db-' ~ branch | hash_port }}", &vars, false).unwrap();
+ let without_parens = expand_template(
+ "{{ 'db-' ~ branch | hash_port }}",
+ &vars,
+ false,
+ &repository,
+ )
+ .unwrap();
// The result should be different because of precedence
// Without parens: 'db-' ~ (branch | hash_port) = 'db-' ~ hash("feature")
@@ -220,16 +243,23 @@ fn test_doc_hash_port_concatenation_precedence() {
);
}
-#[test]
-fn test_doc_hash_port_repo_branch_concatenation() {
+#[rstest]
+fn test_doc_hash_port_repo_branch_concatenation(repo: TestRepo) {
// From docs/content/hook.md line 176:
// dev = "npm run dev --port {{ (repo ~ '-' ~ branch) | hash_port }}"
+ let repository = Repository::at(repo.root_path()).unwrap();
let mut vars = HashMap::new();
vars.insert("repo", "myapp");
vars.insert("branch", "feature");
- let result = expand_template("{{ (repo ~ '-' ~ branch) | hash_port }}", &vars, false).unwrap();
+ let result = expand_template(
+ "{{ (repo ~ '-' ~ branch) | hash_port }}",
+ &vars,
+ false,
+ &repository,
+ )
+ .unwrap();
let port: u16 = result.parse().unwrap();
// Should hash the full concatenated string
@@ -245,11 +275,12 @@ fn test_doc_hash_port_repo_branch_concatenation() {
// These test complete template strings from the documentation
// =============================================================================
-#[test]
-fn test_doc_example_docker_postgres() {
+#[rstest]
+fn test_doc_example_docker_postgres(repo: TestRepo) {
// From docs/content/tips-patterns.md lines 75-84:
// docker run ... -p {{ ('db-' ~ branch) | hash_port }}:5432
+ let repository = Repository::at(repo.root_path()).unwrap();
let mut vars = HashMap::new();
vars.insert("repo", "myproject");
vars.insert("branch", "feature-auth");
@@ -259,7 +290,7 @@ fn test_doc_example_docker_postgres() {
-p {{ ('db-' ~ branch) | hash_port }}:5432 \
postgres:16"#;
- let result = expand_template(template, &vars, false).unwrap();
+ let result = expand_template(template, &vars, false, &repository).unwrap();
// Check the container name uses sanitized branch
assert!(
@@ -275,18 +306,19 @@ fn test_doc_example_docker_postgres() {
);
}
-#[test]
-fn test_doc_example_database_url() {
+#[rstest]
+fn test_doc_example_database_url(repo: TestRepo) {
// From docs/content/tips-patterns.md lines 96-101:
// DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ repo }}
+ let repository = Repository::at(repo.root_path()).unwrap();
let mut vars = HashMap::new();
vars.insert("repo", "myproject");
vars.insert("branch", "feature");
let template = "DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ repo }}";
- let result = expand_template(template, &vars, false).unwrap();
+ let result = expand_template(template, &vars, false, &repository).unwrap();
let expected_port = hash_port("db-feature");
assert_eq!(
@@ -295,17 +327,18 @@ fn test_doc_example_database_url() {
);
}
-#[test]
-fn test_doc_example_dev_server() {
+#[rstest]
+fn test_doc_example_dev_server(repo: TestRepo) {
// From docs/content/hook.md lines 168-170:
// dev = "npm run dev -- --host {{ branch }}.lvh.me --port {{ branch | hash_port }}"
+ let repository = Repository::at(repo.root_path()).unwrap();
let mut vars = HashMap::new();
vars.insert("branch", "feature-auth");
let template = "npm run dev -- --host {{ branch }}.lvh.me --port {{ branch | hash_port }}";
- let result = expand_template(template, &vars, false).unwrap();
+ let result = expand_template(template, &vars, false, &repository).unwrap();
let expected_port = hash_port("feature-auth");
assert_eq!(
@@ -314,18 +347,19 @@ fn test_doc_example_dev_server() {
);
}
-#[test]
-fn test_doc_example_worktree_path_sanitize() {
+#[rstest]
+fn test_doc_example_worktree_path_sanitize(repo: TestRepo) {
// From docs/content/tips-patterns.md line 217:
// worktree-path = "{{ branch | sanitize }}"
+ let repository = Repository::at(repo.root_path()).unwrap();
let mut vars = HashMap::new();
vars.insert("branch", "feature/user/auth");
vars.insert("main_worktree", "/home/user/project");
let template = "{{ main_worktree }}.{{ branch | sanitize }}";
- let result = expand_template(template, &vars, false).unwrap();
+ let result = expand_template(template, &vars, false, &repository).unwrap();
assert_eq!(result, "/home/user/project.feature-user-auth");
}
@@ -333,12 +367,13 @@ fn test_doc_example_worktree_path_sanitize() {
// Edge Cases
// =============================================================================
-#[test]
-fn test_doc_hash_port_empty_string() {
+#[rstest]
+fn test_doc_hash_port_empty_string(repo: TestRepo) {
+ let repository = Repository::at(repo.root_path()).unwrap();
let mut vars = HashMap::new();
vars.insert("branch", "");
- let result = expand_template("{{ branch | hash_port }}", &vars, false).unwrap();
+ let result = expand_template("{{ branch | hash_port }}", &vars, false, &repository).unwrap();
let port: u16 = result.parse().unwrap();
assert!(
@@ -347,28 +382,54 @@ fn test_doc_hash_port_empty_string() {
);
}
-#[test]
-fn test_doc_sanitize_no_slashes() {
+#[rstest]
+fn test_doc_sanitize_no_slashes(repo: TestRepo) {
+ let repository = Repository::at(repo.root_path()).unwrap();
let mut vars = HashMap::new();
vars.insert("branch", "simple-branch");
- let result = expand_template("{{ branch | sanitize }}", &vars, false).unwrap();
+ let result = expand_template("{{ branch | sanitize }}", &vars, false, &repository).unwrap();
assert_eq!(
result, "simple-branch",
"sanitize should be no-op without slashes"
);
}
-#[test]
-fn test_doc_combined_filters() {
+#[rstest]
+fn test_doc_combined_filters(repo: TestRepo) {
// sanitize then hash_port (not currently documented, but should work)
+ let repository = Repository::at(repo.root_path()).unwrap();
let mut vars = HashMap::new();
vars.insert("branch", "feature/auth");
- let result = expand_template("{{ branch | sanitize | hash_port }}", &vars, false).unwrap();
+ let result = expand_template(
+ "{{ branch | sanitize | hash_port }}",
+ &vars,
+ false,
+ &repository,
+ )
+ .unwrap();
let port: u16 = result.parse().unwrap();
// Should hash the sanitized version
let expected = hash_port("feature-auth");
assert_eq!(port, expected);
}
+
+// =============================================================================
+// worktree_path Function
+// =============================================================================
+
+#[rstest]
+fn test_worktree_path_function_registered(repo: TestRepo) {
+ // Test that worktree_path function is callable and returns empty for nonexistent branch
+ let repository = Repository::at(repo.root_path()).unwrap();
+ let vars: HashMap<&str, &str> = HashMap::new();
+ let result = expand_template(
+ "{{ worktree_path('nonexistent') }}",
+ &vars,
+ false,
+ &repository,
+ );
+ assert_eq!(result.unwrap(), "");
+}