Skip to content

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

Add git and worktree template variables for hooks

Maximilian Roosd274cc2e0dce
diff --git a/docs/content/hooks.md b/docs/content/hooks.md
index 1223c38c5..3a1a97522 100644
--- a/docs/content/hooks.md
+++ b/docs/content/hooks.md
@@ -72,14 +72,26 @@ Hooks can use template variables that expand at runtime:
- `{{ repo }}` — Repository name (e.g., "my-project")
- `{{ branch }}` — Branch name (slashes replaced with dashes)
- `{{ worktree }}` — Absolute path to the worktree
+- `{{ worktree_name }}` — Worktree directory name (e.g., "my-project.feature-foo")
- `{{ repo_root }}` — Absolute path to the repository root
- `{{ default_branch }}` — Default branch name (e.g., "main")
+### Git Variables (All Hooks)
+
+- `{{ commit }}` — Current HEAD commit SHA (full 40-character hash)
+- `{{ short_commit }}` — Current HEAD commit SHA (short 7-character hash)
+- `{{ remote }}` — Primary remote name (e.g., "origin")
+- `{{ upstream }}` — Upstream tracking branch (e.g., "origin/feature"), if configured
+
### Merge Variables (pre-commit, pre-merge, post-merge)
- `{{ target }}` — Target branch for the merge (e.g., "main")
```toml
+# Tag builds with commit hash
+post-create = "echo '{{ short_commit }}' > .version"
+
+# Reference merge target
pre-merge = "echo 'Merging {{ branch }} into {{ target }}'"
```
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 08af88283..3f73fc914 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -72,6 +72,31 @@ fn expand_commands(
if let Ok(default_branch) = ctx.repo.default_branch() {
extras_owned.insert("default_branch".to_string(), default_branch);
}
+
+ // Git ref variables
+ if let Ok(commit) = ctx.repo.run_command(&["rev-parse", "HEAD"]) {
+ let commit = commit.trim();
+ extras_owned.insert("commit".to_string(), commit.to_string());
+ // Short commit is first 7 characters
+ if commit.len() >= 7 {
+ extras_owned.insert("short_commit".to_string(), commit[..7].to_string());
+ }
+ }
+
+ // Remote variables
+ if let Ok(remote) = ctx.repo.primary_remote() {
+ extras_owned.insert("remote".to_string(), remote.clone());
+ // Upstream tracking branch (if configured)
+ if let Ok(Some(upstream)) = ctx.repo.upstream_branch(ctx.branch) {
+ extras_owned.insert("upstream".to_string(), upstream);
+ }
+ }
+
+ // Worktree name (basename of worktree path)
+ if let Some(name) = ctx.worktree_path.file_name().and_then(|n| n.to_str()) {
+ extras_owned.insert("worktree_name".to_string(), name.to_string());
+ }
+
for &(key, value) in extra_vars {
extras_owned.insert(key.to_string(), value.to_string());
}
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 4bf70658e..295e1fef7 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -98,9 +98,14 @@ pub fn expand_template(
/// Supported variables:
/// - `{{ repo }}` - Repository name
/// - `{{ branch }}` - Branch name (sanitized: slashes → dashes)
-/// - `{{ worktree }}` - Path to the worktree
-/// - `{{ repo_root }}` - Path to the main repository root
+/// - `{{ worktree }}` - Absolute path to the worktree
+/// - `{{ worktree_name }}` - Worktree directory name (basename of worktree path)
+/// - `{{ repo_root }}` - Absolute path to the main repository root
/// - `{{ default_branch }}` - Default branch name (e.g., "main")
+/// - `{{ commit }}` - Current HEAD commit SHA (full 40-character hash)
+/// - `{{ short_commit }}` - Current HEAD commit SHA (short 7-character hash)
+/// - `{{ remote }}` - Primary remote name (e.g., "origin")
+/// - `{{ upstream }}` - Upstream tracking branch (e.g., "origin/feature"), if configured
/// - `{{ target }}` - Target branch (for merge commands, optional)
///
/// # Examples
diff --git a/src/config/project.rs b/src/config/project.rs
index 4123662c5..66d9f7422 100644
--- a/src/config/project.rs
+++ b/src/config/project.rs
@@ -19,8 +19,13 @@ use super::commands::CommandConfig;
/// - `{{ repo }}` - Repository name (e.g., "my-project")
/// - `{{ branch }}` - Branch name (e.g., "feature-foo")
/// - `{{ worktree }}` - Absolute path to the worktree
+/// - `{{ worktree_name }}` - Worktree directory name (e.g., "my-project.feature-foo")
/// - `{{ repo_root }}` - Absolute path to the repository root
/// - `{{ default_branch }}` - Default branch name (e.g., "main")
+/// - `{{ commit }}` - Current HEAD commit SHA (full 40-character hash)
+/// - `{{ short_commit }}` - Current HEAD commit SHA (short 7-character hash)
+/// - `{{ remote }}` - Primary remote name (e.g., "origin")
+/// - `{{ upstream }}` - Upstream tracking branch (e.g., "origin/feature"), if configured
///
/// Merge-related hooks (`pre-commit`, `pre-merge`, `post-merge`) also support:
/// - `{{ target }}` - Target branch for the merge (e.g., "main")
@@ -29,14 +34,14 @@ pub struct ProjectConfig {
/// Commands to execute sequentially before worktree is ready (blocking)
/// Supports string (single command), array (sequential), or table (named, sequential)
///
- /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ repo_root }}`, `{{ default_branch }}`
+ /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ worktree_name }}`, `{{ repo_root }}`, `{{ default_branch }}`, `{{ commit }}`, `{{ short_commit }}`, `{{ remote }}`, `{{ upstream }}`
#[serde(default, rename = "post-create")]
pub post_create: Option<CommandConfig>,
/// Commands to execute in parallel as background processes (non-blocking)
/// Supports string (single), array (parallel), or table (named, parallel)
///
- /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ repo_root }}`, `{{ default_branch }}`
+ /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ worktree_name }}`, `{{ repo_root }}`, `{{ default_branch }}`, `{{ commit }}`, `{{ short_commit }}`, `{{ remote }}`, `{{ upstream }}`
#[serde(default, rename = "post-start")]
pub post_start: Option<CommandConfig>,
@@ -45,7 +50,7 @@ pub struct ProjectConfig {
/// All commands must exit with code 0 for commit to proceed
/// Runs before any commit operation during `wt merge` (both squash and no-squash modes)
///
- /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ repo_root }}`, `{{ default_branch }}`, `{{ target }}`
+ /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ worktree_name }}`, `{{ repo_root }}`, `{{ default_branch }}`, `{{ commit }}`, `{{ short_commit }}`, `{{ remote }}`, `{{ upstream }}`, `{{ target }}`
#[serde(default, rename = "pre-commit")]
pub pre_commit: Option<CommandConfig>,
@@ -53,7 +58,7 @@ pub struct ProjectConfig {
/// Supports string (single command), array (sequential), or table (named, sequential)
/// All commands must exit with code 0 for merge to proceed
///
- /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ repo_root }}`, `{{ default_branch }}`, `{{ target }}`
+ /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ worktree_name }}`, `{{ repo_root }}`, `{{ default_branch }}`, `{{ commit }}`, `{{ short_commit }}`, `{{ remote }}`, `{{ upstream }}`, `{{ target }}`
#[serde(default, rename = "pre-merge")]
pub pre_merge: Option<CommandConfig>,
@@ -61,7 +66,7 @@ pub struct ProjectConfig {
/// Supports string (single command), array (sequential), or table (named, sequential)
/// Runs after push succeeds but before cleanup
///
- /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ repo_root }}`, `{{ default_branch }}`, `{{ target }}`
+ /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ worktree_name }}`, `{{ repo_root }}`, `{{ default_branch }}`, `{{ commit }}`, `{{ short_commit }}`, `{{ remote }}`, `{{ upstream }}`, `{{ target }}`
#[serde(default, rename = "post-merge")]
pub post_merge: Option<CommandConfig>,
diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rs
index dc489f4db..41cd40b4b 100644
--- a/tests/integration_tests/post_start_commands.rs
+++ b/tests/integration_tests/post_start_commands.rs
@@ -275,6 +275,124 @@ approved-commands = ["echo 'Default: {{ default_branch }}' > default.txt"]
);
}
+#[test]
+fn test_post_create_git_variables_template() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Set up an upstream tracking branch
+ repo.git_command(&["push", "-u", "origin", "main"])
+ .output()
+ .expect("failed to push");
+
+ // Create project config with git-related template variables
+ repo.write_project_config(
+ r#"post-create = [
+ "echo 'Commit: {{ commit }}' > git_vars.txt",
+ "echo 'Short: {{ short_commit }}' >> git_vars.txt",
+ "echo 'Remote: {{ remote }}' >> git_vars.txt",
+ "echo 'Worktree Name: {{ worktree_name }}' >> git_vars.txt"
+]"#,
+ );
+
+ repo.commit("Add config with git template variables");
+
+ // Create a feature branch worktree (--force skips approval prompt)
+ snapshot_switch(
+ "post_create_git_variables_template",
+ &repo,
+ &["--create", "feature", "--force"],
+ );
+
+ // Verify template expansion actually worked
+ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
+ let vars_file = worktree_path.join("git_vars.txt");
+
+ assert!(
+ vars_file.exists(),
+ "git_vars.txt should have been created in the worktree"
+ );
+
+ let contents = fs::read_to_string(&vars_file).unwrap();
+
+ // Verify commit variable (should be 40 char hex)
+ assert!(
+ contents.contains("Commit: ")
+ && contents.lines().any(|l| {
+ l.starts_with("Commit: ") && l.len() == 48 // "Commit: " (8) + 40 hex chars
+ }),
+ "Should contain expanded commit SHA, got: {}",
+ contents
+ );
+
+ // Verify short_commit variable (should be 7 char hex)
+ assert!(
+ contents.contains("Short: ")
+ && contents.lines().any(|l| {
+ l.starts_with("Short: ") && l.len() == 14 // "Short: " (7) + 7 hex chars
+ }),
+ "Should contain expanded short_commit SHA, got: {}",
+ contents
+ );
+
+ // Verify remote variable
+ assert!(
+ contents.contains("Remote: origin"),
+ "Should contain expanded remote name, got: {}",
+ contents
+ );
+
+ // Verify worktree_name variable (basename of worktree path)
+ assert!(
+ contents.contains("Worktree Name: repo.feature"),
+ "Should contain expanded worktree_name, got: {}",
+ contents
+ );
+}
+
+#[test]
+fn test_post_create_upstream_template() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Push main to set up tracking
+ repo.git_command(&["push", "-u", "origin", "main"])
+ .output()
+ .expect("failed to push main");
+
+ // Create project config with upstream template variable
+ repo.write_project_config(r#"post-create = "echo 'Upstream: {{ upstream }}' > upstream.txt""#);
+
+ repo.commit("Add config with upstream template");
+
+ // Create a feature branch based on main (which has upstream tracking)
+ // The new branch will inherit upstream since it's created from main
+ snapshot_switch(
+ "post_create_upstream_template",
+ &repo,
+ &["--create", "feature", "--force"],
+ );
+
+ // Verify template expansion actually worked
+ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
+ let upstream_file = worktree_path.join("upstream.txt");
+
+ assert!(
+ upstream_file.exists(),
+ "upstream.txt should have been created in the worktree"
+ );
+
+ let contents = fs::read_to_string(&upstream_file).unwrap();
+ // New branches don't have upstream until pushed - upstream should be empty
+ assert!(
+ contents.contains("Upstream: "),
+ "Should have upstream line (possibly empty), got: {}",
+ contents
+ );
+}
+
// ============================================================================
// Post-Start Command Tests (parallel, background)
// ============================================================================
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_git_variables_template.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_git_variables_template.snap
new file mode 100644
index 000000000..e713e30f1
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_git_variables_template.snap
@@ -0,0 +1,38 @@
+---
+source: tests/integration_tests/post_start_commands.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - feature
+ - "--force"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1735776000"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+🔄 Running post-create:
+  echo 'Commit: ca423bfe8d8bb22a62e11874452caa0e667c626e' > git_vars.txt
+🔄 Running post-create:
+  echo 'Short: ca423bf' >> git_vars.txt
+🔄 Running post-create:
+  echo 'Remote: origin' >> git_vars.txt
+🔄 Running post-create:
+  echo 'Worktree Name: repo.feature' >> git_vars.txt
+✅ Created new worktree for feature from main at [REPO].feature
+💡 Run wt config shell install to enable automatic cd
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snap
new file mode 100644
index 000000000..877508c7b
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snap
@@ -0,0 +1,32 @@
+---
+source: tests/integration_tests/post_start_commands.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - feature
+ - "--force"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1735776000"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+🔄 Running post-create:
+  echo 'Upstream: ' > upstream.txt
+✅ Created new worktree for feature from main at [REPO].feature
+💡 Run wt config shell install to enable automatic cd