Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Feat: Add post-start commands to project config
Maximilian Roosf674619158b1
diff --git a/.config/wt.toml b/.config/wt.tomlnew file mode 100644index 000000000..bd549dcd6--- /dev/null+++ b/.config/wt.toml@@ -0,0 +1,15 @@+# Post-start commands for worktree setup+# These run after creating a new worktree+#+# Available template variables:+# {repo} - Repository name (e.g., "worktrunk.project-config")+# {branch} - Branch name with slashes replaced by dashes+# {worktree} - Path to the new worktree+# {repo_root} - Path to the main repository root+post-start-commands = [+ # Seed target/ from base worktree using CoW (copy-on-write)+ # Each worktree gets its own target/ (avoids incremental build corruption)+ # but seeded from base to warm-start builds (low disk usage)+ # rsync --reflink=auto works on both macOS and Linux+ "[ -d {repo_root}/target ] && [ ! -e {worktree}/target ] && rsync -a --reflink=auto {repo_root}/target/ {worktree}/target/ && echo '✓ CoW seeded target/'"+]diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 05124a42c..a11f7d8d1 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -66,9 +66,10 @@//!//! See also: DEMO.md for detailed architecture explanation.+use std::collections::HashMap;use std::io::{self, Write};use std::path::PathBuf;-use worktrunk::config::{ProjectConfig, WorktrunkConfig};+use worktrunk::config::{ProjectConfig, WorktrunkConfig, expand_template};use worktrunk::git::{GitError, Repository};use worktrunk::shell::Shell;use worktrunk::styling::{AnstyleStyle, ERROR, HINT, WARNING, eprintln, println};@@ -170,9 +171,8 @@ impl RemoveResult {Some(format!("Already on default branch {bold}{branch}{bold:#}"))}RemoveResult::RemovedWorktree { primary_path } => Some(format!(- "Moved to primary worktree and removed worktree\nPath: {}{}",- primary_path.display(),- shell_integration_hint()+ "Moved to primary worktree and removed worktree\nPath: {}\n\nTo enable automatic cd, run: wt configure-shell",+ primary_path.display())),RemoveResult::SwitchedToDefault(branch) => {let bold = AnstyleStyle::new().bold();@@ -271,7 +271,7 @@ pub fn handle_switch(.unwrap_or_else(|_| worktree_path.clone());// Execute post-start commands from project config- execute_post_start_commands(&canonical_path, &repo, config)?;+ execute_post_start_commands(&canonical_path, &repo, config, branch, repo_name)?;Ok(SwitchResult::CreatedWorktree {path: canonical_path,@@ -407,6 +407,27 @@ fn check_worktree_conflicts(Ok(())}+/// Replace template variables in a command string+///+/// Supported variables:+/// - `{repo}` - Repository name+/// - `{branch}` - Branch name (sanitized)+/// - `{worktree}` - Path to the new worktree+/// - `{repo_root}` - Path to the main repository root+fn expand_command_template(+ command: &str,+ repo_name: &str,+ branch: &str,+ worktree_path: &std::path::Path,+ repo_root: &std::path::Path,+) -> String {+ let mut extra = HashMap::new();+ extra.insert("worktree", worktree_path.to_str().unwrap_or(""));+ extra.insert("repo_root", repo_root.to_str().unwrap_or(""));++ expand_template(command, repo_name, branch, &extra)+}+/// Prompt the user to approve a command for executionfn prompt_for_approval(command: &str, project_id: &str) -> io::Result<bool> {eprintln!();@@ -432,6 +453,8 @@ fn execute_post_start_commands(worktree_path: &std::path::Path,repo: &Repository,config: &WorktrunkConfig,+ branch: &str,+ repo_name: &str,) -> Result<(), GitError> {// Load project configlet repo_root = repo.repo_root()?;@@ -498,8 +521,12 @@ fn execute_post_start_commands(};if approved {- eprintln!("Executing: {}", command);- if let Err(e) = execute_command_in_worktree(worktree_path, command) {+ // Expand template variables in the command+ let expanded_command =+ expand_command_template(command, repo_name, branch, worktree_path, &repo_root);++ eprintln!("Executing: {}", expanded_command);+ if let Err(e) = execute_command_in_worktree(worktree_path, &expanded_command) {eprintln!("Warning: Command failed: {}", e);// Continue with other commands even if one fails}diff --git a/src/config.rs b/src/config.rsindex 0bf6f61d5..184d8117c 100644--- a/src/config.rs+++ b/src/config.rs@@ -134,11 +134,12 @@ impl WorktrunkConfig {/// assert_eq!(path, "../myproject.feature-foo");/// ```pub fn format_path(&self, repo: &str, branch: &str) -> String {- // Sanitize branch name by replacing path separators to prevent directory traversal- let safe_branch = branch.replace(['/', '\\'], "-");- self.worktree_path- .replace("{repo}", repo)- .replace("{branch}", &safe_branch)+ expand_template(+ &self.worktree_path,+ repo,+ branch,+ &std::collections::HashMap::new(),+ )}}@@ -146,6 +147,43 @@ fn get_config_path() -> Option<PathBuf> {ProjectDirs::from("", "", "worktrunk").map(|dirs| dirs.config_dir().join("config.toml"))}+/// Expand template variables in a string+///+/// All templates support:+/// - `{repo}` - Repository name+/// - `{branch}` - Branch name (sanitized: slashes → dashes)+///+/// Additional variables can be provided via the `extra` parameter.+///+/// # Examples+/// ```+/// use worktrunk::config::expand_template;+/// use std::collections::HashMap;+///+/// let result = expand_template("path/{repo}/{branch}", "myrepo", "feature/foo", &HashMap::new());+/// assert_eq!(result, "path/myrepo/feature-foo");+/// ```+pub fn expand_template(+ template: &str,+ repo: &str,+ branch: &str,+ extra: &std::collections::HashMap<&str, &str>,+) -> String {+ // Sanitize branch name by replacing path separators+ let safe_branch = branch.replace(['/', '\\'], "-");++ let mut result = template+ .replace("{repo}", repo)+ .replace("{branch}", &safe_branch);++ // Apply any extra variables+ for (key, value) in extra {+ result = result.replace(&format!("{{{}}}", key), value);+ }++ result+}+impl ProjectConfig {/// Load project configuration from .config/wt.toml in the repository rootpub fn load(repo_root: &std::path::Path) -> Result<Option<Self>, ConfigError> {@@ -437,4 +475,40 @@ mod tests {.ok();assert_eq!(config.approved_commands.len(), count_before);}++ #[test]+ fn test_expand_template_basic() {+ use std::collections::HashMap;++ let result = expand_template("../{repo}.{branch}", "myrepo", "feature-x", &HashMap::new());+ assert_eq!(result, "../myrepo.feature-x");+ }++ #[test]+ fn test_expand_template_sanitizes_branch() {+ use std::collections::HashMap;++ let result = expand_template("{repo}/{branch}", "myrepo", "feature/foo", &HashMap::new());+ assert_eq!(result, "myrepo/feature-foo");++ let result = expand_template("{branch}", "myrepo", "feat\\bar", &HashMap::new());+ assert_eq!(result, "feat-bar");+ }++ #[test]+ fn test_expand_template_with_extra_vars() {+ use std::collections::HashMap;++ let mut extra = HashMap::new();+ extra.insert("worktree", "/path/to/worktree");+ extra.insert("repo_root", "/path/to/repo");++ let result = expand_template(+ "{repo_root}/target -> {worktree}/target",+ "myrepo",+ "main",+ &extra,+ );+ assert_eq!(result, "/path/to/repo/target -> /path/to/worktree/target");+ }}diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rsindex 22d164e13..2b408257a 100644--- a/tests/integration_tests/post_start_commands.rs+++ b/tests/integration_tests/post_start_commands.rs@@ -61,15 +61,12 @@ fn test_post_start_commands_with_approval() {fs::create_dir_all(&user_config_dir).ok();fs::write(user_config_dir.join("config.toml"),- format!(- r#"worktree-path = "../{{repo}}.{{branch}}"+ r#"worktree-path = "../{repo}.{branch}"[[approved-commands]]-project = "{}"+project = "main"command = "echo 'Setup complete'""#,- repo.root_path().file_name().unwrap().to_str().unwrap()- ),).ok();@@ -119,15 +116,12 @@ fn test_post_start_commands_failing_command() {fs::create_dir_all(&config_dir).ok();fs::write(config_dir.join("config.toml"),- format!(- r#"worktree-path = "../{{repo}}.{{branch}}"+ r#"worktree-path = "../{repo}.{branch}"[[approved-commands]]-project = "{}"+project = "main"command = "exit 1""#,- repo.root_path().file_name().unwrap().to_str().unwrap()- ),).ok();@@ -161,20 +155,16 @@ fn test_post_start_commands_multiple_commands() {fs::create_dir_all(&config_dir).ok();fs::write(config_dir.join("config.toml"),- format!(- r#"worktree-path = "../{{repo}}.{{branch}}"+ r#"worktree-path = "../{repo}.{branch}"[[approved-commands]]-project = "{}"+project = "main"command = "echo 'First'"[[approved-commands]]-project = "{}"+project = "main"command = "echo 'Second'""#,- repo.root_path().file_name().unwrap().to_str().unwrap(),- repo.root_path().file_name().unwrap().to_str().unwrap()- ),).ok();@@ -185,3 +175,123 @@ command = "echo 'Second'"&["--create", "feature"],);}++#[test]+fn test_post_start_commands_template_expansion() {+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create project config with template variables+ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create .config dir");+ fs::write(+ config_dir.join("wt.toml"),+ r#"post-start-commands = [+ "echo 'Repo: {repo}' > info.txt",+ "echo 'Branch: {branch}' >> info.txt",+ "echo 'Worktree: {worktree}' >> info.txt",+ "echo 'Root: {repo_root}' >> info.txt"+]"#,+ )+ .expect("Failed to write config");++ repo.commit("Add config with templates");++ // Pre-approve all commands+ let home_dir = std::env::var("HOME").unwrap();+ let user_config_dir =+ std::path::Path::new(&home_dir).join("Library/Application Support/worktrunk");+ fs::create_dir_all(&user_config_dir).ok();+ let repo_name = "main";+ fs::write(+ user_config_dir.join("config.toml"),+ r#"worktree-path = "../{repo}.{branch}"++[[approved-commands]]+project = "main"+command = "echo 'Repo: {repo}' > info.txt"++[[approved-commands]]+project = "main"+command = "echo 'Branch: {branch}' >> info.txt"++[[approved-commands]]+project = "main"+command = "echo 'Worktree: {worktree}' >> info.txt"++[[approved-commands]]+project = "main"+command = "echo 'Root: {repo_root}' >> info.txt"+"#,+ )+ .ok();++ // Commands should execute with expanded templates+ snapshot_switch(+ "post_start_template_expansion",+ &repo,+ &["--create", "feature/test"],+ );++ // Verify template expansion actually worked by checking the output file+ // The worktree path should be ../main.feature-test (slashes replaced with dashes)+ let worktree_path = repo+ .root_path()+ .parent()+ .unwrap()+ .join(format!("{}.feature-test", repo_name));+ let info_file = worktree_path.join("info.txt");++ assert!(+ info_file.exists(),+ "info.txt should have been created in the worktree"+ );++ let contents = fs::read_to_string(&info_file).expect("Failed to read info.txt");++ // Verify that template variables were actually expanded, not left as literals+ assert!(+ contents.contains(&format!("Repo: {}", repo_name)),+ "Should contain expanded repo name, got: {}",+ contents+ );+ assert!(+ contents.contains("Branch: feature-test"),+ "Should contain expanded branch name (sanitized), got: {}",+ contents+ );+ assert!(+ contents.contains(&format!(+ "Worktree: {}",+ worktree_path.canonicalize().unwrap().display()+ )),+ "Should contain expanded worktree path, got: {}",+ contents+ );+ assert!(+ contents.contains(&format!(+ "Root: {}",+ repo.root_path().canonicalize().unwrap().display()+ )),+ "Should contain expanded repo root path, got: {}",+ contents+ );++ // Make sure they're NOT the literal template strings+ assert!(+ !contents.contains("{repo}"),+ "Should not contain literal {{repo}} placeholder"+ );+ assert!(+ !contents.contains("{branch}"),+ "Should not contain literal {{branch}} placeholder"+ );+ assert!(+ !contents.contains("{worktree}"),+ "Should not contain literal {{worktree}} placeholder"+ );+ assert!(+ !contents.contains("{repo_root}"),+ "Should not contain literal {{repo_root}} placeholder"+ );+}diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_template_expansion.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_template_expansion.snapnew file mode 100644index 000000000..40651000d--- /dev/null+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_template_expansion.snap@@ -0,0 +1,31 @@+---+source: tests/integration_tests/post_start_commands.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - feature/test+ env:+ CLICOLOR_FORCE: "1"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: true+exit_code: 0+----- stdout -----+Created new branch and worktree for [1mfeature/test[0m at [REPO].feature-test++To enable automatic cd, run: wt configure-shell++----- stderr -----+Executing: echo 'Repo: main' > info.txt+Executing: echo 'Branch: feature-test' >> info.txt+Executing: echo 'Worktree: [REPO].feature-test' >> info.txt+Executing: echo 'Root: [REPO]' >> info.txt