Skip to content

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

feat: use tilde paths in shell command hints when safe (#710)

Maximilian Roos7ab70ac5cbf6
diff --git a/Cargo.toml b/Cargo.toml
index 8c90e4a47..d0141a6d9 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -106,6 +106,7 @@ home = "0.5.12"
once_cell = "1.21"
dirs = "6.0"
normalize-path = "0.2.1"
+path-slash = "0.2"
pathdiff = "0.2"
which = "8.0"
# Cross-platform path canonicalization that avoids Windows verbatim paths (\\?\)
@@ -139,7 +140,6 @@ regex = "1.12"
vt100 = "0.16"
ansi-to-html = "0.2.2"
wt-perf = { path = "tests/helpers/wt-perf" }
-path-slash = "0.2.1"
[[bench]]
name = "completion"
diff --git a/src/config/deprecation.rs b/src/config/deprecation.rs
index 3e76ad915..f94c68aa5 100644
--- a/src/config/deprecation.rs
+++ b/src/config/deprecation.rs
@@ -25,6 +25,7 @@ use regex::Regex;
use shell_escape::unix::escape;
use crate::config::WorktrunkConfig;
+use crate::path::format_path_for_display;
use crate::styling::{eprintln, hint_message, warning_message};
/// Tracks which config paths have already shown deprecation warnings this process.
@@ -516,23 +517,21 @@ pub fn check_and_migrate(
let _ = repo.mark_hint_shown(HINT_DEPRECATED_CONFIG);
}
- // Show just the filename in the message, full paths in the command
+ // Show just the filename in the message, tilde paths when safe in the command
let new_filename = new_path
.file_name()
.map(|n| n.to_string_lossy())
.unwrap_or_default();
- // Use forward slashes for cross-platform compatibility (works in Git Bash on Windows)
- // Don't shell-escape since config paths rarely have special characters
- let new_path_str = new_path.to_string_lossy().replace('\\', "/");
- let path_str = path.to_string_lossy().replace('\\', "/");
+ let new_path_display = format_path_for_display(&new_path);
+ let path_display = format_path_for_display(path);
eprintln!(
"{}",
hint_message(cformat!(
"Wrote migrated {}; to apply: <bright-black>mv -- {} {}</>",
new_filename,
- new_path_str,
- path_str
+ new_path_display,
+ path_display
))
);
}
diff --git a/src/diagnostic.rs b/src/diagnostic.rs
index 0dd25d67e..446cf3606 100644
--- a/src/diagnostic.rs
+++ b/src/diagnostic.rs
@@ -42,14 +42,12 @@
//! eprintln!("{}", hint_message(issue_hint()));
//! ```
//!
-use std::borrow::Cow;
-use std::path::{Path, PathBuf};
+use std::path::PathBuf;
use ansi_str::AnsiStr;
use anyhow::Context;
use color_print::cformat;
use minijinja::{Environment, context};
-use shell_escape::unix::escape as posix_escape;
use worktrunk::git::Repository;
use worktrunk::path::format_path_for_display;
use worktrunk::shell_exec::Cmd;
@@ -58,27 +56,6 @@ use worktrunk::styling::{eprintln, hint_message, info_message, warning_message};
use crate::cli::version_str;
use crate::output;
-/// Shell-escape a path for use in POSIX shell commands.
-///
-/// This is used for hints like `gh gist create --web <path>` that users copy/paste.
-/// We use POSIX escaping because:
-/// - `gh` is a cross-platform CLI that accepts POSIX-style paths on all platforms
-/// - Users on Windows typically use Git Bash or similar POSIX-compatible shells
-/// - The `shell_escape` crate's platform-specific escaping produces different output
-/// on Windows (cmd.exe style) vs Unix (POSIX style), causing snapshot test failures
-///
-/// We normalize Windows backslashes to forward slashes for consistent output.
-fn shell_escape_path(path: &Path) -> Cow<'_, str> {
- let path_str = path.to_string_lossy();
- // Normalize Windows backslashes to forward slashes for consistent POSIX-style paths
- let normalized = if path_str.contains('\\') {
- Cow::Owned(path_str.replace('\\', "/"))
- } else {
- path_str
- };
- posix_escape(normalized)
-}
-
/// Markdown template for the diagnostic report.
///
/// This template makes the report structure immediately visible.
@@ -263,7 +240,7 @@ pub(crate) fn write_if_verbose(verbose: u8, command_line: &str, error_msg: Optio
// Only show gh command if gh is installed
if is_gh_installed() {
- let path_str = shell_escape_path(&path);
+ let path_str = format_path_for_display(&path);
// URL with prefilled body: ## Gist\n\n[Paste URL]\n\n## Description\n\n[Describe the issue]
let issue_url = "https://github.com/max-sixty/worktrunk/issues/new?body=%23%23%20Gist%0A%0A%5BPaste%20gist%20URL%5D%0A%0A%23%23%20Description%0A%0A%5BDescribe%20the%20issue%5D";
eprintln!(
@@ -462,30 +439,4 @@ mod tests {
assert!(result.starts_with("(log truncated to last ~50KB)"));
assert!(result.len() < 55 * 1024);
}
-
- #[test]
- fn test_shell_escape_path_unix_style() {
- // Unix paths with no special chars pass through unchanged
- let path = Path::new("/home/user/project/.git/wt-logs/diagnostic.md");
- let result = shell_escape_path(path);
- assert_eq!(result, "/home/user/project/.git/wt-logs/diagnostic.md");
- }
-
- #[test]
- fn test_shell_escape_path_windows_backslashes() {
- // Windows backslashes are normalized to forward slashes
- let path = Path::new(r"D:\a\worktrunk\.git\wt-logs\diagnostic.md");
- let result = shell_escape_path(path);
- // The colon in D: requires quoting in POSIX shells
- assert!(result.contains("D:/a/worktrunk"));
- assert!(!result.contains('\\'));
- }
-
- #[test]
- fn test_shell_escape_path_special_chars() {
- // Paths with spaces or special chars get quoted
- let path = Path::new("/path/with spaces/file.md");
- let result = shell_escape_path(path);
- assert!(result.starts_with('\'') || result.contains("\\ "));
- }
}
diff --git a/src/git/error.rs b/src/git/error.rs
index 9bc77b405..ffef2e097 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -402,10 +402,7 @@ impl std::fmt::Display for GitError {
"there's a detached worktree at the expected path <bold>{path_display}</>"
)
};
- // Use actual path for command (not display path with ~, which won't expand in single quotes)
- let path_str = path.to_string_lossy();
- let path_escaped = escape(Cow::Borrowed(path_str.as_ref()));
- let command = format!("cd {path_escaped} && git switch {branch}");
+ let command = format!("cd {path_display} && git switch {branch}");
write!(
f,
"{}\n{}",
@@ -422,8 +419,6 @@ impl std::fmt::Display for GitError {
create,
} => {
let path_display = format_path_for_display(path);
- let path_str = path.to_string_lossy();
- let path_escaped = escape(Cow::Borrowed(path_str.as_ref()));
let flags: &[&str] = if *create {
&["--create", "--clobber"]
} else {
@@ -437,7 +432,7 @@ impl std::fmt::Display for GitError {
"Directory already exists: <bold>{path_display}</>"
)),
hint_message(cformat!(
- "To remove manually, run <bright-black>rm -rf {path_escaped}</>; to overwrite (with backup), run <bright-black>{switch_cmd}</>"
+ "To remove manually, run <bright-black>rm -rf {path_display}</>; to overwrite (with backup), run <bright-black>{switch_cmd}</>"
))
)
}
diff --git a/src/path.rs b/src/path.rs
index e154699ca..e3bee400c 100644
--- a/src/path.rs
+++ b/src/path.rs
@@ -1,8 +1,13 @@
-use std::path::{Path, PathBuf};
+use path_slash::PathExt as _;
+use shell_escape::unix::escape;
+use std::borrow::Cow;
+use std::path::Path;
use crate::config::short_hash;
#[cfg(windows)]
use crate::shell_exec::{Cmd, ShellConfig};
+#[cfg(windows)]
+use std::path::PathBuf;
/// Convert a path to POSIX format for Git Bash compatibility.
///
@@ -81,11 +86,26 @@ fn find_cygpath_from_shell(shell: &crate::shell_exec::ShellConfig) -> Option<Pat
/// - Windows: `USERPROFILE` or `HOMEDRIVE`/`HOMEPATH`
pub use home::home_dir;
+/// Check if a string needs shell escaping (contains characters outside the safe set).
+fn needs_shell_escaping(s: &str) -> bool {
+ !matches!(escape(Cow::Borrowed(s)), Cow::Borrowed(_))
+}
+
/// Format a filesystem path for user-facing output.
///
-/// Replaces home directory prefix with `~` (e.g., `/Users/alex/projects/wt` -> `~/projects/wt`).
-/// Paths outside home are returned unchanged.
+/// Replaces home directory prefix with `~` when safe for shell use. Falls back to
+/// quoted absolute path when escaping is needed (to avoid tilde-in-quotes issues).
+///
+/// Uses POSIX shell escaping since all our hints target POSIX-compatible shells
+/// (bash, zsh, fish, and Git Bash on Windows).
+///
+/// # Examples
+/// - `/Users/alex/repo` → `~/repo` (no escaping needed)
+/// - `/Users/alex/my repo` → `'/Users/alex/my repo'` (needs quoting, use original)
+/// - `/tmp/repo` → `/tmp/repo` (no escaping needed)
+/// - `/tmp/my repo` → `'/tmp/my repo'` (needs quoting)
pub fn format_path_for_display(path: &Path) -> String {
+ // Try to use tilde for home directory paths
if let Some(home) = home_dir()
&& let Ok(stripped) = path.strip_prefix(&home)
{
@@ -93,12 +113,23 @@ pub fn format_path_for_display(path: &Path) -> String {
return "~".to_string();
}
- let mut display_path = PathBuf::from("~");
- display_path.push(stripped);
- return display_path.display().to_string();
+ // Build tilde path with forward slash (POSIX style, works everywhere)
+ let rest = stripped.to_slash_lossy();
+
+ // Only use tilde form if the rest doesn't need escaping
+ // (tilde doesn't expand inside quotes)
+ if !needs_shell_escaping(&rest) {
+ return format!("~/{rest}");
+ }
}
- path.display().to_string()
+ // Non-home path or escaping needed - use POSIX quoting
+ // Use to_slash_lossy for Windows compatibility (forward slashes in shell hints)
+ let original = path.to_slash_lossy();
+ match escape(Cow::Borrowed(&original)) {
+ Cow::Borrowed(_) => original.into_owned(),
+ Cow::Owned(escaped) => escaped,
+ }
}
/// Sanitize a string for use as a filename on all platforms.
@@ -151,7 +182,9 @@ pub fn sanitize_for_filename(value: &str) -> String {
#[cfg(test)]
mod tests {
- use super::{PathBuf, format_path_for_display, home_dir, sanitize_for_filename, to_posix_path};
+ use std::path::PathBuf;
+
+ use super::{format_path_for_display, home_dir, sanitize_for_filename, to_posix_path};
#[test]
fn shortens_path_under_home() {
@@ -291,4 +324,67 @@ mod tests {
assert!(a.starts_with("origin-feature-"));
assert!(b.starts_with("origin-feature-"));
}
+
+ #[test]
+ #[cfg(unix)]
+ fn format_path_for_display_escaping() {
+ use insta::assert_snapshot;
+
+ let Some(home) = home_dir() else {
+ return;
+ };
+
+ // Build test cases: (input_path, expected_pattern)
+ // For home paths, we normalize output by replacing actual result with description
+ let mut lines = Vec::new();
+
+ // Non-home paths - predictable across machines
+ for path_str in [
+ "/tmp/repo",
+ "/tmp/my repo",
+ "/tmp/file;rm -rf",
+ "/tmp/test'quote",
+ ] {
+ let path = PathBuf::from(path_str);
+ lines.push(format!(
+ "{} => {}",
+ path_str,
+ format_path_for_display(&path)
+ ));
+ }
+
+ // Home-relative paths - normalize by showing ~/... pattern
+ let home_cases = [
+ "workspace/repo", // simple -> ~/workspace/repo
+ "my workspace/repo", // spaces -> quoted absolute
+ "project's/repo", // quote -> quoted absolute
+ ];
+
+ for suffix in home_cases {
+ let path = home.join(suffix);
+ let result = format_path_for_display(&path);
+
+ let display = if result.starts_with('\'') {
+ // Quoted absolute path - normalize for snapshot
+ "QUOTED_ABSOLUTE".to_string()
+ } else {
+ result
+ };
+ lines.push(format!("$HOME/{} => {}", suffix, display));
+ }
+
+ // Home directory itself
+ lines.push(format!("$HOME => {}", format_path_for_display(&home)));
+
+ assert_snapshot!(lines.join("\n"), @r"
+ /tmp/repo => /tmp/repo
+ /tmp/my repo => '/tmp/my repo'
+ /tmp/file;rm -rf => '/tmp/file;rm -rf'
+ /tmp/test'quote => '/tmp/test'\''quote'
+ $HOME/workspace/repo => ~/workspace/repo
+ $HOME/my workspace/repo => QUOTED_ABSOLUTE
+ $HOME/project's/repo => QUOTED_ABSOLUTE
+ $HOME => ~
+ ");
+ }
}
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 2dd157374..d23c58fa3 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -2313,10 +2313,22 @@ fn setup_snapshot_settings_for_paths(
);
// Final cleanup: strip any remaining quotes around placeholders.
- // shell_escape may quote paths, and ANSI codes may appear between quotes and content.
- // This unified pattern matches all placeholder types: _REPO_, _REPO_.suffix, _WORKTREE_X_
+ // shell_escape may quote paths containing ~ (Windows short path notation like RUNNER~1).
+ // ANSI codes may appear between quotes and content.
+ // This pattern matches placeholders with optional suffixes and subpaths:
+ // - '_REPO_' -> _REPO_
+ // - '_REPO_.feat' -> _REPO_.feat
+ // - '_REPO_.name.bak.20250102-000000' -> _REPO_.name.bak.20250102-000000
+ // - '_REPO_/.config/wt.toml' -> _REPO_/.config/wt.toml
+ // - '_WORKTREE_A_/subpath' -> _WORKTREE_A_/subpath
settings.add_filter(
- r"'(?:\x1b\[[0-9;]*m)*(_(?:REPO|WORKTREE_[A-Z0-9_]+)_(?:\.[a-zA-Z0-9_-]+)?)(?:\x1b\[[0-9;]*m)*'",
+ r"'(?:\x1b\[[0-9;]*m)*(_(?:REPO|WORKTREE_[A-Z0-9_]+)_(?:\.[a-zA-Z0-9_.-]+)?(?:/[^']*)?)(?:\x1b\[[0-9;]*m)*'",
+ "$1",
+ );
+
+ // Also strip quotes around bracket placeholders like [PROJECT_ID]
+ settings.add_filter(
+ r"'(?:\x1b\[[0-9;]*m)*(\[[A-Z_]+\])(?:\x1b\[[0-9;]*m)*'",
"$1",
);
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_template_shell_escape.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_template_shell_escape.snap
index 689ebc6a9..7fceb40e6 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_template_shell_escape.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_template_shell_escape.snap
@@ -39,9 +39,9 @@ exit_code: 0
feat;id
----- stderr -----
-✓ Created branch feat;id from main and worktree @ _REPO_.feat;id
+✓ Created branch feat;id from main and worktree @ '_REPO_.feat;id'
↳ To customize worktree locations, run wt config create
▲ Cannot change directory — shell integration not installed
↳ To enable automatic cd, run wt config shell install
-◎ Executing (--execute) @ _REPO_.feat;id:
+◎ Executing (--execute) @ '_REPO_.feat;id':
  echo 'feat;id'