Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Fix Windows path quoting in shell templates (#161)
Maximilian Roosa87c8a35a1f2
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex 36b0f500a..be82fad9d 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -5,6 +5,7 @@ use worktrunk::config::{Command, CommandConfig, WorktrunkConfig, expand_template, sanitize_branch_name,};use worktrunk::git::Repository;+use worktrunk::path::to_posix_path;#[derive(Debug)]pub struct PreparedCommand {@@ -63,7 +64,9 @@ pub fn build_hook_context(.and_then(|n| n.to_str()).unwrap_or("unknown");- let worktree = ctx.worktree_path.to_string_lossy();+ // Convert paths to POSIX format for Git Bash compatibility on Windows.+ // This avoids shell escaping of `:` and `\` characters in Windows paths.+ let worktree = to_posix_path(&ctx.worktree_path.to_string_lossy());let worktree_name = ctx.worktree_path.file_name()@@ -74,9 +77,12 @@ pub fn build_hook_context(map.insert("repo".into(), repo_name.into());map.insert("main_worktree".into(), repo_name.into()); // Alias for repomap.insert("branch".into(), sanitize_branch_name(ctx.branch_or_head()));- map.insert("worktree".into(), worktree.into());+ map.insert("worktree".into(), worktree);map.insert("worktree_name".into(), worktree_name.into());- map.insert("repo_root".into(), repo_root.to_string_lossy().into());+ map.insert(+ "repo_root".into(),+ to_posix_path(&repo_root.to_string_lossy()),+ );if let Ok(default_branch) = ctx.repo.default_branch() {map.insert("default_branch".into(), default_branch);diff --git a/src/path.rs b/src/path.rsindex 7d421a385..a2e4b7ef6 100644--- a/src/path.rs+++ b/src/path.rs@@ -1,5 +1,80 @@use std::path::{Path, PathBuf};+#[cfg(windows)]+use std::process::Command;++/// Convert a path to POSIX format for Git Bash compatibility.+///+/// On Windows, uses `cygpath -u` from Git for Windows to convert paths like+/// `C:\Users\test` to `/c/Users/test`. This handles all edge cases including+/// UNC paths (`\\server\share`) and verbatim paths (`\\?\C:\...`).+///+/// If cygpath is not available, returns the path unchanged.+///+/// On Unix, returns the path unchanged.+///+/// # Examples+/// - `C:\Users\test\repo` → `/c/Users/test/repo`+/// - `D:\a\worktrunk` → `/d/a/worktrunk`+/// - `\\?\C:\repo` → `/c/repo` (verbatim prefix stripped)+/// - `/tmp/test/repo` → `/tmp/test/repo` (unchanged on Unix)+#[cfg(windows)]+pub fn to_posix_path(path: &str) -> String {+ use crate::shell_exec::ShellConfig;++ let Some(cygpath) = find_cygpath_from_shell(ShellConfig::get()) else {+ return path.to_string();+ };++ let Ok(output) = Command::new(&cygpath).arg("-u").arg(path).output() else {+ return path.to_string();+ };++ if output.status.success() {+ String::from_utf8_lossy(&output.stdout).trim().to_string()+ } else {+ path.to_string()+ }+}++#[cfg(not(windows))]+pub fn to_posix_path(path: &str) -> String {+ path.to_string()+}++/// Find cygpath.exe relative to the shell executable.+///+/// cygpath is always at `usr/bin/cygpath.exe` in a Git for Windows installation.+/// bash.exe can be at `bin/bash.exe` or `usr/bin/bash.exe`, so we check both+/// relative paths.+#[cfg(windows)]+fn find_cygpath_from_shell(shell: &crate::shell_exec::ShellConfig) -> Option<PathBuf> {+ // Only Git Bash has cygpath+ if !shell.is_posix {+ return None;+ }++ let shell_dir = shell.executable.parent()?;++ // If bash is at usr/bin/bash.exe, cygpath is in the same directory+ let cygpath = shell_dir.join("cygpath.exe");+ if cygpath.exists() {+ return Some(cygpath);+ }++ // If bash is at bin/bash.exe, cygpath is at ../usr/bin/cygpath.exe+ let cygpath = shell_dir+ .parent()?+ .join("usr")+ .join("bin")+ .join("cygpath.exe");+ if cygpath.exists() {+ return Some(cygpath);+ }++ None+}+/// Get the user's home directory.////// Uses the `home` crate which handles platform-specific detection:@@ -33,7 +108,7 @@ pub fn format_path_for_display(path: &Path) -> String {mod tests {use std::path::PathBuf;- use super::{format_path_for_display, home_dir};+ use super::{format_path_for_display, home_dir, to_posix_path};#[test]fn shortens_path_under_home() {@@ -75,4 +150,39 @@ mod tests {let formatted = format_path_for_display(&path);assert_eq!(formatted, path.display().to_string());}++ // Tests for to_posix_path behavior (results depend on platform)+ #[test]+ fn to_posix_path_leaves_unix_paths_unchanged() {+ // Unix-style paths should pass through unchanged on all platforms+ assert_eq!(to_posix_path("/tmp/test/repo"), "/tmp/test/repo");+ assert_eq!(to_posix_path("relative/path"), "relative/path");+ }++ #[test]+ #[cfg(windows)]+ fn to_posix_path_converts_windows_drive_letter() {+ // On Windows, drive letters should be converted to /x/ format+ let result = to_posix_path(r"C:\Users\test");+ assert!(+ result.starts_with("/c/"),+ "Expected /c/ prefix, got: {result}"+ );+ assert!(+ result.contains("Users"),+ "Expected Users in path, got: {result}"+ );+ }++ #[test]+ #[cfg(windows)]+ fn to_posix_path_handles_verbatim_paths() {+ // cygpath should handle verbatim paths (\\?\C:\...)+ let result = to_posix_path(r"\\?\C:\Users\test");+ // Should either strip \\?\ prefix or handle it correctly+ assert!(+ result.contains("/c/") || result.contains("Users"),+ "Expected converted path, got: {result}"+ );+ }}diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex 75efcb48a..455b85411 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -418,6 +418,7 @@ use std::path::{Path, PathBuf};use std::process::Command;use tempfile::TempDir;use worktrunk::config::sanitize_branch_name;+use worktrunk::path::to_posix_path;/// Path to the fixture template repo (relative to crate root)./// Contains `_git/` (renamed .git) and `gitconfig`.@@ -1539,6 +1540,8 @@ pub fn setup_snapshot_settings(repo: &TestRepo) -> insta::Settings {// (output may have either format depending on when filters are applied)settings.add_filter(®ex::escape(root_str), "[REPO]");settings.add_filter(®ex::escape(&root_str.replace('\\', "/")), "[REPO]");+ // Also add POSIX-style path for Git Bash (C:\foo\bar -> /c/foo/bar)+ settings.add_filter(®ex::escape(&to_posix_path(root_str)), "[REPO]");// In tests, HOME is set to the temp directory containing the repo. Commands being tested// see HOME=temp_dir, so format_path_for_display() outputs ~/repo instead of the full path.@@ -1568,6 +1571,8 @@ pub fn setup_snapshot_settings(repo: &TestRepo) -> insta::Settings {let replacement = format!("[WORKTREE_{}]", name.to_uppercase().replace('-', "_"));settings.add_filter(®ex::escape(path_str), &replacement);settings.add_filter(®ex::escape(&path_str.replace('\\', "/")), &replacement);+ // Also add POSIX-style path for Git Bash (C:\foo\bar -> /c/foo/bar)+ settings.add_filter(®ex::escape(&to_posix_path(path_str)), &replacement);// Also add tilde-prefixed worktree path filter for Windowsif let Some(home) = home::home_dir().and_then(|h| canonicalize(&h).ok())@@ -1586,6 +1591,12 @@ pub fn setup_snapshot_settings(repo: &TestRepo) -> insta::Settings {// paths used in commands. MUST come after backslash normalization so paths have forward slashes.// Pattern: ~/AppData/Local/Temp/.tmpXXXXXX/repo (where XXXXXX varies)settings.add_filter(r"~/AppData/Local/Temp/\.tmp[^/]+/repo", "[REPO]");+ // Windows fallback for POSIX-style paths from Git Bash (used in hook template expansion).+ // Pattern: /c/Users/.../Temp/.tmpXXXXXX/repo and worktrees like /c/.../repo.feature-test+ settings.add_filter(+ r"/[a-z]/Users/[^/]+/AppData/Local/Temp/\.tmp[^/]+/repo(\.[a-zA-Z0-9_/-]+)?",+ "[REPO]$1",+ );// Normalize temp directory paths in project identifiers (approval prompts)// Example: /private/var/folders/wf/.../T/.tmpABC123/origin -> [PROJECT_ID]diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rsindex 2452c5dce..923126737 100644--- a/tests/integration_tests/post_start_commands.rs+++ b/tests/integration_tests/post_start_commands.rs@@ -124,8 +124,6 @@ approved-commands = ["exit 1"]);}-/// Skipped on Windows: snapshot output differs due to shell/path differences.-#[cfg_attr(windows, ignore)]#[rstest]fn test_post_create_template_expansion(repo: TestRepo) {// Create project config with template variables@@ -190,8 +188,6 @@ approved-commands = [);}-/// Skipped on Windows: snapshot output differs due to shell/path differences.-#[cfg_attr(windows, ignore)]#[rstest]fn test_post_create_default_branch_template(repo: TestRepo) {// Create project config with default_branch template variable@@ -234,8 +230,6 @@ approved-commands = ["echo 'Default: {{ default_branch }}' > default.txt"]);}-/// Skipped on Windows: snapshot output differs due to shell/path differences.-#[cfg_attr(windows, ignore)]#[rstest]fn test_post_create_git_variables_template(#[from(repo_with_remote)] repo: TestRepo) {// Set up an upstream tracking branch@@ -308,8 +302,6 @@ worktree_name = "echo 'Worktree Name: {{ worktree_name }}' >> git_vars.txt");}-/// Skipped on Windows: snapshot output differs due to shell/path differences.-#[cfg_attr(windows, ignore)]#[rstest]fn test_post_create_upstream_template(#[from(repo_with_remote)] repo: TestRepo) {// Push main to set up tracking@@ -349,9 +341,7 @@ fn test_post_create_upstream_template(#[from(repo_with_remote)] repo: TestRepo)}/// Test that hooks receive JSON context on stdin-/// Skipped on Windows: snapshot output differs due to shell/path differences.#[rstest]-#[cfg_attr(windows, ignore)]fn test_post_create_json_stdin(repo: TestRepo) {use crate::common::wt_command;@@ -530,10 +520,7 @@ approved-commands = ["./scripts/setup.py"]}/// Test that background hooks also receive JSON context on stdin-///-/// Skipped on Windows: Uses `cat` command which is not available natively on Windows.#[rstest]-#[cfg_attr(windows, ignore)]fn test_post_start_json_stdin(repo: TestRepo) {use crate::common::wt_command;@@ -730,8 +717,6 @@ fn test_invalid_toml(repo: TestRepo) {// Additional Coverage Tests// ============================================================================-/// Skipped on Windows: snapshot output differs due to shell/path differences.-#[cfg_attr(windows, ignore)]#[rstest]fn test_post_start_log_file_captures_output(repo: TestRepo) {// Create command that writes to both stdout and stderr@@ -819,8 +804,6 @@ approved-commands = ["echo 'unclosed quote"]);}-/// Skipped on Windows: snapshot output differs due to shell/path differences.-#[cfg_attr(windows, ignore)]#[rstest]fn test_post_start_multiple_commands_separate_logs(repo: TestRepo) {// Create multiple background commands with distinct output@@ -902,8 +885,6 @@ approved-commands = [);}-/// Skipped on Windows: snapshot output differs due to shell/path differences.-#[cfg_attr(windows, ignore)]#[rstest]fn test_execute_flag_with_post_start_commands(repo: TestRepo) {// Create post-start command@@ -947,8 +928,6 @@ approved-commands = ["echo 'Background task' > background.txt"]);}-/// Skipped on Windows: snapshot output differs due to shell/path differences.-#[cfg_attr(windows, ignore)]#[rstest]fn test_post_start_complex_shell_commands(repo: TestRepo) {// Create command with pipes and redirects@@ -978,8 +957,6 @@ approved-commands = ["echo 'line1\nline2\nline3' | grep line2 > filtered.txt"]assert_snapshot!(contents, @"line2");}-/// Skipped on Windows: snapshot output differs due to shell/path differences.-#[cfg_attr(windows, ignore)]#[rstest]fn test_post_start_multiline_commands_with_newlines(repo: TestRepo) {// Create command with actual newlines (using TOML triple-quoted string)@@ -1028,8 +1005,6 @@ approved-commands = ["""");}-/// Skipped on Windows: snapshot output differs due to shell/path differences.-#[cfg_attr(windows, ignore)]#[rstest]fn test_post_create_multiline_with_control_structures(repo: TestRepo) {// Test multiline command with if-else control structure@@ -1089,8 +1064,6 @@ approved-commands = ["""////// This is a regression test for a bug where post-start commands were running on ALL/// `wt switch` operations instead of only on `wt switch --create`.-/// Skipped on Windows: snapshot output differs due to shell/path differences.-#[cfg_attr(windows, ignore)]#[rstest]fn test_post_start_skipped_on_existing_worktree(repo: TestRepo) {// Create project config with post-start commanddiff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex 5858fd917..d3ef46aaf 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -736,8 +736,6 @@ approved-commands = ["echo 'About to remove worktree'"]}/// Test pre-remove hook has access to template variables.-/// Skipped on Windows: snapshot output differs due to shell/path differences.-#[cfg_attr(windows, ignore)]#[rstest]fn test_pre_remove_hook_template_variables(mut repo: TestRepo) {// Create project config with template variables@@ -776,8 +774,6 @@ approved-commands = [}/// Test pre-remove hook runs even in background mode (before spawning background process).-/// Skipped on Windows: snapshot output differs due to shell/path differences.-#[cfg_attr(windows, ignore)]#[rstest]fn test_pre_remove_hook_runs_in_background_mode(mut repo: TestRepo) {use crate::common::wait_for_file;@@ -1003,8 +999,6 @@ approved-commands = ["touch {marker_path}"]////// This complements `test_pre_remove_hook_runs_for_detached_head` by verifying/// the hook also runs when removal happens in background (the default).-/// Skipped on Windows: snapshot output differs due to shell/path differences.-#[cfg_attr(windows, ignore)]#[rstest]fn test_pre_remove_hook_runs_for_detached_head_background(mut repo: TestRepo) {// Create marker file path in the repo rootdiff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex 169dd7db7..1907104cd 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -7,8 +7,8 @@//! - Skipped together with project hooks via --no-verifyuse crate::common::{- TestRepo, make_snapshot_cmd, repo, repo_with_feature_worktree, setup_snapshot_settings,- wait_for_file, wait_for_file_content,+ TestRepo, make_snapshot_cmd, repo, setup_snapshot_settings, wait_for_file,+ wait_for_file_content,};use insta_cmd::assert_cmd_snapshot;use rstest::rstest;@@ -251,8 +251,10 @@ fn snapshot_merge(test_name: &str, repo: &TestRepo, args: &[&str], cwd: Option<&}#[rstest]-fn test_user_pre_merge_hook_executes(#[from(repo_with_feature_worktree)] repo: TestRepo) {- let feature_wt = repo.worktree_path("feature");+fn test_user_pre_merge_hook_executes(mut repo: TestRepo) {+ // Create feature worktree with a commit+ let feature_wt =+ repo.add_worktree_with_commit("feature", "feature.txt", "feature content", "Add feature");// Write user config with pre-merge hookrepo.write_test_config(@@ -267,7 +269,7 @@ check = "echo 'USER_PRE_MERGE_RAN' > user_premerge.txt""user_pre_merge_executes",&repo,&["main", "--force", "--no-remove"],- Some(feature_wt),+ Some(&feature_wt),);// Verify user hook ran@@ -276,10 +278,10 @@ check = "echo 'USER_PRE_MERGE_RAN' > user_premerge.txt"}#[rstest]-fn test_user_pre_merge_hook_failure_blocks_merge(- #[from(repo_with_feature_worktree)] repo: TestRepo,-) {- let feature_wt = repo.worktree_path("feature");+fn test_user_pre_merge_hook_failure_blocks_merge(mut repo: TestRepo) {+ // Create feature worktree with a commit+ let feature_wt =+ repo.add_worktree_with_commit("feature", "feature.txt", "feature content", "Add feature");// Write user config with failing pre-merge hookrepo.write_test_config(@@ -295,13 +297,15 @@ check = "exit 1""user_pre_merge_failure",&repo,&["main", "--force", "--no-remove"],- Some(feature_wt),+ Some(&feature_wt),);}#[rstest]-fn test_user_pre_merge_skipped_with_no_verify(#[from(repo_with_feature_worktree)] repo: TestRepo) {- let feature_wt = repo.worktree_path("feature");+fn test_user_pre_merge_skipped_with_no_verify(mut repo: TestRepo) {+ // Create feature worktree with a commit+ let feature_wt =+ repo.add_worktree_with_commit("feature", "feature.txt", "feature content", "Add feature");// Write user config with pre-merge hook that creates a markerrepo.write_test_config(@@ -316,7 +320,7 @@ check = "echo 'USER_PRE_MERGE' > user_premerge_marker.txt""user_pre_merge_skipped_no_verify",&repo,&["main", "--force", "--no-remove", "--no-verify"],- Some(feature_wt),+ Some(&feature_wt),);// User hook should NOT have run (--no-verify skips all hooks)@@ -389,8 +393,10 @@ long = "sh -c 'echo start >> hook.log; sleep 30; echo done >> hook.log'"// ============================================================================#[rstest]-fn test_user_post_merge_hook_executes(#[from(repo_with_feature_worktree)] repo: TestRepo) {- let feature_wt = repo.worktree_path("feature");+fn test_user_post_merge_hook_executes(mut repo: TestRepo) {+ // Create feature worktree with a commit+ let feature_wt =+ repo.add_worktree_with_commit("feature", "feature.txt", "feature content", "Add feature");// Write user config with post-merge hookrepo.write_test_config(@@ -405,7 +411,7 @@ notify = "echo 'USER_POST_MERGE_RAN' > user_postmerge.txt""user_post_merge_executes",&repo,&["main", "--force", "--no-remove"],- Some(feature_wt),+ Some(&feature_wt),);// Post-merge runs in the destination (main) worktreediff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_post_merge_executes.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_post_merge_executes.snapindex a1f8cf843..d45752288 100644--- a/tests/snapshots/integration__integration_tests__user_hooks__user_post_merge_executes.snap+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_post_merge_executes.snap@@ -30,8 +30,8 @@ exit_code: 0----- stdout ---------- stderr ------🔄 [36mMerging 1 commit to [1mmain[22m @ [2m3cf9bf5[22m (no commit/squash/rebase needed)[39m-[107m [0m * [33m3cf9bf5[m Add feature file+🔄 [36mMerging 1 commit to [1mmain[22m @ [2m90f2330[22m (no commit/squash/rebase needed)[39m+[107m [0m * [33m90f2330[m Add feature[107m [0m feature.txt | 1 [32m+[m[107m [0m 1 file changed, 1 insertion(+)✅ [32mMerged to [1mmain[22m [90m(1 commit, 1 file, [32m+1[39m[39m[90m)[39m[39mdiff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_pre_merge_executes.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_merge_executes.snapindex 28388cab9..6349c4dac 100644--- a/tests/snapshots/integration__integration_tests__user_hooks__user_pre_merge_executes.snap+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_merge_executes.snap@@ -32,8 +32,8 @@ exit_code: 0----- stderr -----🔄 [36mRunning user pre-merge [1mcheck[22m:[39m[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'USER_PRE_MERGE_RAN'[0m[2m [0m[2m[36m>[0m[2m user_premerge.txt-[0m🔄 [36mMerging 1 commit to [1mmain[22m @ [2m3cf9bf5[22m (no commit/squash/rebase needed)[39m-[107m [0m * [33m3cf9bf5[m Add feature file+[0m🔄 [36mMerging 1 commit to [1mmain[22m @ [2m90f2330[22m (no commit/squash/rebase needed)[39m+[107m [0m * [33m90f2330[m Add feature[107m [0m feature.txt | 1 [32m+[m[107m [0m 1 file changed, 1 insertion(+)✅ [32mMerged to [1mmain[22m [90m(1 commit, 1 file, [32m+1[39m[39m[90m)[39m[39mdiff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_pre_merge_skipped_no_verify.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_merge_skipped_no_verify.snapindex b930ca272..27bffe037 100644--- a/tests/snapshots/integration__integration_tests__user_hooks__user_pre_merge_skipped_no_verify.snap+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_merge_skipped_no_verify.snap@@ -31,8 +31,8 @@ exit_code: 0----- stdout ---------- stderr ------🔄 [36mMerging 1 commit to [1mmain[22m @ [2m3cf9bf5[22m (no commit/squash/rebase needed)[39m-[107m [0m * [33m3cf9bf5[m Add feature file+🔄 [36mMerging 1 commit to [1mmain[22m @ [2m90f2330[22m (no commit/squash/rebase needed)[39m+[107m [0m * [33m90f2330[m Add feature[107m [0m feature.txt | 1 [32m+[m[107m [0m 1 file changed, 1 insertion(+)✅ [32mMerged to [1mmain[22m [90m(1 commit, 1 file, [32m+1[39m[39m[90m)[39m[39m