Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Introduce configurable worktree path formatting
Maximilian Roosf573758852ad
diff --git a/src/config.rs b/src/config.rsindex 018e9896e..629487a39 100644--- a/src/config.rs+++ b/src/config.rs@@ -3,6 +3,34 @@ use directories::ProjectDirs;use serde::{Deserialize, Serialize};use std::path::PathBuf;+/// Configuration for worktree path formatting.+///+/// The `worktree-path` template is relative to the repository root and supports:+/// - `{repo}` - Repository name+/// - `{branch}` - Branch name (slashes replaced with dashes)+///+/// # Examples+///+/// ```toml+/// # Default - parent directory siblings+/// worktree-path = "../{repo}.{branch}"+///+/// # Inside repo (bare repository style)+/// worktree-path = "{branch}"+///+/// # Organized in .worktrees subdirectory+/// worktree-path = ".worktrees/{branch}"+///+/// # Repository-namespaced shared directory (avoids conflicts)+/// worktree-path = "../worktrees/{repo}/{branch}"+/// ```+///+/// Config file location:+/// - Linux: `~/.config/worktrunk/config.toml`+/// - macOS: `~/Library/Application Support/worktrunk/config.toml`+/// - Windows: `%APPDATA%\worktrunk\config.toml`+///+/// Environment variable: `WORKTRUNK_WORKTREE_PATH`#[derive(Debug, Serialize, Deserialize)]pub struct WorktrunkConfig {#[serde(rename = "worktree-path")]@@ -12,7 +40,7 @@ pub struct WorktrunkConfig {impl Default for WorktrunkConfig {fn default() -> Self {Self {- worktree_path: "{repo}.{branch}".to_string(),+ worktree_path: "../{repo}.{branch}".to_string(),}}}@@ -36,7 +64,35 @@ pub fn load_config() -> Result<WorktrunkConfig, ConfigError> {// Add environment variables with WORKTRUNK prefixbuilder = builder.add_source(config::Environment::with_prefix("WORKTRUNK").separator("_"));- builder.build()?.try_deserialize()+ let config: WorktrunkConfig = builder.build()?.try_deserialize()?;+ validate_worktree_path(&config.worktree_path)?;+ Ok(config)+}++fn validate_worktree_path(template: &str) -> Result<(), ConfigError> {+ if template.is_empty() {+ return Err(ConfigError::Message(+ "worktree-path cannot be empty".to_string(),+ ));+ }++ // Reject absolute paths+ let path = std::path::Path::new(template);+ if path.is_absolute() {+ return Err(ConfigError::Message(+ "worktree-path must be relative, not absolute".to_string(),+ ));+ }++ Ok(())+}++pub fn format_worktree_path(template: &str, repo: &str, branch: &str) -> String {+ // Sanitize branch name by replacing path separators to prevent directory traversal+ let safe_branch = branch.replace('/', "-").replace('\\', "-");+ template+ .replace("{repo}", repo)+ .replace("{branch}", &safe_branch)}#[cfg(test)]@@ -46,7 +102,7 @@ mod tests {#[test]fn test_default_config() {let config = WorktrunkConfig::default();- assert_eq!(config.worktree_path, "{repo}.{branch}");+ assert_eq!(config.worktree_path, "../{repo}.{branch}");}#[test]@@ -54,13 +110,92 @@ mod tests {let config = WorktrunkConfig::default();let toml = toml::to_string(&config).unwrap();assert!(toml.contains("worktree-path"));- assert!(toml.contains("{repo}.{branch}"));+ assert!(toml.contains("../{repo}.{branch}"));}#[test]fn test_load_config_defaults() {// Without a config file or env vars, should return defaultslet config = load_config().unwrap();- assert_eq!(config.worktree_path, "{repo}.{branch}");+ assert_eq!(config.worktree_path, "../{repo}.{branch}");+ }++ #[test]+ fn test_format_worktree_path() {+ assert_eq!(+ format_worktree_path("{repo}.{branch}", "myproject", "feature-x"),+ "myproject.feature-x"+ );+ }++ #[test]+ fn test_format_worktree_path_custom_template() {+ assert_eq!(+ format_worktree_path("{repo}-{branch}", "myproject", "feature-x"),+ "myproject-feature-x"+ );+ }++ #[test]+ fn test_format_worktree_path_only_branch() {+ assert_eq!(+ format_worktree_path("{branch}", "myproject", "feature-x"),+ "feature-x"+ );+ }++ #[test]+ fn test_format_worktree_path_with_slashes() {+ // Slashes should be replaced with dashes to prevent directory traversal+ assert_eq!(+ format_worktree_path("{repo}.{branch}", "myproject", "feature/foo"),+ "myproject.feature-foo"+ );+ }++ #[test]+ fn test_format_worktree_path_with_multiple_slashes() {+ assert_eq!(+ format_worktree_path("{branch}", "myproject", "feature/sub/task"),+ "feature-sub-task"+ );+ }++ #[test]+ fn test_format_worktree_path_with_backslashes() {+ // Windows-style path separators should also be sanitized+ assert_eq!(+ format_worktree_path("{branch}", "myproject", "feature\\foo"),+ "feature-foo"+ );+ }++ #[test]+ fn test_validate_rejects_empty_path() {+ let result = validate_worktree_path("");+ assert!(result.is_err());+ assert!(result.unwrap_err().to_string().contains("cannot be empty"));+ }++ #[test]+ fn test_validate_rejects_absolute_path_unix() {+ let result = validate_worktree_path("/absolute/path/{branch}");+ assert!(result.is_err());+ assert!(result.unwrap_err().to_string().contains("must be relative"));+ }++ #[test]+ #[cfg(target_os = "windows")]+ fn test_validate_rejects_absolute_path_windows() {+ let result = validate_worktree_path("C:\\absolute\\path\\{branch}");+ assert!(result.is_err());+ assert!(result.unwrap_err().to_string().contains("must be relative"));+ }++ #[test]+ fn test_validate_accepts_relative_path() {+ assert!(validate_worktree_path(".worktrees/{branch}").is_ok());+ assert!(validate_worktree_path("../{repo}.{branch}").is_ok());+ assert!(validate_worktree_path("../../shared/{branch}").is_ok());}}diff --git a/src/main.rs b/src/main.rsindex f92e2d168..8e9fdef99 100644--- a/src/main.rs+++ b/src/main.rs@@ -4,6 +4,7 @@ use clap_complete::{Shell as CompletionShell, generate};use rayon::prelude::*;use std::io;use std::process;+use worktrunk::config::{format_worktree_path, load_config};use worktrunk::error_format::{format_error_with_bold, format_hint, format_warning};use worktrunk::git::{GitError, Worktree, branch_exists, count_commits, get_ahead_behind_in, get_all_branches,@@ -132,7 +133,17 @@ fn main() {create,base,internal,- } => handle_switch(&branch, create, base.as_deref(), internal),+ } => load_config()+ .map_err(|e| GitError::CommandFailed(format!("Failed to load config: {}", e)))+ .and_then(|config| {+ handle_switch(+ &branch,+ create,+ base.as_deref(),+ internal,+ &config.worktree_path,+ )+ }),Commands::Remove { internal } => handle_remove(internal),Commands::Push {target,@@ -499,6 +510,7 @@ fn handle_switch(create: bool,base: Option<&str>,internal: bool,+ worktree_path_template: &str,) -> Result<(), GitError> {// Check for conflicting conditionsif create && branch_exists(branch)? {@@ -548,11 +560,8 @@ fn handle_switch(.to_str().ok_or_else(|| GitError::CommandFailed("Invalid UTF-8 in path".to_string()))?;- let parent_dir = repo_root- .parent()- .ok_or_else(|| GitError::CommandFailed("Invalid repository location".to_string()))?;-- let worktree_path = parent_dir.join(format!("{}.{}", repo_name, branch));+ let worktree_name = format_worktree_path(worktree_path_template, repo_name, branch);+ let worktree_path = repo_root.join(worktree_name);// Create the worktree// Build git worktree add commanddiff --git a/tests/snapshots/integration__integration_tests__switch__switch_create_new.snap b/tests/snapshots/integration__integration_tests__switch__switch_create_new.snapindex a9c01090e..a2178c2dc 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_create_new.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_create_new.snap@@ -20,7 +20,7 @@ success: trueexit_code: 0----- stdout -----Created new branch and worktree for 'feature-x'-Path: [REPO].feature-x+Path: [REPO]/../main.feature-xNote: Use 'wt switch' (with shell integration) for automatic cd----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__switch__switch_internal_mode.snap b/tests/snapshots/integration__integration_tests__switch__switch_internal_mode.snapindex c0040b8c3..dbe808c93 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_internal_mode.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_internal_mode.snap@@ -20,7 +20,7 @@ info:success: trueexit_code: 0----- stdout ------__WORKTRUNK_CD__[REPO].internal-test-Created new branch and worktree for 'internal-test' at [REPO].internal-test+__WORKTRUNK_CD__[REPO]/../main.internal-test+Created new branch and worktree for 'internal-test' at [REPO]/../main.internal-test----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__switch__switch_with_base.snap b/tests/snapshots/integration__integration_tests__switch__switch_with_base.snapindex 5d2e5a9d0..b84b458eb 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_with_base.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_with_base.snap@@ -22,7 +22,7 @@ success: trueexit_code: 0----- stdout -----Created new branch and worktree for 'feature-with-base'-Path: [REPO].feature-with-base+Path: [REPO]/../main.feature-with-baseNote: Use 'wt switch' (with shell integration) for automatic cd----- stderr -----