Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Fix bugs found in adversarial code review (#849)
Maximilian Roos29a6cec4cbe5
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex 5babbee33..660e6b4c8 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -412,11 +412,12 @@ impl StashData {)));+ // Don't use --quiet so git shows conflicts if anylet success = Repository::current().ok().and_then(|repo| {repo.worktree_at(&self.path)- .run_command(&["stash", "pop", "--quiet", &self.stash_ref])+ .run_command(&["stash", "pop", &self.stash_ref]).ok()}).is_some();diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 1dd90e614..d8e67f445 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -283,6 +283,12 @@ pub fn handle_squash(eprintln!("{}", format_with_gutter(&formatted_message, None));// Reset to merge base (soft reset stages all changes, including any already-staged uncommitted changes)+ //+ // TOCTOU note: Between this reset and the commit below, an external process could+ // modify the staging area. This is extremely unlikely (requires precise timing) and+ // the consequence is minor (unexpected content in squash commit). The commit message+ // generated above accurately reflects the original commits being squashed, so any+ // discrepancy would be visible in the diff. Considered acceptable risk.repo.run_command(&["reset", "--soft", &merge_base]).context("Failed to reset to merge base")?;diff --git a/src/commands/worktree/resolve.rs b/src/commands/worktree/resolve.rsindex 4db63554e..6517047ca 100644--- a/src/commands/worktree/resolve.rs+++ b/src/commands/worktree/resolve.rs@@ -128,12 +128,55 @@ 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(super) fn paths_match(a: &std::path::Path, b: &std::path::Path) -> bool {- let a_canonical = canonicalize(a).unwrap_or_else(|_| a.to_path_buf());- let b_canonical = canonicalize(b).unwrap_or_else(|_| b.to_path_buf());+ let a_canonical = canonicalize_with_parents(a);+ let b_canonical = canonicalize_with_parents(b);a_canonical == b_canonical}@@ -291,4 +334,99 @@ mod tests {let path = PathBuf::from("..");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);+ }}diff --git a/src/config/deprecation.rs b/src/config/deprecation.rsindex f34c27e7a..f05c8d724 100644--- a/src/config/deprecation.rs+++ b/src/config/deprecation.rs@@ -474,10 +474,11 @@ pub fn check_and_migrate(}// Build the .new path: "config.toml" -> "config.toml.new"- let new_path = path.with_extension(format!(- "{}.new",- path.extension().unwrap_or_default().to_string_lossy()- ));+ // For files without extension: "config" -> "config.new" (not "config..new")+ let new_path = match path.extension() {+ Some(ext) => path.with_extension(format!("{}.new", ext.to_string_lossy())),+ None => path.with_extension("new"),+ };// Skip writing if: (a) this is a brief warning (not `wt config show`), AND// (b) migration file already exists@@ -1134,6 +1135,40 @@ approved-commands = [assert!(result2.unwrap().is_some());}+ #[test]+ fn test_migration_path_with_extension() {+ // config.toml -> config.toml.new+ let path = std::path::Path::new("/tmp/config.toml");+ let new_path = match path.extension() {+ Some(ext) => path.with_extension(format!("{}.new", ext.to_string_lossy())),+ None => path.with_extension("new"),+ };+ assert_eq!(new_path.to_str().unwrap(), "/tmp/config.toml.new");+ }++ #[test]+ fn test_migration_path_without_extension() {+ // config -> config.new (not config..new)+ let path = std::path::Path::new("/tmp/config");+ let new_path = match path.extension() {+ Some(ext) => path.with_extension(format!("{}.new", ext.to_string_lossy())),+ None => path.with_extension("new"),+ };+ assert_eq!(new_path.to_str().unwrap(), "/tmp/config.new");+ }++ #[test]+ fn test_migration_path_hidden_file() {+ // .hidden -> .hidden.new (not .hidden..new)+ // Note: .hidden has no extension (the dot is part of the filename)+ let path = std::path::Path::new("/tmp/.hidden");+ let new_path = match path.extension() {+ Some(ext) => path.with_extension(format!("{}.new", ext.to_string_lossy())),+ None => path.with_extension("new"),+ };+ assert_eq!(new_path.to_str().unwrap(), "/tmp/.hidden.new");+ }+// Tests for commit-generation section migration#[test]diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 9a666521f..1542baa29 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -224,6 +224,9 @@ impl Repository {}/// Resolve the git common directory for a path.+ ///+ /// Always returns a canonicalized absolute path to ensure consistent+ /// comparison with `WorkingTree::git_dir()`.fn resolve_git_common_dir(discovery_path: &Path) -> anyhow::Result<PathBuf> {let output = Cmd::new("git").args(["rev-parse", "--git-common-dir"])@@ -239,12 +242,13 @@ impl Repository {let stdout = String::from_utf8_lossy(&output.stdout);let path = PathBuf::from(stdout.trim());- if path.is_relative() {- canonicalize(discovery_path.join(&path))- .context("Failed to resolve git common directory")+ // Always canonicalize to resolve symlinks (e.g., /var -> /private/var on macOS)+ let absolute_path = if path.is_relative() {+ discovery_path.join(&path)} else {- Ok(path)- }+ path+ };+ canonicalize(&absolute_path).context("Failed to resolve git common directory")}/// Get the path this repository was discovered from.diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex 74af39325..1f7df4f30 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -92,28 +92,42 @@ impl<'a> WorkingTree<'a> {/// Get the branch checked out in this worktree, or None if in detached HEAD state.////// Result is cached in the repository's shared cache (keyed by worktree path).+ /// Errors (e.g., permission denied, corrupted `.git`) are propagated, not swallowed.pub fn branch(&self) -> anyhow::Result<Option<String>> {- Ok(self- .repo+ // Check cache first+ if let Some(cached) = self.repo.cache.current_branches.get(&self.path) {+ return Ok(cached.clone());+ }++ // Not cached - run git command and propagate errors+ let stdout = self+ .run_command(&["branch", "--show-current"])+ .context("Failed to determine current branch")?;++ let branch = stdout.trim();+ let result = if branch.is_empty() {+ None // Detached HEAD+ } else {+ Some(branch.to_string())+ };++ // Cache the successful result+ self.repo.cache.current_branches- .entry(self.path.clone())- .or_insert_with(|| {- self.run_command(&["branch", "--show-current"])- .ok()- .and_then(|s| {- let branch = s.trim();- if branch.is_empty() {- None // Detached HEAD- } else {- Some(branch.to_string())- }- })- })- .clone())+ .insert(self.path.clone(), result.clone());++ Ok(result)}/// Check if the working tree has uncommitted changes.+ ///+ /// Note: This does NOT detect files hidden via `git update-index --assume-unchanged`+ /// or `--skip-worktree`. We intentionally skip that check because:+ /// 1. Detecting hidden files requires `git ls-files -v` which lists ALL tracked files+ /// 2. On large repos (70k+ files), this adds noticeable latency to every clean check+ /// 3. Users who use skip-worktree are power users who understand the implications+ /// 4. A warning wouldn't prevent data loss anyway — it's informational onlypub fn is_dirty(&self) -> anyhow::Result<bool> {let stdout = self.run_command(&["status", "--porcelain"])?;Ok(!stdout.trim().is_empty())@@ -142,17 +156,19 @@ impl<'a> WorkingTree<'a> {/// Get the git directory (may be different from common-dir in worktrees).///- /// Always returns an absolute path, resolving any relative paths returned by git.+ /// Always returns a canonicalized absolute path, resolving symlinks.+ /// This ensures consistent comparison with `git_common_dir()`.pub fn git_dir(&self) -> anyhow::Result<PathBuf> {let stdout = self.run_command(&["rev-parse", "--git-dir"])?;let path = PathBuf::from(stdout.trim());- // Resolve relative paths against the worktree's directory- if path.is_relative() {- canonicalize(self.path.join(&path)).context("Failed to resolve git directory")+ // Always canonicalize to resolve symlinks (e.g., /var -> /private/var on macOS)+ let absolute_path = if path.is_relative() {+ self.path.join(&path)} else {- Ok(path)- }+ path+ };+ canonicalize(&absolute_path).context("Failed to resolve git directory")}/// Check if a rebase is in progress.@@ -203,6 +219,7 @@ impl<'a> WorkingTree<'a> {}.into());}+Ok(())}diff --git a/src/shell/detection.rs b/src/shell/detection.rsindex 9a34fddad..21be7a14d 100644--- a/src/shell/detection.rs+++ b/src/shell/detection.rs@@ -87,8 +87,8 @@ use super::paths::{home_dir_required, powershell_profile_paths};pub fn is_shell_integration_line(line: &str, cmd: &str) -> bool {let trimmed = line.trim();- // Skip comments (# for POSIX shells, <# #> for PowerShell)- if trimmed.starts_with('#') {+ // Skip comments (# for POSIX shells, <# #> for PowerShell block comments)+ if trimmed.starts_with('#') || trimmed.starts_with("<#") {return false;}@@ -142,10 +142,13 @@ fn has_init_pattern_with_prefix_check(line: &str, cmd: &str) -> bool {// Check what precedes the matchif is_valid_command_position(line, absolute_pos, &cmd_in_line) {- // Must be in an execution context+ // Must be in an execution context (eval, source, dot command, PowerShell, etc.)if line.contains("eval")|| line.contains("source")+ || line.contains(". <(") // POSIX dot command with process substitution+ || line.contains(". =(") // zsh dot command with =() substitution|| line.contains("Invoke-Expression")+ || line.contains("iex")|| line.contains("if "){return true;@@ -188,9 +191,9 @@ fn is_valid_command_position(line: &str, pos: usize, cmd: &str) -> bool {return false;}- // Valid if preceded by: whitespace, $(, (, ", ', or `command `+ // Valid if preceded by: whitespace, $(, (, ", ', `, or / (for absolute paths)let last_char = before.chars().last().unwrap();- matches!(last_char, ' ' | '\t' | '$' | '(' | '"' | '\'' | '`')+ matches!(last_char, ' ' | '\t' | '$' | '(' | '"' | '\'' | '`' | '/')}/// Check if a line contains the command name at a word boundary.@@ -638,25 +641,25 @@ mod tests {// FALSE NEGATIVE: dot (.) command as source equivalent// ------------------------------------------------------------------------- /// The `.` command is POSIX-equivalent to `source` but NOT detected+ /// The `.` command is POSIX-equivalent to `source` - now detected#[test]- fn test_fn_dot_command_process_substitution() {+ fn test_dot_command_process_substitution() {// . <(wt config shell init bash) is equivalent to source <(...)// This is a common POSIX pattern- assert_not_detects(+ assert_detects(". <(wt config shell init bash)","wt",- "CONFIRMED FALSE NEGATIVE: dot command with process substitution",+ "dot command with process substitution",);}#[test]- fn test_fn_dot_command_zsh_equals() {+ fn test_dot_command_zsh_equals() {// . =(wt config shell init zsh) is zsh-specific- assert_not_detects(+ assert_detects(". =(wt config shell init zsh)","wt",- "CONFIRMED FALSE NEGATIVE: dot command with zsh =() substitution",+ "dot command with zsh =() substitution",);}@@ -664,23 +667,23 @@ mod tests {// FALSE NEGATIVE: PowerShell iex alias// ------------------------------------------------------------------------- /// iex is PowerShell's alias for Invoke-Expression+ /// iex is PowerShell's alias for Invoke-Expression - now detected#[test]- fn test_fn_powershell_iex_alias() {+ fn test_powershell_iex_alias() {// Common in PowerShell profiles- assert_not_detects(+ assert_detects("iex (wt config shell init powershell)","wt",- "CONFIRMED FALSE NEGATIVE: PowerShell iex alias",+ "PowerShell iex alias",);}#[test]- fn test_fn_powershell_iex_with_ampersand() {- assert_not_detects(+ fn test_powershell_iex_with_ampersand() {+ assert_detects("iex (& wt config shell init powershell)","wt",- "CONFIRMED FALSE NEGATIVE: PowerShell iex with &",+ "PowerShell iex with &",);}@@ -690,28 +693,22 @@ mod tests {// ------------------------------------------------------------------------#[test]- fn test_fn_powershell_block_comment() {- // PowerShell block comments <# #> should NOT match- // But current code doesn't skip them+ fn test_powershell_block_comment() {+ // PowerShell block comments <# #> should NOT match - now correctly skippedlet line = "<# Invoke-Expression (wt config shell init powershell) #>";- let result = is_shell_integration_line(line, "wt");- // This DOES match (false positive) - documenting the behavior- assert!(- result,- "PowerShell block comment currently matches (false positive risk)"- );+ assert_not_detects(line, "wt", "PowerShell block comment should not match");}// ------------------------------------------------------------------------// FALSE NEGATIVE: zsh =() process substitution without source/eval// ------------------------------------------------------------------------- /// Zsh allows sourcing with just =() which creates a temp file+ /// Zsh allows sourcing with just =() which creates a temp file - now detected#[test]- fn test_fn_zsh_bare_equals_substitution() {+ fn test_zsh_bare_equals_substitution() {// Some zsh configs might use: . =(command)// Already covered above, but this is a variant- assert_not_detects(+ assert_detects(". =(command wt config shell init zsh)","wt","dot with command prefix",@@ -749,30 +746,30 @@ mod tests {// ------------------------------------------------------------------------#[test]- fn test_fn_absolute_path() {- // Path-prefixed binary invocation - NOT detected because '/' not in allowed chars- assert_not_detects(+ fn test_absolute_path() {+ // Path-prefixed binary invocation - now detected with '/' in allowed chars+ assert_detects(r#"eval "$(/usr/local/bin/wt config shell init bash)""#,"wt",- "CONFIRMED FALSE NEGATIVE: absolute path to binary",+ "absolute path to binary",);}#[test]- fn test_fn_home_path() {- assert_not_detects(+ fn test_home_path() {+ assert_detects(r#"eval "$(~/.cargo/bin/wt config shell init bash)""#,"wt",- "CONFIRMED FALSE NEGATIVE: home-relative path",+ "home-relative path",);}#[test]- fn test_fn_env_var_path() {- assert_not_detects(+ fn test_env_var_path() {+ assert_detects(r#"eval "$($HOME/.cargo/bin/wt config shell init bash)""#,"wt",- "CONFIRMED FALSE NEGATIVE: env var in path",+ "env var in path",);}diff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rsindex 0ed3a7f52..091a2b562 100644--- a/tests/integration_tests/repository.rs+++ b/tests/integration_tests/repository.rs@@ -649,9 +649,117 @@ fn test_repo_path_in_submodule() {// Also verify that git_common_dir is in the parent's .git/modules/ (confirming this is a real submodule)let git_common_dir = repository.git_common_dir();+ // Use components() to check path structure (works on both Unix and Windows)+ let components: Vec<_> = git_common_dir.components().collect();+ let has_git_modules = components.windows(2).any(|pair| {+ matches!(+ (pair[0].as_os_str().to_str(), pair[1].as_os_str().to_str()),+ (Some(".git"), Some("modules"))+ )+ });assert!(- git_common_dir.to_string_lossy().contains(".git/modules"),+ has_git_modules,"git_common_dir should be in parent's .git/modules/ for a submodule, got: {:?}",git_common_dir);}++// =============================================================================+// branch() error propagation tests (Bug fix: branch() swallows errors)+// =============================================================================++#[test]+fn test_branch_returns_none_for_detached_head() {+ let repo = TestRepo::new();+ let root = repo.root_path().to_path_buf();++ // Detach HEAD by checking out a specific commit+ let sha = repo.git_output(&["rev-parse", "HEAD"]);++ repo.run_git(&["checkout", "--detach", &sha]);++ // Create a fresh repository instance to avoid cached result+ let repository = Repository::at(&root).unwrap();+ // Use worktree_at with explicit path, not current_worktree() which uses base_path()+ let wt = repository.worktree_at(&root);++ let result = wt.branch();+ assert!(+ result.is_ok(),+ "branch() should succeed even for detached HEAD"+ );+ assert!(+ result.unwrap().is_none(),+ "branch() should return None for detached HEAD"+ );+}++#[test]+fn test_branch_returns_branch_name() {+ let repo = TestRepo::new();+ let root = repo.root_path().to_path_buf();+ let repository = Repository::at(&root).unwrap();+ // Use worktree_at with explicit path, not current_worktree() which uses base_path()+ let wt = repository.worktree_at(&root);++ let result = wt.branch();+ assert!(result.is_ok(), "branch() should succeed");+ assert_eq!(+ result.unwrap(),+ Some("main".to_string()),+ "branch() should return the current branch name"+ );+}++#[test]+fn test_branch_caches_result() {+ let repo = TestRepo::new();+ let root = repo.root_path().to_path_buf();+ let repository = Repository::at(&root).unwrap();+ // Use worktree_at with explicit path, not current_worktree() which uses base_path()+ let wt = repository.worktree_at(&root);++ // First call+ let result1 = wt.branch().unwrap();+ // Second call should return cached result+ let result2 = wt.branch().unwrap();++ assert_eq!(result1, result2);+ assert_eq!(result1, Some("main".to_string()));+}++// =============================================================================+// is_dirty() behavior tests+// =============================================================================++#[test]+fn test_is_dirty_does_not_detect_skip_worktree_changes() {+ // This test documents a known limitation: is_dirty() uses `git status --porcelain`+ // which doesn't show files hidden via --skip-worktree or --assume-unchanged.+ //+ // We intentionally don't check for these because:+ // 1. Detecting them requires `git ls-files -v` which lists ALL tracked files+ // 2. On large repos (70k+ files), this adds noticeable latency to every clean check+ // 3. Users who use skip-worktree are power users who understand the implications+ let repo = TestRepo::new();+ let root = repo.root_path().to_path_buf();++ // Create and commit a file+ let file_path = root.join("local.env");+ fs::write(&file_path, "original").unwrap();+ repo.run_git(&["add", "local.env"]);+ repo.run_git(&["commit", "-m", "add local.env"]);++ // Mark with skip-worktree and modify+ repo.run_git(&["update-index", "--skip-worktree", "local.env"]);+ fs::write(&file_path, "modified but hidden").unwrap();++ let repository = Repository::at(&root).unwrap();+ let wt = repository.worktree_at(&root);++ // is_dirty() returns false — this is documented behavior, not a bug+ assert!(+ !wt.is_dirty().unwrap(),+ "is_dirty() does not detect skip-worktree changes by design"+ );+}