Skip to content

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

Add hash_port filter for deterministic port assignment (#266)

Maximilian Roos5f32e30bd278
diff --git a/.claude-plugin/skills/worktrunk/reference/hook-types-reference.md b/.claude-plugin/skills/worktrunk/reference/hook-types-reference.md
index 7cc8b1c0e..c3e8f5669 100644
--- a/.claude-plugin/skills/worktrunk/reference/hook-types-reference.md
+++ b/.claude-plugin/skills/worktrunk/reference/hook-types-reference.md
@@ -14,7 +14,7 @@ Detailed behavior and use cases for all five Worktrunk hook types.
**Basic variables**: `{{ repo }}`, `{{ branch }}` (raw), `{{ worktree }}`, `{{ repo_root }}`
**Merge variables**: Basic + `{{ target }}`
-**Filter**: `{{ branch | sanitize }}` replaces `/` and `\` with `-`
+**Filters**: `{{ branch | sanitize }}` (replace `/` `\` with `-`), `{{ branch | hash_port }}` (port 10000-19999)
## Detailed Behavior
diff --git a/.claude-plugin/skills/worktrunk/reference/project-config.md b/.claude-plugin/skills/worktrunk/reference/project-config.md
index 42fcab3e1..ab63cce35 100644
--- a/.claude-plugin/skills/worktrunk/reference/project-config.md
+++ b/.claude-plugin/skills/worktrunk/reference/project-config.md
@@ -187,10 +187,21 @@ All hooks support template variables for dynamic behavior.
Available in all hook types:
- `{{ repo }}` - Repository name (e.g., "my-project")
- `{{ 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
+### Filters
+
+- `{{ branch | sanitize }}` - Replace `/` and `\` with `-` (e.g., "feature-auth")
+- `{{ branch | hash_port }}` - Hash string to deterministic port (10000-19999)
+
+Example:
+```toml
+[post-start]
+dev = "npm run dev --port {{ branch | hash_port }}"
+cache = "ln -sf {{ repo_root }}/node_modules.{{ branch | sanitize }} node_modules"
+```
+
<example type="basic-variables">
```toml
diff --git a/.claude-plugin/skills/worktrunk/reference/user-config.md b/.claude-plugin/skills/worktrunk/reference/user-config.md
index f7e239c2f..3f922d02a 100644
--- a/.claude-plugin/skills/worktrunk/reference/user-config.md
+++ b/.claude-plugin/skills/worktrunk/reference/user-config.md
@@ -131,7 +131,11 @@ Result: `~/code/myproject/.worktrees/feature-auth`
- `{{ main_worktree }}` - Main worktree directory name
- `{{ branch }}` - Raw branch name (e.g., `feature/foo`)
-- `{{ branch | sanitize }}` - Branch name with `/` and `\` replaced by `-`
+
+### Filters
+
+- `{{ branch | sanitize }}` - Replace `/` and `\` with `-` (e.g., `feature-foo`)
+- `{{ branch | hash_port }}` - Hash string to deterministic port (10000-19999)
### Validation Rules
diff --git a/dev/wt.example.toml b/dev/wt.example.toml
index 978bb2e5e..55ffccdb4 100644
--- a/dev/wt.example.toml
+++ b/dev/wt.example.toml
@@ -6,14 +6,17 @@
# developers working on the project.
# Available template variables (all hooks):
-# {{ 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
+# {{ repo }} - Repository name (e.g., "my-project")
+# {{ branch }} - Raw branch name (e.g., "feature/foo")
+# {{ 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")
+#
+# Filters:
+# {{ branch | sanitize }} - Replace / and \ with - (e.g., "feature-foo")
+# {{ branch | hash_port }} - Hash string to deterministic port (10000-19999)
# Post-Create Hook
# Runs SEQUENTIALLY and BLOCKS until complete
diff --git a/docs/content/config.md b/docs/content/config.md
index 5eb25bed0..30dcb5397 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -469,14 +469,17 @@ 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 }} - 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
+# {{ repo }} - Repository name (e.g., "my-project")
+# {{ branch }} - Raw branch name (e.g., "feature/foo")
+# {{ 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")
+#
+# Filters:
+# {{ branch | sanitize }} - Replace / and \ with - (e.g., "feature-foo")
+# {{ branch | hash_port }} - Hash string to deterministic port (10000-19999)
# Post-Create Hook
# Runs SEQUENTIALLY and BLOCKS until complete
diff --git a/docs/content/hook.md b/docs/content/hook.md
index 260aa3365..79db8ff05 100644
--- a/docs/content/hook.md
+++ b/docs/content/hook.md
@@ -147,6 +147,29 @@ Hooks can use template variables that expand at runtime:
| `{{ upstream }}` | origin/feature | Upstream tracking branch |
| `{{ target }}` | main | Target branch (merge hooks only) |
+### Filters
+
+Templates support Jinja2 filters for transforming values:
+
+| Filter | Example | Description |
+|--------|---------|-------------|
+| `sanitize` | `{{ branch \| sanitize }}` → feature-foo | Replace `/` and `\` with `-` |
+| `hash_port` | `{{ branch \| hash_port }}` → 12472 | Hash string to port (10000-19999) |
+
+The `sanitize` filter makes branch names safe for filesystem paths. The `hash_port` filter is useful for running dev servers on unique ports per worktree:
+
+```toml
+[post-start]
+dev = "npm run dev -- --host {{ branch }}.lvh.me --port {{ branch | hash_port }}"
+```
+
+You can hash any string, including concatenations:
+
+```toml
+# Unique port per repo+branch combination
+dev = "npm run dev --port {{ repo ~ '-' ~ branch | hash_port }}"
+```
+
### JSON context
Hooks also receive context as JSON on stdin, enabling hooks in any language:
diff --git a/src/cli.rs b/src/cli.rs
index f6decfefe..de86d4eff 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -1578,6 +1578,29 @@ Hooks can use template variables that expand at runtime:
| `{{ upstream }}` | origin/feature | Upstream tracking branch |
| `{{ target }}` | main | Target branch (merge hooks only) |
+### Filters
+
+Templates support Jinja2 filters for transforming values:
+
+| Filter | Example | Description |
+|--------|---------|-------------|
+| `sanitize` | `{{ branch \| sanitize }}` → feature-foo | Replace `/` and `\` with `-` |
+| `hash_port` | `{{ branch \| hash_port }}` → 12472 | Hash string to port (10000-19999) |
+
+The `sanitize` filter makes branch names safe for filesystem paths. The `hash_port` filter is useful for running dev servers on unique ports per worktree:
+
+```toml
+[post-start]
+dev = "npm run dev -- --host {{ branch }}.lvh.me --port {{ branch | hash_port }}"
+```
+
+You can hash any string, including concatenations:
+
+```toml
+# Unique port per repo+branch combination
+dev = "npm run dev --port {{ repo ~ '-' ~ branch | hash_port }}"
+```
+
### JSON context
Hooks also receive context as JSON on stdin, enabling hooks in any language:
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 19b37c461..6e8062c9e 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -5,9 +5,30 @@
//! - `shell_escape: false` — Literal values for filesystem paths
//!
//! 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
+//! ```
+//!
+//! - `hash_port` — Hash a string to a deterministic port number (10000-19999)
+//! ```text
+//! {{ branch | hash_port }} → 12472
+//! {{ repo ~ "-" ~ branch | hash_port }} → 15839
+//! ```
use minijinja::{Environment, Value};
use std::collections::HashMap;
+use std::hash::{Hash, Hasher};
+
+/// Hash a string to a port in range 10000-19999.
+fn string_to_port(s: &str) -> u16 {
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ s.hash(&mut h);
+ 10000 + (h.finish() % 10000) as u16
+}
/// Sanitize a branch name for use in filesystem paths.
///
@@ -84,10 +105,11 @@ pub fn expand_template(
env.set_keep_trailing_newline(true);
}
- // Register the `sanitize` filter for branch names (replaces / and \ with -)
+ // Register custom filters
env.add_filter("sanitize", |value: Value| -> String {
sanitize_branch_name(value.as_str().unwrap_or_default())
});
+ env.add_filter("hash_port", |value: String| string_to_port(&value));
let tmpl = env
.template_from_str(template)
@@ -249,4 +271,31 @@ mod tests {
.ends_with('\n')
);
}
+
+ #[test]
+ fn test_string_to_port_deterministic_and_in_range() {
+ for input in ["main", "feature-foo", "", "a", "long-branch-name-123"] {
+ let p1 = string_to_port(input);
+ let p2 = string_to_port(input);
+ assert_eq!(p1, p2, "same input should produce same port");
+ assert!((10000..20000).contains(&p1), "port {} out of range", p1);
+ }
+ }
+
+ #[test]
+ fn test_hash_port_filter() {
+ 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 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 r2 = expand_template("{{ repo ~ '-' ~ branch | hash_port }}", &vars, false).unwrap();
+ assert_eq!(r1, r2);
+ }
}
diff --git a/src/config/project.rs b/src/config/project.rs
index fa8f03e9b..e91688ab0 100644
--- a/src/config/project.rs
+++ b/src/config/project.rs
@@ -29,6 +29,11 @@ use super::commands::CommandConfig;
///
/// Merge-related hooks (`pre-commit`, `pre-merge`, `post-merge`) also support:
/// - `{{ target }}` - Target branch for the merge (e.g., "main")
+///
+/// # Filters
+///
+/// - `{{ branch | sanitize }}` - Replace `/` and `\` with `-` (e.g., "feature-foo")
+/// - `{{ branch | hash_port }}` - Hash string to deterministic port (10000-19999)
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
pub struct ProjectConfig {
/// Commands to execute sequentially before worktree is ready (blocking)
diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rs
index 187b731bd..bdc56544e 100644
--- a/tests/integration_tests/post_start_commands.rs
+++ b/tests/integration_tests/post_start_commands.rs
@@ -131,6 +131,7 @@ fn test_post_create_template_expansion(repo: TestRepo) {
r#"[post-create]
repo = "echo 'Repo: {{ main_worktree }}' > info.txt"
branch = "echo 'Branch: {{ branch }}' >> info.txt"
+hash_port = "echo 'Port: {{ branch | hash_port }}' >> info.txt"
worktree = "echo 'Worktree: {{ worktree }}' >> info.txt"
root = "echo 'Root: {{ repo_root }}' >> info.txt"
"#,
@@ -147,6 +148,7 @@ root = "echo 'Root: {{ repo_root }}' >> info.txt"
approved-commands = [
"echo 'Repo: {{ main_worktree }}' > info.txt",
"echo 'Branch: {{ branch }}' >> info.txt",
+ "echo 'Port: {{ branch | hash_port }}' >> info.txt",
"echo 'Worktree: {{ worktree }}' >> info.txt",
"echo 'Root: {{ repo_root }}' >> info.txt",
]
@@ -186,6 +188,22 @@ approved-commands = [
"Should contain raw branch name, got: {}",
contents
);
+
+ // Verify port is a valid number in the expected range (10000-19999)
+ let port_line = contents
+ .lines()
+ .find(|l| l.starts_with("Port: "))
+ .expect("Should contain port line");
+ let port: u16 = port_line
+ .strip_prefix("Port: ")
+ .unwrap()
+ .parse()
+ .expect("Port should be a valid number");
+ assert!(
+ (10000..20000).contains(&port),
+ "Port should be in range 10000-19999, got: {}",
+ port
+ );
}
#[rstest]
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 c1e9da9c4..b39160a46 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_create.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
@@ -245,14 +245,17 @@ 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 }} - 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
+ # {{ repo }} - Repository name (e.g., "my-project")
+ # {{ branch }} - Raw branch name (e.g., "feature/foo")
+ # {{ 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")
+ #
+ # Filters:
+ # {{ branch | sanitize }} - Replace / and \ with - (e.g., "feature-foo")
+ # {{ branch | hash_port }} - Hash string to deterministic port (10000-19999)

# Post-Create Hook
# Runs SEQUENTIALLY and BLOCKS until complete
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 c7f71adc2..0ccfc7abd 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
@@ -35,6 +35,8 @@ exit_code: 0
  echo 'Repo: repo' > info.txt
◎ Running project post-create branch:
  echo 'Branch: feature/test' >> info.txt
+◎ Running project post-create hash_port:
+  echo 'Port: 18064' >> info.txt
◎ Running project post-create worktree:
  echo 'Worktree: _REPO_.feature-test' >> info.txt
◎ Running project post-create root: