Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(relocate): move the shell with its worktree through a swap, and not out of a nested worktree (#4325)
Worktrunk Botccacf2135033
diff --git a/src/commands/relocate.rs b/src/commands/relocate.rsindex b84c253e7..5c1dfb699 100644--- a/src/commands/relocate.rs+++ b/src/commands/relocate.rs@@ -83,6 +83,13 @@ struct TempRelocation {original_path: PathBuf,}+/// Where the user's shell stands: its cwd and the pending worktree holding it.+#[derive(Clone, Copy)]+struct ShellPosition<'a> {+ cwd: &'a Path,+ index: usize,+}+/// A worktree that was successfully relocated.pub struct RelocatedEntry {pub branch: String,@@ -475,6 +482,11 @@ impl<'a> RelocationExecutor<'a> {/// Execute all relocations in dependency order.pub fn execute(&mut self, default_branch: &str, cwd: Option<&Path>) -> anyhow::Result<()> {+ let shell = cwd+ .map(|cwd| self.shell_position(cwd))+ .transpose()?+ .flatten();+// Process until all pending are moved or in temploop {let mut made_progress = false;@@ -487,7 +499,7 @@ impl<'a> RelocationExecutor<'a> {match self.is_target_empty(i) {Some(true) => {- self.move_worktree(i, default_branch, cwd)?;+ self.move_worktree(i, default_branch, shell)?;made_progress = true;}Some(false) => {@@ -542,7 +554,7 @@ impl<'a> RelocationExecutor<'a> {}// Move temp-relocated worktrees to final destinations- self.finalize_temp_relocations()?;+ self.finalize_temp_relocations(shell)?;// Clean up temp directory if emptyif self.temp_dir.exists() {@@ -552,6 +564,25 @@ impl<'a> RelocationExecutor<'a> {Ok(())}+ /// Find the pending worktree the user's shell stands in, if any.+ ///+ /// The owner is the worktree whose path is the longest prefix of `cwd`, so+ /// a shell inside a worktree nested under another (the+ /// `.worktrees/{{ branch }}` layout nests every linked worktree under the+ /// main one) belongs to the inner worktree, not the outer.+ fn shell_position<'c>(&self, cwd: &'c Path) -> anyhow::Result<Option<ShellPosition<'c>>> {+ let owner = self+ .repo+ .list_worktrees()?+ .iter()+ .map(|wt| wt.path.as_path())+ .filter(|path| cwd.starts_with(path))+ .max_by_key(|path| path.components().count());+ Ok(owner+ .and_then(|owner| self.pending.iter().position(|c| c.wt.path == owner))+ .map(|index| ShellPosition { cwd, index }))+ }+/// Check if target path is empty (not occupied by a pending worktree).////// Returns:@@ -601,7 +632,7 @@ impl<'a> RelocationExecutor<'a> {&mut self,idx: usize,default_branch: &str,- cwd: Option<&Path>,+ shell: Option<ShellPosition<'_>>,) -> anyhow::Result<()> {// Extract data we need before any mutable borrowslet branch = self.pending[idx].branch().to_string();@@ -626,26 +657,7 @@ impl<'a> RelocationExecutor<'a> {let msg = cformat!("Relocated <bold>{branch}</>: {src_display} → {dest_display}");eprintln!("{}", success_message(msg));- // Update shell if user is inside this worktree, preserving their- // subdirectory position via the same helper as `switch`/`remove` so- // every path-switching command behaves identically.- if let Some(cwd_path) = cwd- && cwd_path.starts_with(&src_path)- {- let cd_target = crate::output::handlers::resolve_subdir_in_target(- &dest_path,- Some(&src_path),- cwd_path,- );- crate::output::change_directory(cd_target)?;- if crate::output::retired_shell_wrapper_active() {- eprintln!(- "{}",- warning_message("Cannot change directory — shell wrapper is out of date")- );- crate::output::print_outdated_shell_wrapper_hint_once();- }- }+ follow_shell(shell, idx, &src_path, &dest_path)?;self.moved.insert(idx);self.relocated_entries.push(RelocatedEntry {@@ -745,7 +757,10 @@ impl<'a> RelocationExecutor<'a> {}/// Move worktrees from temp locations to their final destinations.- fn finalize_temp_relocations(&mut self) -> anyhow::Result<()> {+ fn finalize_temp_relocations(+ &mut self,+ shell: Option<ShellPosition<'_>>,+ ) -> anyhow::Result<()> {for temp in std::mem::take(&mut self.temp_relocated) {let candidate = &self.pending[temp.index];let branch = candidate.branch();@@ -763,6 +778,9 @@ impl<'a> RelocationExecutor<'a> {let msg = cformat!("Relocated <bold>{branch}</>: {src_display} → {dest_display}");eprintln!("{}", success_message(msg));+ let (from, to) = (&temp.original_path, &candidate.expected_path);+ follow_shell(shell, temp.index, from, to)?;+self.relocated_entries.push(RelocatedEntry {branch: branch.to_string(),from: temp.original_path,@@ -774,6 +792,32 @@ impl<'a> RelocationExecutor<'a> {}}+/// Send the shell to the worktree's new path if it stood in the worktree that+/// just moved from `src_path` to `dest_path`, preserving its subdirectory+/// position via the same helper as `switch`/`remove` so every path-switching+/// command behaves identically.+fn follow_shell(+ shell: Option<ShellPosition<'_>>,+ index: usize,+ src_path: &Path,+ dest_path: &Path,+) -> anyhow::Result<()> {+ let Some(shell) = shell.filter(|shell| shell.index == index) else {+ return Ok(());+ };+ let cd_target =+ crate::output::handlers::resolve_subdir_in_target(dest_path, Some(src_path), shell.cwd);+ crate::output::change_directory(cd_target)?;+ if crate::output::retired_shell_wrapper_active() {+ eprintln!(+ "{}",+ warning_message("Cannot change directory — shell wrapper is out of date")+ );+ crate::output::print_outdated_shell_wrapper_hint_once();+ }+ Ok(())+}+// ============================================================================// Display helpers// ============================================================================diff --git a/tests/integration_tests/step_relocate.rs b/tests/integration_tests/step_relocate.rsindex 63fe27b24..638fc3057 100644--- a/tests/integration_tests/step_relocate.rs+++ b/tests/integration_tests/step_relocate.rs@@ -1641,3 +1641,103 @@ fn step_relocate_rejects_prunable_worktree(mut repo: TestRepo) {"expected a prunable-worktree error, got: {stderr}");}++/// A swap moves one worktree through a temporary location. The shell of a user+/// standing in either worktree must follow its branch to the new path, whichever+/// of the two takes the temporary route.+///+/// Ignored on Windows for the same reason as `test_relocate_preserves_subdir`.+#[rstest]+#[case::in_alpha("alpha")]+#[case::in_beta("beta")]+#[cfg_attr(windows, ignore)]+fn test_relocate_swap_moves_shell_with_its_branch(repo: TestRepo, #[case] standing_in: &str) {+ let parent = worktree_parent(&repo);+ let (cd_path, _guard) = directive_file();++ // alpha sits at beta's expected path and beta at alpha's.+ let path_for_beta = parent.join("repo.beta");+ let path_for_alpha = parent.join("repo.alpha");+ repo.run_git(&[+ "worktree",+ "add",+ "-b",+ "alpha",+ path_for_beta.to_str().unwrap(),+ ]);+ repo.run_git(&[+ "worktree",+ "add",+ "-b",+ "beta",+ path_for_alpha.to_str().unwrap(),+ ]);++ let (cwd, expected) = if standing_in == "alpha" {+ (&path_for_beta, &path_for_alpha)+ } else {+ (&path_for_alpha, &path_for_beta)+ };++ let mut cmd = repo.wt_command();+ configure_directive_file(&mut cmd, &cd_path);+ cmd.args(["step", "relocate"]).current_dir(cwd);+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "wt step relocate failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ let cd_content = fs::read_to_string(&cd_path).unwrap_or_default();+ assert_eq!(+ cd_content.trim(),+ expected.to_string_lossy(),+ "the shell should follow {standing_in} to its new path"+ );+}++/// Relocating the main worktree's branch must not move a shell that stands in a+/// different worktree nested inside the main one, as the+/// `.worktrees/{{ branch | sanitize }}` layout produces.+#[rstest]+fn test_relocate_main_leaves_shell_in_nested_worktree(repo: TestRepo) {+ let root = repo.root_path().to_path_buf();+ let (cd_path, _guard) = directive_file();+ fs::write(+ repo.test_config_path(),+ "worktree-path = \".worktrees/{{ branch | sanitize }}\"\n",+ )+ .unwrap();+ fs::write(root.join(".git/info/exclude"), ".worktrees\n").unwrap();++ // `other` is already at its expected nested path; the main worktree is on+ // `feature`, so relocate moves `feature` out to `.worktrees/feature`.+ let other_path = root.join(".worktrees").join("other");+ repo.run_git(&[+ "worktree",+ "add",+ "-b",+ "other",+ other_path.to_str().unwrap(),+ ]);+ repo.run_git(&["checkout", "-b", "feature"]);++ let mut cmd = repo.wt_command();+ configure_directive_file(&mut cmd, &cd_path);+ cmd.args(["step", "relocate"]).current_dir(&other_path);+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "wt step relocate failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(root.join(".worktrees").join("feature").exists());++ let cd_content = fs::read_to_string(&cd_path).unwrap_or_default();+ assert_eq!(+ cd_content.trim(),+ "",+ "the shell in `other` should stay put, not follow `feature`"+ );+}