Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(relocate): surface failed git checkout/move instead of silent success (#2348)

Maximilian Roosd51b651bd49a
diff --git a/src/commands/relocate.rs b/src/commands/relocate.rs
index ff1a9f1cd..a89a9db11 100644
--- a/src/commands/relocate.rs
+++ b/src/commands/relocate.rs
@@ -28,7 +28,6 @@ use color_print::cformat;
use worktrunk::config::UserConfig;
use worktrunk::git::{Repository, WorktreeInfo};
use worktrunk::path::format_path_for_display;
-use worktrunk::shell_exec::Cmd;
use worktrunk::styling::{
eprintln, format_with_gutter, hint_message, info_message, progress_message, success_message,
warning_message,
@@ -81,7 +80,14 @@ struct TempRelocation {
}
/// Executes relocations in dependency order, handling cycles via temp moves.
-pub struct RelocationExecutor {
+///
+/// Git commands route through `repo.worktree_at(path).run_command(...)` rather
+/// than raw `Cmd::new("git").run()`. `Cmd::run()` returns `Ok(Output)` on
+/// non-zero exit — only spawn errors travel through `?` — so raw `.run()`
+/// would silently swallow a failed `git worktree move` / `git checkout` and
+/// let the caller print a false "Relocated ..." success message.
+pub struct RelocationExecutor<'a> {
+ repo: &'a Repository,
pending: Vec<ValidatedCandidate>,
/// Maps canonical current path → index in pending (for cycle detection)
current_locations: HashMap<PathBuf, usize>,
@@ -267,10 +273,10 @@ pub fn validate_candidates(
// Phase 3 & 4: Execute relocations
// ============================================================================
-impl RelocationExecutor {
+impl<'a> RelocationExecutor<'a> {
/// Create executor and classify targets (handling blockers with optional clobber).
pub fn new(
- repo: &Repository,
+ repo: &'a Repository,
validated: Vec<ValidatedCandidate>,
clobber: bool,
) -> anyhow::Result<Self> {
@@ -365,6 +371,7 @@ impl RelocationExecutor {
}
Ok(Self {
+ repo,
pending: validated,
current_locations,
blocked,
@@ -377,12 +384,7 @@ impl RelocationExecutor {
}
/// Execute all relocations in dependency order.
- pub fn execute(
- &mut self,
- repo_path: &Path,
- default_branch: &str,
- cwd: Option<&Path>,
- ) -> anyhow::Result<()> {
+ pub fn execute(&mut self, default_branch: &str, cwd: Option<&Path>) -> anyhow::Result<()> {
// Process until all pending are moved or in temp
loop {
let mut made_progress = false;
@@ -395,7 +397,7 @@ impl RelocationExecutor {
match self.is_target_empty(i) {
Some(true) => {
- self.move_worktree(i, repo_path, default_branch, cwd)?;
+ self.move_worktree(i, default_branch, cwd)?;
made_progress = true;
}
Some(false) => {
@@ -461,7 +463,6 @@ impl RelocationExecutor {
fn move_worktree(
&mut self,
idx: usize,
- repo_path: &Path,
default_branch: &str,
cwd: Option<&Path>,
) -> anyhow::Result<()> {
@@ -475,14 +476,13 @@ impl RelocationExecutor {
let dest_display = format_path_for_display(&dest_path);
if is_main {
- self.move_main_worktree(idx, repo_path, default_branch)?;
+ self.move_main_worktree(idx, default_branch)?;
} else {
- Cmd::new("git")
- .args(["worktree", "move"])
- .arg(src_path.to_string_lossy())
- .arg(dest_path.to_string_lossy())
- .context(&branch)
- .run()
+ let src = src_path.to_string_lossy();
+ let dest = dest_path.to_string_lossy();
+ self.repo
+ .worktree_at(self.repo.repo_path()?)
+ .run_command(&["worktree", "move", &src, &dest])
.context("Failed to move worktree")?;
}
@@ -503,43 +503,32 @@ impl RelocationExecutor {
}
/// Main worktree can't use `git worktree move`; must create new + switch.
- fn move_main_worktree(
- &mut self,
- idx: usize,
- repo_path: &Path,
- default_branch: &str,
- ) -> anyhow::Result<()> {
+ fn move_main_worktree(&mut self, idx: usize, default_branch: &str) -> anyhow::Result<()> {
let candidate = &self.pending[idx];
let branch = candidate.branch();
let msg = cformat!("Switching main worktree to <bold>{default_branch}</>...");
eprintln!("{}", progress_message(msg));
- Cmd::new("git")
- .args(["checkout", default_branch])
- .current_dir(repo_path)
- .context("main")
- .run()
- .context("Failed to checkout default branch")?;
-
- // Try to create worktree; if it fails, rollback to original branch
- let add_result = Cmd::new("git")
- .args(["worktree", "add"])
- .arg(candidate.expected_path.to_string_lossy())
- .arg(branch)
- .context(branch)
- .run();
+ // Bind the main worktree up front so the rollback path can reuse it
+ // without threading another `?` through a best-effort cleanup.
+ let main_wt = self.repo.worktree_at(self.repo.repo_path()?);
+
+ main_wt
+ .run_command(&["checkout", default_branch])
+ .with_context(|| format!("Failed to checkout default branch '{default_branch}'"))?;
+
+ // Try to create worktree; if it fails, rollback to original branch.
+ let dest = candidate.expected_path.to_string_lossy();
+ let add_result = main_wt.run_command(&["worktree", "add", &dest, branch]);
if let Err(e) = add_result {
// Rollback: checkout the original branch to restore user context
let rollback_msg = cformat!("Worktree creation failed, restoring <bold>{branch}</>...");
eprintln!("{}", warning_message(rollback_msg));
- let _ = Cmd::new("git")
- .args(["checkout", branch])
- .current_dir(repo_path)
- .context("main")
- .run(); // Best-effort rollback
+ // Best-effort rollback: log failures but don't mask the original error.
+ let _ = main_wt.run_command(&["checkout", branch]);
return Err(e).context("Failed to create worktree for main relocation");
}
@@ -579,12 +568,11 @@ impl RelocationExecutor {
let msg = cformat!("Moving <bold>{branch}</> to temporary location...");
eprintln!("{}", progress_message(msg));
- Cmd::new("git")
- .args(["worktree", "move"])
- .arg(candidate.wt.path.to_string_lossy())
- .arg(temp_path.to_string_lossy())
- .context(branch)
- .run()
+ let src = candidate.wt.path.to_string_lossy();
+ let dest = temp_path.to_string_lossy();
+ self.repo
+ .worktree_at(self.repo.repo_path()?)
+ .run_command(&["worktree", "move", &src, &dest])
.context("Failed to move worktree to temp")?;
// Update current_locations to reflect the move
@@ -614,12 +602,11 @@ impl RelocationExecutor {
let src_display = format_path_for_display(&temp.original_path);
let dest_display = format_path_for_display(&candidate.expected_path);
- Cmd::new("git")
- .args(["worktree", "move"])
- .arg(temp.temp_path.to_string_lossy())
- .arg(candidate.expected_path.to_string_lossy())
- .context(branch)
- .run()
+ let src = temp.temp_path.to_string_lossy();
+ let dest = candidate.expected_path.to_string_lossy();
+ self.repo
+ .worktree_at(self.repo.repo_path()?)
+ .run_command(&["worktree", "move", &src, &dest])
.context("Failed to move worktree from temp to final location")?;
let msg = cformat!("Relocated <bold>{branch}</>: {src_display} → {dest_display}");
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index 7f2241d75..6d7a86e53 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -1830,7 +1830,7 @@ pub fn step_relocate(
// Phase 3 & 4: Create executor (classifies targets) and execute relocations
let mut executor = RelocationExecutor::new(&repo, validated, clobber)?;
let cwd = std::env::current_dir().ok();
- executor.execute(&repo_path, &default_branch, cwd.as_deref())?;
+ executor.execute(&default_branch, cwd.as_deref())?;
// Show summary
let total_skipped = skipped + executor.skipped;
diff --git a/tests/integration_tests/step_relocate.rs b/tests/integration_tests/step_relocate.rs
index adffcc1df..d5afeefea 100644
--- a/tests/integration_tests/step_relocate.rs
+++ b/tests/integration_tests/step_relocate.rs
@@ -598,6 +598,84 @@ worktree-path = "{{ nonexistent_variable }}"
);
}
+/// Regression test: main worktree relocation must surface a failed
+/// `git checkout <default_branch>` rather than silently claiming success.
+///
+/// Setup engineers a state where `worktrunk.default-branch` is set to a
+/// branch that does not exist locally. `Repository::default_branch()`
+/// trusts the persisted value (validation happens downstream), so
+/// `wt step relocate` proceeds into `move_main_worktree`, which tries
+/// `git checkout <nonexistent-branch>`. Before the fix, `Cmd::run()`
+/// returned `Ok(Output { status: non-zero, .. })` and the `?` operator
+/// didn't propagate it, so relocate printed "Relocated main ..." even
+/// though nothing happened.
+///
+/// After the fix: non-zero exit bails with the git stderr, exit code is
+/// non-zero, and the main worktree stays at its original path.
+#[rstest]
+fn test_relocate_main_worktree_checkout_failure_surfaces(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+ let repo_path = repo.root_path().to_path_buf();
+
+ // Switch main worktree to a non-default branch so it becomes a
+ // relocation candidate (expected path = repo.feature, not repo).
+ repo.run_git(&["checkout", "-b", "feature"]);
+
+ // Point worktrunk's default-branch cache at a branch that doesn't
+ // resolve locally. `default_branch()` now returns this value without
+ // validating it, so relocate's preflight does NOT bail and the main
+ // worktree code path runs `git checkout nonexistent-branch-xyz`.
+ repo.run_git(&[
+ "config",
+ "worktrunk.default-branch",
+ "nonexistent-branch-xyz",
+ ]);
+
+ let output = repo
+ .wt_command()
+ .args(["step", "relocate"])
+ .output()
+ .unwrap();
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let stderr = String::from_utf8_lossy(&output.stderr);
+
+ assert!(
+ !output.status.success(),
+ "relocate must fail when checkout of default branch fails; \
+ stdout: {stdout}\nstderr: {stderr}"
+ );
+ assert!(
+ !stderr.contains("Relocated"),
+ "relocate must not claim success after a failed checkout; \
+ stdout: {stdout}\nstderr: {stderr}"
+ );
+
+ // Main worktree is untouched - still at repo_path, still on feature.
+ assert!(
+ repo_path.exists(),
+ "main worktree path should still exist: {}",
+ repo_path.display()
+ );
+ let expected_path = parent.join("repo.feature");
+ assert!(
+ !expected_path.exists(),
+ "relocate must not create the new worktree path after checkout \
+ failure: {}",
+ expected_path.display()
+ );
+
+ let branch_output = repo
+ .git_command()
+ .args(["branch", "--show-current"])
+ .run()
+ .unwrap();
+ assert_eq!(
+ String::from_utf8_lossy(&branch_output.stdout).trim(),
+ "feature",
+ "main worktree branch should be unchanged after failed checkout"
+ );
+}
+
/// Test that empty default branch is detected early with actionable error.
///
/// Engineers a state where detection genuinely fails (no remote, no