Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(switch): preserve subdirectory position when switching worktrees (#939)
Maximilian Roos114b5ebea64b
diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rsindex 76a26a03a..836c7a520 100644--- a/src/commands/handle_switch.rs+++ b/src/commands/handle_switch.rs@@ -103,7 +103,10 @@ pub fn handle_switch(// Show success message (temporal locality: immediately after worktree operation)// Returns path to display in hooks when user's shell won't be in the worktree// Also shows worktree-path hint on first --create (before shell integration warning)- let hooks_display_path = handle_switch_output(&result, &branch_info, change_dir)?;+ let cwd = std::env::current_dir().context("Failed to get current directory")?;+ let source_root = repo.current_worktree().root()?;+ let hooks_display_path =+ handle_switch_output(&result, &branch_info, change_dir, Some(&source_root), &cwd)?;// Offer shell integration if not already installed/active// (only shows prompt/hint when shell integration isn't working)diff --git a/src/commands/select/mod.rs b/src/commands/select/mod.rsindex a7afc668f..84e0ca0f7 100644--- a/src/commands/select/mod.rs+++ b/src/commands/select/mod.rs@@ -283,7 +283,9 @@ pub fn handle_select(// Show success message; emit cd directive if shell integration is active// Interactive picker always performs cd (change_dir: true)- handle_switch_output(&result, &branch_info, true)?;+ let cwd = std::env::current_dir().context("Failed to get current directory")?;+ let source_root = repo.current_worktree().root()?;+ handle_switch_output(&result, &branch_info, true, Some(&source_root), &cwd)?;}Ok(())diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 14051b9d7..d7721f8d6 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -284,6 +284,29 @@ fn print_switch_message_if_changed(Ok(())}+/// Compute the target directory for `cd` after switching, preserving the user's+/// subdirectory position when possible.+///+/// If the user is in `source_root/apps/gateway/` and `target_root/apps/gateway/`+/// exists, returns `target_root/apps/gateway/`. Otherwise returns `target_root`.+fn resolve_subdir_in_target(target_root: &Path, source_root: Option<&Path>, cwd: &Path) -> PathBuf {+ if let Some(source_root) = source_root {+ // Canonicalize both paths to handle symlinks (e.g., /var -> /private/var on macOS)+ let cwd = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf());+ let source_root =+ dunce::canonicalize(source_root).unwrap_or_else(|_| source_root.to_path_buf());+ if let Ok(relative) = cwd.strip_prefix(&source_root)+ && !relative.as_os_str().is_empty()+ {+ let candidate = target_root.join(relative);+ if candidate.is_dir() {+ return candidate;+ }+ }+ }+ target_root.to_path_buf()+}+/// Handle output for a switch operation////// # Shell Integration Warnings@@ -322,10 +345,15 @@ pub fn handle_switch_output(result: &SwitchResult,branch_info: &SwitchBranchInfo,change_dir: bool,+ source_worktree_root: Option<&Path>,+ cwd: &Path,) -> anyhow::Result<Option<std::path::PathBuf>> {- // Set target directory for command execution+ // Set target directory for command execution, preserving subdirectory position.+ // If the user is in apps/gateway/ in the source worktree and that directory exists+ // in the target, cd to apps/gateway/ in the target instead of the root.if change_dir {- super::change_directory(result.path())?;+ let cd_target = resolve_subdir_in_target(result.path(), source_worktree_root, cwd);+ super::change_directory(&cd_target)?;}let path = result.path();@@ -1246,6 +1274,51 @@ mod tests {}}+ #[test]+ fn test_resolve_subdir_in_target_no_source_root() {+ let target = PathBuf::from("/target/worktree");+ let cwd = PathBuf::from("/some/dir");+ assert_eq!(resolve_subdir_in_target(&target, None, &cwd), target);+ }++ #[test]+ fn test_resolve_subdir_in_target_subdir_exists() {+ let dir = tempfile::tempdir().unwrap();+ let source = dir.path().join("source");+ let target = dir.path().join("target");+ std::fs::create_dir_all(source.join("apps/gateway")).unwrap();+ std::fs::create_dir_all(target.join("apps/gateway")).unwrap();++ let cwd = source.join("apps/gateway");+ let result = resolve_subdir_in_target(&target, Some(&source), &cwd);+ assert_eq!(result, target.join("apps/gateway"));+ }++ #[test]+ fn test_resolve_subdir_in_target_subdir_missing() {+ let dir = tempfile::tempdir().unwrap();+ let source = dir.path().join("source");+ let target = dir.path().join("target");+ std::fs::create_dir_all(source.join("apps/gateway")).unwrap();+ std::fs::create_dir_all(&target).unwrap();++ let cwd = source.join("apps/gateway");+ let result = resolve_subdir_in_target(&target, Some(&source), &cwd);+ assert_eq!(result, target); // Falls back to root+ }++ #[test]+ fn test_resolve_subdir_in_target_at_root() {+ let dir = tempfile::tempdir().unwrap();+ let source = dir.path().join("source");+ let target = dir.path().join("target");+ std::fs::create_dir_all(&source).unwrap();+ std::fs::create_dir_all(&target).unwrap();++ let result = resolve_subdir_in_target(&target, Some(&source), &source);+ assert_eq!(result, target);+ }+#[test]fn test_shell_integration_hint() {let hint = shell_integration_hint();diff --git a/tests/integration_tests/directives.rs b/tests/integration_tests/directives.rsindex 176cc687a..e6e5201f0 100644--- a/tests/integration_tests/directives.rs+++ b/tests/integration_tests/directives.rs@@ -5,6 +5,7 @@ use crate::common::{use insta_cmd::assert_cmd_snapshot;use rstest::rstest;use std::fs;+use std::path::Path;// ============================================================================// Directive File Tests@@ -94,6 +95,119 @@ fn test_remove_directive_file(#[from(repo_with_remote)] mut repo: TestRepo) {});}+// ============================================================================+// Subdirectory Preservation Tests+// ============================================================================+// These tests verify that switching preserves the user's subdirectory position++#[rstest]+fn test_switch_preserves_subdir(#[from(repo_with_remote)] mut repo: TestRepo) {+ let feature_wt = repo.add_worktree("feature");+ let (directive_path, _guard) = directive_file();++ // Create the same subdirectory in both worktrees+ let subdir = "apps/gateway";+ fs::create_dir_all(repo.root_path().join(subdir)).unwrap();+ fs::create_dir_all(feature_wt.join(subdir)).unwrap();++ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ configure_directive_file(&mut cmd, &directive_path);+ cmd.arg("switch")+ .arg("feature")+ .current_dir(repo.root_path().join(subdir));++ let output = cmd.output().unwrap();+ assert!(output.status.success(), "wt switch failed: {:?}", output);++ // Verify directive file contains cd to the subdirectory, not the root.+ // Use Path::join for each component so separators are native on Windows.+ let directives = fs::read_to_string(&directive_path).unwrap_or_default();+ let expected_subdir = feature_wt.join(Path::new("apps").join("gateway"));+ let expected_str = expected_subdir.to_string_lossy();+ assert!(+ directives.contains(&*expected_str),+ "Directive should cd to subdirectory {}, got: {}",+ expected_str,+ directives+ );+}++#[rstest]+fn test_switch_falls_back_to_root_when_subdir_missing(+ #[from(repo_with_remote)] mut repo: TestRepo,+) {+ let feature_wt = repo.add_worktree("feature");+ let (directive_path, _guard) = directive_file();++ // Create subdirectory only in the source worktree, not in the target+ let subdir = "apps/gateway";+ fs::create_dir_all(repo.root_path().join(subdir)).unwrap();+ // Intentionally NOT creating the subdir in feature_wt++ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ configure_directive_file(&mut cmd, &directive_path);+ cmd.arg("switch")+ .arg("feature")+ .current_dir(repo.root_path().join(subdir));++ let output = cmd.output().unwrap();+ assert!(output.status.success(), "wt switch failed: {:?}", output);++ // Verify directive file contains cd to worktree root (not the missing subdir)+ let directives = fs::read_to_string(&directive_path).unwrap_or_default();+ let feature_str = feature_wt.to_string_lossy();+ assert!(+ directives.contains(&*feature_str),+ "Directive should cd to worktree root {}, got: {}",+ feature_str,+ directives+ );+ // Make sure it doesn't contain the subdir path.+ // Use Path::join for each component so separators are native on Windows.+ let subdir_path = feature_wt.join(Path::new("apps").join("gateway"));+ let subdir_str = subdir_path.to_string_lossy();+ assert!(+ !directives.contains(&*subdir_str),+ "Directive should NOT cd to missing subdirectory {}, got: {}",+ subdir_str,+ directives+ );+}++#[rstest]+fn test_switch_create_preserves_subdir(#[from(repo_with_remote)] repo: TestRepo) {+ let (directive_path, _guard) = directive_file();++ // Create a subdirectory in the source worktree and commit it so it appears in the new branch+ let subdir = "apps/gateway";+ fs::create_dir_all(repo.root_path().join(subdir)).unwrap();+ // Add a file so git tracks the directory+ fs::write(repo.root_path().join(subdir).join(".gitkeep"), "").unwrap();+ repo.commit("Add apps/gateway");++ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ configure_directive_file(&mut cmd, &directive_path);+ cmd.args(["switch", "--create", "new-feature"])+ .current_dir(repo.root_path().join(subdir));++ let output = cmd.output().unwrap();+ assert!(output.status.success(), "wt switch failed: {:?}", output);++ // The subdirectory was committed, so the new worktree should have it.+ // Use Path to construct the expected substring so separators match on Windows.+ let directives = fs::read_to_string(&directive_path).unwrap_or_default();+ let subdir_suffix = Path::new("apps").join("gateway");+ let subdir_str = subdir_suffix.to_string_lossy();+ assert!(+ directives.contains(&*subdir_str),+ "New worktree should cd to preserved subdirectory, got: {}",+ directives+ );+}+// ============================================================================// --no-cd Tests// ============================================================================