Skip to content

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

fix: handle submodules in worktree removal (#1196)

worktrunk-bot1383845b002b
diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rs
index 93efbe356..fb3df1974 100644
--- a/src/git/repository/worktrees.rs
+++ b/src/git/repository/worktrees.rs
@@ -131,6 +131,30 @@ impl Repository {
/// When `force` is true, passes `--force` to `git worktree remove`,
/// allowing removal even when the worktree contains untracked files
/// (like build artifacts such as `.vite/` or `node_modules/`).
+ ///
+ /// When the worktree contains initialized submodules, git refuses removal
+ /// even for clean worktrees. This method detects that case and automatically
+ /// retries with `--force`, which is safe because the caller has already
+ /// validated worktree cleanliness via `ensure_clean()`.
+ ///
+ /// # Why git requires `--force` for submodules
+ ///
+ /// Git's `--force` flag on `worktree remove` bypasses two unrelated
+ /// protections under one flag: dirty working tree checks AND the
+ /// submodule structural check. We separate these concerns — our
+ /// `ensure_clean()` handles dirty state, and the `--force` retry
+ /// handles the submodule restriction.
+ ///
+ /// # TOCTOU note
+ ///
+ /// Git checks for submodules *before* checking for dirty files. If a
+ /// file is modified between our `ensure_clean()` and the git command,
+ /// git reports the submodule error (not the dirty error), so the
+ /// `--force` retry fires and bypasses git's dirty check. This is the
+ /// same TOCTOU window that exists for all removal (between
+ /// `ensure_clean()` and the actual delete), but for non-submodule
+ /// worktrees git's own dirty check acts as an accidental backstop
+ /// that we lose here. The window is milliseconds.
pub fn remove_worktree(&self, path: &std::path::Path, force: bool) -> anyhow::Result<()> {
let path_str = path.to_str().ok_or_else(|| {
anyhow::Error::from(GitError::Other {
@@ -145,8 +169,21 @@ impl Repository {
args.push("--force");
}
args.push(path_str);
- self.run_command(&args)?;
- Ok(())
+
+ match self.run_command(&args) {
+ Ok(_) => Ok(()),
+ Err(e)
+ if !force
+ && e.to_string()
+ .contains("submodules cannot be moved or removed") =>
+ {
+ // Submodule retry — see doc comment above for safety analysis.
+ log::debug!("Retrying worktree removal with --force due to submodules");
+ self.run_command(&["worktree", "remove", "--force", path_str])?;
+ Ok(())
+ }
+ Err(e) => Err(e),
+ }
}
/// Resolve a worktree name, expanding "@" to current, "-" to previous, and "^" to main.
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 135ad0780..153a8ff65 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -72,7 +72,13 @@ fn execute_instant_removal_or_fallback(
// Fallback: cross-filesystem, permissions, Windows file locking, etc.
// Use legacy git worktree remove which handles these cases.
log::debug!("Instant removal unavailable, using legacy: {}", e);
- build_remove_command(worktree_path, branch_to_delete, force_worktree)
+ // Git refuses to remove worktrees with initialized submodules without
+ // --force. We preemptively set --force when .gitmodules exists — broader
+ // than checking initialization, but harmless for clean worktrees.
+ // See remove_worktree() doc comment for why --force is safe here and
+ // the TOCTOU nuance around git's error ordering.
+ let force = force_worktree || worktree_path.join(".gitmodules").exists();
+ build_remove_command(worktree_path, branch_to_delete, force)
}
}
}
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 12bd38ee7..b4d85a170 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -2254,6 +2254,87 @@ fn test_remove_foreground_failure_shows_remaining_entries_detached(mut repo: Tes
);
}
+/// Worktrees with initialized git submodules should be removable.
+///
+/// Git refuses `git worktree remove` when submodules are initialized,
+/// requiring `--force`. This test verifies that `wt remove --foreground`
+/// handles this automatically (retries with `--force`).
+///
+/// Regression test for <https://github.com/max-sixty/worktrunk/issues/1194>.
+#[rstest]
+fn test_remove_foreground_with_submodules(mut repo: TestRepo) {
+ // Create a local repo to use as a submodule source
+ let sub_source = repo.root_path().parent().unwrap().join("sub-source");
+ std::fs::create_dir_all(&sub_source).unwrap();
+ repo.run_git_in(&sub_source, &["init"]);
+ std::fs::write(sub_source.join("sub.txt"), "submodule content").unwrap();
+ repo.run_git_in(&sub_source, &["add", "sub.txt"]);
+ repo.run_git_in(&sub_source, &["commit", "-m", "sub init"]);
+
+ // Add submodule to the main repo (requires protocol.file.allow=always)
+ let output = repo
+ .git_command()
+ .args([
+ "-c",
+ "protocol.file.allow=always",
+ "submodule",
+ "add",
+ sub_source.to_str().unwrap(),
+ "submod",
+ ])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "Failed to add submodule: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ repo.run_git(&["commit", "-m", "add submodule"]);
+
+ // Create a worktree and initialize submodules in it
+ let worktree_path = repo.add_worktree("feature-submod");
+ let output = repo
+ .git_command()
+ .current_dir(&worktree_path)
+ .args([
+ "-c",
+ "protocol.file.allow=always",
+ "submodule",
+ "update",
+ "--init",
+ ])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "Failed to init submodule: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ // Verify the submodule is actually initialized
+ assert!(
+ worktree_path.join("submod").join("sub.txt").exists(),
+ "Submodule should be initialized"
+ );
+
+ // Remove the worktree in foreground mode — should succeed despite submodules
+ let output = repo
+ .wt_command()
+ .args(["remove", "--foreground", "feature-submod"])
+ .output()
+ .unwrap();
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ output.status.success(),
+ "Remove should succeed with submodules, got: {stderr}"
+ );
+ assert!(
+ !worktree_path.exists(),
+ "Worktree directory should be removed"
+ );
+}
+
/// Restore write permissions recursively so TempDir cleanup succeeds.
#[cfg(unix)]
fn restore_dir_permissions(dir: &std::path::Path) {