Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: use format_path_for_display() consistently for user-facing paths (#856)
Maximilian Roosb1ca0d22f332
diff --git a/.claude/skills/writing-user-outputs/SKILL.md b/.claude/skills/writing-user-outputs/SKILL.mdindex aa5aeec71..6fc390f9f 100644--- a/.claude/skills/writing-user-outputs/SKILL.md+++ b/.claude/skills/writing-user-outputs/SKILL.md@@ -874,6 +874,41 @@ Format for template expansion:Uses `log::debug!()` with structured format for deep debugging. Not intended forregular users.+## Path Formatting++**All user-facing paths must use `format_path_for_display()`** from+`worktrunk::path`. This function replaces home directory prefixes with `~` for+readability (e.g., `/Users/alex/projects/repo` → `~/projects/repo`).++```rust+use worktrunk::path::format_path_for_display;++// GOOD - uses format_path_for_display+crate::output::print(success_message(cformat!(+ "Created worktree at {}",+ format_path_for_display(&worktree_path)+)))?;++// GOOD - error messages too+.map_err(|e| format!("Failed to read {}: {}", format_path_for_display(path), e))?++// BAD - raw path.display()+crate::output::print(success_message(format!(+ "Created worktree at {}",+ worktree_path.display() // Shows /Users/alex/... instead of ~/...+)))?;+```++**Applies to:**+- Success/info/warning/error messages+- Hints suggesting paths+- Progress messages+- Dry-run previews++**Exceptions:**+- Debug logging (`log::debug!`) — full paths help debugging+- Paths passed to git commands — must be real paths+## Table Column Alignment- **Text columns** (Branch, Path): left-aligneddiff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rsindex 3fa16ec80..56f3c1a28 100644--- a/src/commands/configure_shell.rs+++ b/src/commands/configure_shell.rs@@ -480,7 +480,11 @@ fn configure_shell_file(// Create parent directories if they don't existif let Some(parent) = path.parent() {fs::create_dir_all(parent).map_err(|e| {- format!("Failed to create directory {}: {}", parent.display(), e)+ format!(+ "Failed to create directory {}: {}",+ format_path_for_display(parent),+ e+ )})?;}@@ -565,8 +569,12 @@ fn configure_fish_file(// Create parent directories if they don't existif let Some(parent) = path.parent() {- fs::create_dir_all(parent)- .map_err(|e| format!("Failed to create directory {}: {e}", parent.display()))?;+ fs::create_dir_all(parent).map_err(|e| {+ format!(+ "Failed to create directory {}: {e}",+ format_path_for_display(parent)+ )+ })?;}// Write the complete fish function file@@ -829,13 +837,21 @@ pub fn process_shell_completions(// Create parent directory if neededif let Some(parent) = completion_path.parent() {- fs::create_dir_all(parent)- .map_err(|e| format!("Failed to create directory {}: {e}", parent.display()))?;+ fs::create_dir_all(parent).map_err(|e| {+ format!(+ "Failed to create directory {}: {e}",+ format_path_for_display(parent)+ )+ })?;}// Write the completion file- fs::write(&completion_path, &fish_completion)- .map_err(|e| format!("Failed to write {}: {e}", completion_path.display()))?;+ fs::write(&completion_path, &fish_completion).map_err(|e| {+ format!(+ "Failed to write {}: {e}",+ format_path_for_display(&completion_path)+ )+ })?;results.push(CompletionResult {shell,@@ -959,7 +975,10 @@ fn scan_for_uninstall(});} else {fs::remove_file(&legacy_path).map_err(|e| {- format!("Failed to remove {}: {e}", legacy_path.display())+ format!(+ "Failed to remove {}: {e}",+ format_path_for_display(&legacy_path)+ )})?;results.push(UninstallResult {shell,@@ -1023,7 +1042,11 @@ fn scan_for_uninstall(});} else {fs::remove_file(&completion_path).map_err(|e| {- format!("Failed to remove {}: {}", completion_path.display(), e)+ format!(+ "Failed to remove {}: {}",+ format_path_for_display(&completion_path),+ e+ )})?;completion_results.push(CompletionUninstallResult {shell,diff --git a/src/commands/worktree/resolve.rs b/src/commands/worktree/resolve.rsindex 6517047ca..044d91ee2 100644--- a/src/commands/worktree/resolve.rs+++ b/src/commands/worktree/resolve.rs@@ -9,6 +9,7 @@ use dunce::canonicalize;use normalize_path::NormalizePath;use worktrunk::config::UserConfig;use worktrunk::git::{GitError, Repository, ResolvedWorktree};+use worktrunk::path::format_path_for_display;use super::types::OperationMode;@@ -91,12 +92,17 @@ pub fn compute_worktree_path(let repo_name = repo_root.file_name()- .ok_or_else(|| anyhow::anyhow!("Repository path has no filename: {}", repo_root.display()))?+ .ok_or_else(|| {+ anyhow::anyhow!(+ "Repository path has no filename: {}",+ format_path_for_display(repo_root)+ )+ })?.to_str().ok_or_else(|| {anyhow::anyhow!("Repository path contains invalid UTF-8: {}",- repo_root.display()+ format_path_for_display(repo_root))})?;@@ -233,9 +239,12 @@ pub(super) fn generate_backup_path(path: &std::path::Path,suffix: &str,) -> anyhow::Result<PathBuf> {- let file_name = path- .file_name()- .ok_or_else(|| anyhow::anyhow!("Cannot generate backup path for {}", path.display()))?;+ let file_name = path.file_name().ok_or_else(|| {+ anyhow::anyhow!(+ "Cannot generate backup path for {}",+ format_path_for_display(path)+ )+ })?;if path.extension().is_none() {// Path has no extension (e.g., /repo/feature)diff --git a/src/config/user.rs b/src/config/user.rsindex 715abfb31..7c29cc27f 100644--- a/src/config/user.rs+++ b/src/config/user.rs@@ -11,6 +11,7 @@ use schemars::JsonSchema;use serde::{Deserialize, Serialize};use super::HooksConfig;+use crate::path::format_path_for_display;/// Trait for merging configuration structs.///@@ -913,7 +914,7 @@ impl UserConfig {let content = std::fs::read_to_string(&path).map_err(|e| {ConfigError::Message(format!("Failed to read config file {}: {}",- path.display(),+ format_path_for_display(&path),e))})?;@@ -921,7 +922,7 @@ impl UserConfig {let disk_config: UserConfig = toml::from_str(&content).map_err(|e| {ConfigError::Message(format!("Failed to parse config file {}: {}",- path.display(),+ format_path_for_display(&path),e))})?;diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rsindex d4d635ca3..b446b83d1 100644--- a/src/git/repository/worktrees.rs+++ b/src/git/repository/worktrees.rs@@ -7,6 +7,7 @@ use dunce::canonicalize;use normalize_path::NormalizePath;use super::{GitError, Repository, ResolvedWorktree, WorktreeInfo};+use crate::path::format_path_for_display;impl Repository {/// List all worktrees for this repository.@@ -106,7 +107,10 @@ impl Repository {pub fn remove_worktree(&self, path: &std::path::Path, force: bool) -> anyhow::Result<()> {let path_str = path.to_str().ok_or_else(|| {anyhow::Error::from(GitError::Other {- message: format!("Worktree path contains invalid UTF-8: {}", path.display()),+ message: format!(+ "Worktree path contains invalid UTF-8: {}",+ format_path_for_display(path)+ ),})})?;let mut args = vec!["worktree", "remove"];diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex 589469851..3dcc39474 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -952,11 +952,17 @@ pub fn shell_command(////// Sets both Unix (`HOME`, `XDG_CONFIG_HOME`) and Windows (`USERPROFILE`) variables/// so the `home` crate can find the temp home directory on all platforms.+///+/// Canonicalizes the path on macOS to handle `/var` → `/private/var` symlinks.+/// This ensures `format_path_for_display()` can correctly convert paths to `~/...`.pub fn set_temp_home_env(cmd: &mut Command, home: &Path) {- cmd.env("HOME", home);+ // Canonicalize to resolve macOS symlinks (/var -> /private/var)+ // This ensures paths match when format_path_for_display() compares against HOME+ let home = canonicalize(home).unwrap_or_else(|_| home.to_path_buf());+ cmd.env("HOME", &home);cmd.env("XDG_CONFIG_HOME", home.join(".config"));// Windows: the `home` crate uses USERPROFILE for home_dir()- cmd.env("USERPROFILE", home);+ cmd.env("USERPROFILE", &home);// Windows: etcetera uses APPDATA for config_dir() (AppData\Roaming)// Map it to .config to match Unix XDG_CONFIG_HOME behaviorcmd.env("APPDATA", home.join(".config"));@@ -2606,7 +2612,8 @@ fn setup_snapshot_settings_for_paths_with_home(// On CI, HOME is a temp directory, so paths under HOME become ~/something.// This catches paths like ~/wrong-path that don't follow the repo naming convention.// MUST come AFTER specific ~/repo patterns so they match first.- settings.add_filter(r"~/[a-zA-Z0-9_-]+", "[PROJECT_ID]");+ // Uses _PARENT_ prefix (matching _REPO_ convention) and preserves directory name.+ settings.add_filter(r"~/([a-zA-Z0-9_-]+)", "_PARENT_/$1");// Strip quotes around [PROJECT_ID] after replacement.// On Windows, paths inside quotes get replaced but quotes remain: 'C:/...' -> '[PROJECT_ID]'@@ -2758,8 +2765,11 @@ pub fn setup_snapshot_settings_with_home(repo: &TestRepo, temp_home: &TempDir) -pub fn setup_home_snapshot_settings(temp_home: &TempDir) -> insta::Settings {let mut settings = insta::Settings::clone_current();settings.set_snapshot_path("../snapshots");+ // Canonicalize to match paths in output (macOS /var -> /private/var)+ let canonical_home =+ canonicalize(temp_home.path()).unwrap_or_else(|_| temp_home.path().to_path_buf());settings.add_filter(- ®ex::escape(&temp_home.path().to_string_lossy()),+ ®ex::escape(&canonical_home.to_string_lossy()),"[TEMP_HOME]",);settings.add_filter(r"\\", "/");diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rsindex 7a2d2f6bc..bdce3b177 100644--- a/tests/integration_tests/config_show.rs+++ b/tests/integration_tests/config_show.rs@@ -246,7 +246,11 @@ if command -v wt >/dev/null 2>&1; then eval "$(command wt config shell init zsh)repo.configure_wt_cmd(&mut cmd);// Keep PATH minimal so the probe zsh doesn't find a globally-installed `wt`.cmd.env("PATH", "/usr/bin:/bin");- cmd.env("ZDOTDIR", temp_home.path());+ cmd.env(+ "ZDOTDIR",+ crate::common::canonicalize(temp_home.path())+ .unwrap_or_else(|_| temp_home.path().to_path_buf()),+ );cmd.arg("config").arg("show").current_dir(repo.root_path());set_temp_home_env(&mut cmd, temp_home.path());@@ -290,7 +294,11 @@ if command -v wt >/dev/null 2>&1; then eval "$(command wt config shell init zsh)repo.configure_wt_cmd(&mut cmd);// Keep PATH minimal so the probe zsh doesn't find a globally-installed `wt`.cmd.env("PATH", "/usr/bin:/bin");- cmd.env("ZDOTDIR", temp_home.path());+ cmd.env(+ "ZDOTDIR",+ crate::common::canonicalize(temp_home.path())+ .unwrap_or_else(|_| temp_home.path().to_path_buf()),+ );cmd.arg("config").arg("show").current_dir(repo.root_path());set_temp_home_env(&mut cmd, temp_home.path());diff --git a/tests/integration_tests/configure_shell.rs b/tests/integration_tests/configure_shell.rsindex 627372f94..75764fe1a 100644--- a/tests/integration_tests/configure_shell.rs+++ b/tests/integration_tests/configure_shell.rs@@ -1055,7 +1055,8 @@ fn test_configure_shell_no_warning_when_compinit_enabled(repo: TestRepo, temp_horepo.configure_wt_cmd(&mut cmd);set_temp_home_env(&mut cmd, temp_home.path());cmd.env("SHELL", "/bin/zsh");- cmd.env("ZDOTDIR", temp_home.path()); // Point zsh to our test home for config+ // Canonicalize to handle macOS /var -> /private/var symlinks+ cmd.env("ZDOTDIR", crate::common::canonicalize(temp_home.path()).unwrap_or_else(|_| temp_home.path().to_path_buf()));cmd.env("WORKTRUNK_TEST_COMPINIT_CONFIGURED", "1"); // Bypass zsh subprocess check (unreliable on CI)cmd.arg("config").arg("shell")diff --git a/tests/integration_tests/hook_show.rs b/tests/integration_tests/hook_show.rsindex a56395912..43f950347 100644--- a/tests/integration_tests/hook_show.rs+++ b/tests/integration_tests/hook_show.rs@@ -183,7 +183,10 @@ fn test_hook_show_approval_status(repo: TestRepo, temp_home: TempDir) {let project_id_str = repo.project_id();// Create user config at XDG path with one approved command- let global_config_dir = temp_home.path().join(".config").join("worktrunk");+ // Use canonical path to handle macOS /var -> /private/var symlinks+ let canonical_home = crate::common::canonicalize(temp_home.path())+ .unwrap_or_else(|_| temp_home.path().to_path_buf());+ let global_config_dir = canonical_home.join(".config").join("worktrunk");fs::create_dir_all(&global_config_dir).unwrap();let config_path = global_config_dir.join("config.toml");fs::write(@@ -286,7 +289,10 @@ lint = "pre-commit run"let mut settings = setup_home_snapshot_settings(&temp_home);// Replace temp home path with ~ for stable snapshots (override the [TEMP_HOME] filter)- settings.add_filter(®ex::escape(&temp_home.path().to_string_lossy()), "~");+ // Canonicalize to handle macOS /var -> /private/var symlinks+ let canonical_home = crate::common::canonicalize(temp_home.path())+ .unwrap_or_else(|_| temp_home.path().to_path_buf());+ settings.add_filter(®ex::escape(&canonical_home.to_string_lossy()), "~");settings.bind(|| {let mut cmd = wt_command();cmd.arg("hook").arg("show").current_dir(temp_dir.path());diff --git a/tests/snapshots/integration__integration_tests__switch__switch_already_at_branch_worktree_mismatch.snap b/tests/snapshots/integration__integration_tests__switch__switch_already_at_branch_worktree_mismatch.snapindex 7c2a96805..239cea72f 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_already_at_branch_worktree_mismatch.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_already_at_branch_worktree_mismatch.snap@@ -36,5 +36,5 @@ exit_code: 0----- stderr -----[33m▲[39m [33mBranch-worktree mismatch; expected [1mfeature-already[22m @ [1m_REPO_.feature-already[22m [31m⚑[39m[39m-[2m○[22m Already on worktree for [1mfeature-already[22m @ [1m[PROJECT_ID][22m+[2m○[22m Already on worktree for [1mfeature-already[22m @ [1m_PARENT_/wrong-path-already[22m[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_branch_worktree_mismatch_no_shell.snap b/tests/snapshots/integration__integration_tests__switch__switch_branch_worktree_mismatch_no_shell.snapindex d56eea24f..5839ac915 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_branch_worktree_mismatch_no_shell.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_branch_worktree_mismatch_no_shell.snap@@ -36,5 +36,5 @@ exit_code: 0----- stderr -----[33m▲[39m [33mBranch-worktree mismatch; expected [1mfeature-mismatch[22m @ [1m_REPO_.feature-mismatch[22m [31m⚑[39m[39m-[33m▲[39m [33mWorktree for [1mfeature-mismatch[22m @ [1m[PROJECT_ID][22m, but cannot change directory — shell integration not installed[39m+[33m▲[39m [33mWorktree for [1mfeature-mismatch[22m @ [1m_PARENT_/wrong-path-no-shell[22m, but cannot change directory — shell integration not installed[39m[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_branch_worktree_mismatch_shows_hint.snap b/tests/snapshots/integration__integration_tests__switch__switch_branch_worktree_mismatch_shows_hint.snapindex 5298653d7..49091336e 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_branch_worktree_mismatch_shows_hint.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_branch_worktree_mismatch_shows_hint.snap@@ -37,4 +37,4 @@ exit_code: 0----- stderr -----[33m▲[39m [33mBranch-worktree mismatch; expected [1mfeature[22m @ [1m_REPO_.feature[22m [31m⚑[39m[39m-[2m○[22m Switched to worktree for [1mfeature[22m @ [1m[PROJECT_ID][22m+[2m○[22m Switched to worktree for [1mfeature[22m @ [1m_PARENT_/wrong-path[22m