Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(switch): resolve symlinked paths to existing worktrees (#2466)
Worktrunk Bota8f1d4904609
diff --git a/src/commands/relocate.rs b/src/commands/relocate.rsindex 6daf4605b..252607db8 100644--- a/src/commands/relocate.rs+++ b/src/commands/relocate.rs@@ -27,14 +27,14 @@ use anyhow::Context;use color_print::cformat;use worktrunk::config::UserConfig;use worktrunk::git::{Repository, WorktreeInfo};-use worktrunk::path::format_path_for_display;+use worktrunk::path::{format_path_for_display, paths_match};use worktrunk::styling::{eprintln, format_with_gutter, hint_message, info_message, progress_message, success_message,warning_message,};use super::commit::{CommitGenerator, StageMode};-use super::worktree::{compute_worktree_path, paths_match};+use super::worktree::compute_worktree_path;// ============================================================================// Types representing each stage of the pipelinediff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rsindex aaaf6222e..bf62c1f0e 100644--- a/src/commands/worktree/mod.rs+++ b/src/commands/worktree/mod.rs@@ -89,7 +89,6 @@ mod types;// Re-export public types and functionspub use push::{PushKind, handle_no_ff_merge, handle_push};-pub(crate) use resolve::paths_match;pub use resolve::{compute_worktree_path, is_worktree_at_expected_path, offer_bare_repo_worktree_path_fix,path_mismatch, resolve_worktree_arg, worktree_display_name,diff --git a/src/commands/worktree/resolve.rs b/src/commands/worktree/resolve.rsindex d2d66b343..1b4ca127a 100644--- a/src/commands/worktree/resolve.rs+++ b/src/commands/worktree/resolve.rs@@ -7,11 +7,10 @@ use std::path::{Path, PathBuf};use anyhow::Context;use color_print::cformat;-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 worktrunk::path::{format_path_for_display, paths_match};use worktrunk::styling::{eprintln, format_toml, hint_message, info_message, success_message, warning_message,};@@ -160,58 +159,6 @@ pub fn is_worktree_at_expected_path(}}-/// Canonicalize a path, resolving parent symlinks even if the path doesn't exist.-///-/// For existing paths, uses standard canonicalization.-/// For non-existent paths, canonicalizes the longest existing prefix and appends-/// the remaining components. This handles macOS `/var` -> `/private/var` symlinks-/// correctly for computed worktree paths that don't exist yet.-fn canonicalize_with_parents(path: &Path) -> PathBuf {- // Try direct canonicalization first- if let Ok(canonical) = canonicalize(path) {- return canonical;- }-- // Path doesn't exist - find the longest existing prefix and canonicalize that- let mut existing_prefix = path.to_path_buf();- let mut suffix_components = Vec::new();-- // Walk up until we find an existing path- while !existing_prefix.exists() {- if let Some(file_name) = existing_prefix.file_name() {- suffix_components.push(file_name.to_os_string());- if let Some(parent) = existing_prefix.parent() {- existing_prefix = parent.to_path_buf();- } else {- // Reached filesystem root without finding existing path- return path.to_path_buf();- }- } else {- // No more components to strip- return path.to_path_buf();- }- }-- // Canonicalize the existing prefix and append the non-existent components- let canonical_prefix = canonicalize(&existing_prefix).unwrap_or(existing_prefix);- let mut result = canonical_prefix;- for component in suffix_components.into_iter().rev() {- result.push(component);- }- result-}--/// Compare two paths for equality, canonicalizing to handle symlinks and relative paths.-///-/// Returns `true` if the paths resolve to the same location.-/// Handles the case where one path exists and the other doesn't by resolving-/// parent directory symlinks for non-existent paths.-pub(crate) fn paths_match(a: &std::path::Path, b: &std::path::Path) -> bool {- let a_canonical = canonicalize_with_parents(a);- let b_canonical = canonicalize_with_parents(b);- a_canonical == b_canonical-}-/// Returns the expected path if `actual_path` differs from the template-computed path.////// Returns `Some(expected_path)` when there's a mismatch, `None` when paths match.@@ -519,101 +466,6 @@ mod tests {assert!(generate_backup_path(&path, "20250101-000000").is_err());}- #[test]- fn test_paths_match_identical() {- let path = PathBuf::from("/tmp/test");- assert!(paths_match(&path, &path));- }-- #[test]- fn test_paths_match_different() {- let a = PathBuf::from("/tmp/foo");- let b = PathBuf::from("/tmp/bar");- assert!(!paths_match(&a, &b));- }-- #[test]- fn test_canonicalize_with_parents_existing_path() {- // Existing paths should be canonicalized normally- let tmp = std::env::temp_dir();- let canonical = canonicalize_with_parents(&tmp);- // Should resolve to the actual canonical path- assert!(canonical.is_absolute());- }-- #[test]- fn test_canonicalize_with_parents_nonexistent() {- // Non-existent path under existing parent should resolve parent symlinks- let tmp = std::env::temp_dir();- let nonexistent = tmp.join("nonexistent-test-dir-12345");- let canonical = canonicalize_with_parents(&nonexistent);-- // The parent (/tmp or similar) should be canonicalized- // On macOS, /tmp -> /private/tmp, so the result should contain "private" if on macOS- assert!(canonical.is_absolute());-- // The non-existent component should still be at the end- assert_eq!(- canonical.file_name().unwrap().to_str().unwrap(),- "nonexistent-test-dir-12345"- );- }-- #[test]- #[cfg(target_os = "macos")]- fn test_paths_match_macos_var_symlink() {- // On macOS, /var is a symlink to /private/var- // This test verifies the fix for symlink resolution with non-existent paths-- // Create a temp directory under /var/tmp (which is /private/var/tmp)- let test_dir = PathBuf::from("/var/tmp/wt-test-paths-match");-- // Clean up existing test state and create fresh- let _ = std::fs::remove_dir_all(&test_dir);- std::fs::create_dir_all(&test_dir).expect("Failed to create test dir");-- // Test: non-existent path via /private/var vs non-existent path via /var- let private_path = PathBuf::from("/private/var/tmp/wt-test-paths-match/subdir");- let var_path = PathBuf::from("/var/tmp/wt-test-paths-match/subdir");-- // Neither subdir exists, but parent does- // paths_match should return true because both resolve to same location- assert!(- paths_match(&private_path, &var_path),- "Paths should match: {:?} vs {:?}",- canonicalize_with_parents(&private_path),- canonicalize_with_parents(&var_path)- );-- // Clean up- let _ = std::fs::remove_dir_all(&test_dir);- }-- #[test]- fn test_paths_match_existing_vs_nonexistent() {- // When one path exists and the other doesn't, parent symlinks should be resolved- let tmp = std::env::temp_dir();-- // Create an existing directory- let existing = tmp.join("wt-test-existing");- std::fs::create_dir_all(&existing).expect("Failed to create test dir");-- // Non-existent sibling- let nonexistent = tmp.join("wt-test-nonexistent");- let _ = std::fs::remove_dir_all(&nonexistent);-- // These should NOT match (different paths)- assert!(!paths_match(&existing, &nonexistent));-- // But same path with different representations should match- // (this tests that we're correctly canonicalizing even when one side doesn't exist)- let canonical = canonicalize_with_parents(&existing);- assert!(paths_match(&existing, &canonical));-- // Clean up- let _ = std::fs::remove_dir_all(&existing);- }-#[test]fn test_template_references_repo_name_default() {// Default template uses {{ repo }}diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rsindex 1b367c0ae..792cee7f4 100644--- a/src/git/repository/tests.rs+++ b/src/git/repository/tests.rs@@ -706,3 +706,27 @@ fn commit_details_many_deduplicates_repeated_sha() {assert_eq!(result.len(), 1);assert_eq!(result[&sha].1, "only commit");}++#[test]+#[cfg(unix)]+fn worktree_at_path_resolves_symlinked_path() {+ // Reproduction for issue #2460: `wt switch` fails to resolve existing+ // worktrees through symlink paths because `worktree_at_path` compares+ // paths lexically and misses symlink-equivalent spellings.+ use crate::testing::TestRepo;++ let mut test = TestRepo::with_initial_commit();+ let worktree_path = test.add_worktree("feature");++ let parent = worktree_path.parent().unwrap();+ let symlink_path = parent.join("feature-link");+ std::os::unix::fs::symlink(&worktree_path, &symlink_path).unwrap();++ let resolved = test.repo.worktree_at_path(&symlink_path).unwrap();+ assert!(+ resolved.is_some(),+ "worktree_at_path should resolve a symlinked path to its target worktree, got None for {symlink_path:?} -> {worktree_path:?}"+ );+ let (_, branch) = resolved.unwrap();+ assert_eq!(branch.as_deref(), Some("feature"));+}diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rsindex b1e1d1027..e30f76878 100644--- a/src/git/repository/worktrees.rs+++ b/src/git/repository/worktrees.rs@@ -4,10 +4,9 @@ use std::path::{Path, PathBuf};use color_print::cformat;use dunce::canonicalize;-use normalize_path::NormalizePath;use super::{GitError, Repository, ResolvedWorktree, WorktreeInfo};-use crate::path::format_path_for_display;+use crate::path::{format_path_for_display, paths_match};impl Repository {/// List all worktrees for this repository.@@ -90,17 +89,18 @@ impl Repository {////// Returns `Some((path, branch))` if a worktree exists at the path,/// where `branch` is `None` for detached HEAD worktrees.+ ///+ /// Uses symlink-aware comparison so a path that resolves to a worktree+ /// through one or more symlinks still matches the worktree's recorded path.pub fn worktree_at_path(&self,path: &Path,) -> anyhow::Result<Option<(PathBuf, Option<String>)>> {let worktrees = self.list_worktrees()?;- // Use lexical normalization so comparison works even when path doesn't exist- let normalized_path = path.normalize();Ok(worktrees.iter()- .find(|wt| wt.path.normalize() == normalized_path)+ .find(|wt| paths_match(&wt.path, path)).map(|wt| (wt.path.clone(), wt.branch.clone())))}diff --git a/src/path.rs b/src/path.rsindex 9417af36b..dff78053c 100644--- a/src/path.rs+++ b/src/path.rs@@ -1,15 +1,14 @@+use dunce::canonicalize;use path_slash::PathExt as _;use shell_escape::unix::escape;use std::borrow::Cow;-use std::path::Path;+use std::path::{Path, PathBuf};use sanitize_filename::{Options as SanitizeOptions, sanitize_with_options};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.///@@ -137,6 +136,47 @@ pub fn format_path_for_display(path: &Path) -> String {}}+/// Canonicalize a path, resolving parent symlinks even if the path doesn't exist.+///+/// For existing paths, uses standard canonicalization.+/// For non-existent paths, canonicalizes the longest existing prefix and appends+/// the remaining components. This handles macOS `/var` -> `/private/var` symlinks+/// correctly for computed worktree paths that don't exist yet.+fn canonicalize_with_parents(path: &Path) -> PathBuf {+ if let Ok(canonical) = canonicalize(path) {+ return canonical;+ }++ let mut existing_prefix = path.to_path_buf();+ let mut suffix_components = Vec::new();++ while !existing_prefix.exists() {+ let (Some(file_name), Some(parent)) =+ (existing_prefix.file_name(), existing_prefix.parent())+ else {+ return path.to_path_buf();+ };+ suffix_components.push(file_name.to_os_string());+ existing_prefix = parent.to_path_buf();+ }++ let canonical_prefix = canonicalize(&existing_prefix).unwrap_or(existing_prefix);+ let mut result = canonical_prefix;+ for component in suffix_components.into_iter().rev() {+ result.push(component);+ }+ result+}++/// Compare two paths for equality, canonicalizing to handle symlinks and relative paths.+///+/// Returns `true` if the paths resolve to the same location.+/// Handles the case where one path exists and the other doesn't by resolving+/// parent directory symlinks for non-existent paths.+pub fn paths_match(a: &Path, b: &Path) -> bool {+ canonicalize_with_parents(a) == canonicalize_with_parents(b)+}+/// Sanitize a string for use as a filename on all platforms.////// Uses `sanitize-filename` crate to handle invalid characters, control characters,@@ -177,7 +217,10 @@ pub fn sanitize_for_filename(value: &str) -> String {mod tests {use std::path::PathBuf;- use super::{format_path_for_display, home_dir, sanitize_for_filename, to_posix_path};+ use super::{+ canonicalize_with_parents, format_path_for_display, home_dir, paths_match,+ sanitize_for_filename, to_posix_path,+ };#[test]fn shortens_path_under_home() {@@ -402,4 +445,84 @@ mod tests {$HOME => ~");}++ #[test]+ fn test_paths_match_identical() {+ let path = PathBuf::from("/tmp/test");+ assert!(paths_match(&path, &path));+ }++ #[test]+ fn test_paths_match_different() {+ let a = PathBuf::from("/tmp/foo");+ let b = PathBuf::from("/tmp/bar");+ assert!(!paths_match(&a, &b));+ }++ #[test]+ fn test_canonicalize_with_parents_existing_path() {+ let tmp = std::env::temp_dir();+ let canonical = canonicalize_with_parents(&tmp);+ assert!(canonical.is_absolute());+ }++ #[test]+ fn test_canonicalize_with_parents_degenerate() {+ // Empty path can't be decomposed (no file_name) — falls through to returning as-is.+ let canonical = canonicalize_with_parents(std::path::Path::new(""));+ assert_eq!(canonical, PathBuf::from(""));+ }++ #[test]+ fn test_canonicalize_with_parents_nonexistent() {+ let tmp = std::env::temp_dir();+ let nonexistent = tmp.join("nonexistent-test-dir-12345");+ let canonical = canonicalize_with_parents(&nonexistent);++ assert!(canonical.is_absolute());+ assert_eq!(+ canonical.file_name().unwrap().to_str().unwrap(),+ "nonexistent-test-dir-12345"+ );+ }++ #[test]+ #[cfg(target_os = "macos")]+ fn test_paths_match_macos_var_symlink() {+ // On macOS, /var is a symlink to /private/var+ let test_dir = PathBuf::from("/var/tmp/wt-test-paths-match");++ let _ = std::fs::remove_dir_all(&test_dir);+ std::fs::create_dir_all(&test_dir).expect("Failed to create test dir");++ let private_path = PathBuf::from("/private/var/tmp/wt-test-paths-match/subdir");+ let var_path = PathBuf::from("/var/tmp/wt-test-paths-match/subdir");++ assert!(+ paths_match(&private_path, &var_path),+ "Paths should match: {:?} vs {:?}",+ canonicalize_with_parents(&private_path),+ canonicalize_with_parents(&var_path)+ );++ let _ = std::fs::remove_dir_all(&test_dir);+ }++ #[test]+ fn test_paths_match_existing_vs_nonexistent() {+ let tmp = std::env::temp_dir();++ let existing = tmp.join("wt-test-existing");+ std::fs::create_dir_all(&existing).expect("Failed to create test dir");++ let nonexistent = tmp.join("wt-test-nonexistent");+ let _ = std::fs::remove_dir_all(&nonexistent);++ assert!(!paths_match(&existing, &nonexistent));++ let canonical = canonicalize_with_parents(&existing);+ assert!(paths_match(&existing, &canonical));++ let _ = std::fs::remove_dir_all(&existing);+ }}diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 38616ea7b..94053a59a 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -1101,6 +1101,29 @@ fn test_switch_detached_worktree_by_path(mut repo: TestRepo) {);}+/// Switch via a symlink that resolves to an existing worktree (#2460).+#[cfg(unix)]+#[rstest]+fn test_switch_worktree_by_symlinked_path(mut repo: TestRepo) {+ let worktree_path = repo.add_worktree("feature-symlinked");++ let symlink_path = worktree_path.parent().unwrap().join("worktree-link");+ std::os::unix::fs::symlink(&worktree_path, &symlink_path).unwrap();++ let symlink_str = symlink_path.to_string_lossy().to_string();+ let output = repo+ .wt_command()+ .args(["switch", &symlink_str])+ .output()+ .unwrap();++ assert!(+ output.status.success(),+ "wt switch via symlink should succeed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+}+/// Switch to a detached worktree by relative path (#1661)./// Relative paths with directory separators (e.g., "../repo.feature") are resolved against CWD.#[rstest]