Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: detect submodules structurally instead of parsing error messages (#1247)
Maximilian Roos693d2e810b0a
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex 24a646a2a..f51386c1d 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -174,6 +174,9 @@ impl RepositoryCliExt for Repository {}// Check working tree cleanliness (unless --force, which passes through to git)+ // NOTE: background removal fallback may still add --force later when+ // .gitmodules is detected at execution time (see output::handlers),+ // so this remains a best-effort check with a small TOCTOU window.if !force_worktree {target_wt.ensure_clean("remove worktree", branch_name.as_deref(), true)?;}diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex d88f403a9..ecaffb67d 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -9,6 +9,18 @@ use dunce::canonicalize;use super::{GitError, LineDiff, Repository};+/// Parse `git submodule status` output and detect whether any submodule is initialized.+///+/// Status lines start with a one-character state marker:+/// - `-` = not initialized+/// - ` ` / `+` / `U` = initialized variants+fn has_initialized_submodules_from_status(status: &str) -> bool {+ status.lines().any(|line| match line.chars().next() {+ Some('-') | None => false,+ Some(_) => true,+ })+}+/// Get a short display name for a path, used in logging context.pub fn path_to_logging_context(path: &Path) -> String {if path.to_str() == Some(".") {@@ -263,6 +275,15 @@ impl<'a> WorkingTree<'a> {.is_err())}+ /// Check whether this worktree has initialized submodules.+ ///+ /// Uses `git submodule status --recursive` and parses its stable single-character+ /// status prefix instead of relying on human-readable git error messages.+ pub fn has_initialized_submodules(&self) -> anyhow::Result<bool> {+ let output = self.run_command(&["submodule", "status", "--recursive"])?;+ Ok(has_initialized_submodules_from_status(&output))+ }+/// Create a safety backup of current working tree state without affecting the working tree.////// This creates a backup commit containing all changes (staged, unstaged, and untracked files)@@ -324,3 +345,34 @@ impl<'a> WorkingTree<'a> {Ok(backup_sha[..7].to_string())}}++#[cfg(test)]+mod tests {+ use super::has_initialized_submodules_from_status;++ #[test]+ fn submodule_status_empty_is_not_initialized() {+ assert!(!has_initialized_submodules_from_status(""));+ }++ #[test]+ fn submodule_status_dash_is_not_initialized() {+ assert!(!has_initialized_submodules_from_status(+ "-9c8b8ff2fe89b8f1c5b8e17cb60f0d0df47f71e0 submod"+ ));+ }++ #[test]+ fn submodule_status_space_is_initialized() {+ assert!(has_initialized_submodules_from_status(+ " 9c8b8ff2fe89b8f1c5b8e17cb60f0d0df47f71e0 submod (heads/main)"+ ));+ }++ #[test]+ fn submodule_status_plus_is_initialized() {+ assert!(has_initialized_submodules_from_status(+ "+9c8b8ff2fe89b8f1c5b8e17cb60f0d0df47f71e0 submod (heads/main)"+ ));+ }+}diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rsindex c512cbb19..f7663cf6b 100644--- a/src/git/repository/worktrees.rs+++ b/src/git/repository/worktrees.rs@@ -133,25 +133,26 @@ impl Repository {/// (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()`.+ /// even for clean worktrees. This method detects that case up front and+ /// adds `--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+ /// `ensure_clean()` handles dirty state, and `--force`/// 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+ /// git reports the submodule error (not the dirty error), so our+ /// submodule pre-check still leads to `--force` 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.@@ -164,26 +165,22 @@ impl Repository {),})})?;+ let use_force = if force {+ true+ } else {+ self.worktree_at(path).has_initialized_submodules()?+ };+ if use_force && !force {+ log::debug!("Using --force for worktree removal due to initialized submodules");+ }let mut args = vec!["worktree", "remove"];- if force {+ if use_force {args.push("--force");}args.push(path_str);- 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),- }+ self.run_command(&args)?;+ Ok(())}/// Resolve a worktree name, expanding "@" to current, "-" to previous, and "^" to main.diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex be9011160..7621314ad 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -87,8 +87,12 @@ fn execute_instant_removal_or_fallback(// 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.+ //+ // TOCTOU note: the clean check runs during planning in+ // prepare_worktree_removal(). In this fallback path, we may add --force+ // later (at execution time) when .gitmodules is present. That creates a+ // small check-vs-use window where newly introduced changes could be+ // removed. See remove_worktree() docs for the detailed safety analysis.let force = force_worktree || worktree_path.join(".gitmodules").exists();build_remove_command(worktree_path, branch_to_delete, force)}diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex b80e36bf5..438fd7a8a 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -683,6 +683,9 @@ pub fn configure_cli_command(cmd: &mut Command) {cmd.env_remove(&key);}}+ // Prevent host environment from disabling ANSI in snapshots.+ // NO_COLOR can override CLICOLOR_FORCE in downstream output handling.+ cmd.env_remove("NO_COLOR");// Set to non-existent path to prevent loading user's real config.// Tests that need config should use TestRepo::configure_wt_cmd() which overrides this.// Note: env_remove above may cause insta-cmd to capture empty values in snapshots,diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rsindex 2f71f22d6..5b1483a9f 100644--- a/tests/integration_tests/step_prune.rs+++ b/tests/integration_tests/step_prune.rs@@ -268,6 +268,31 @@ fn test_prune_orphan_branch_min_age(repo: TestRepo) {assert_cmd_snapshot!(cmd);}+/// Prune can remove a mix of branch-only and worktree candidates in one run.+#[rstest]+fn test_prune_mixed_worktree_and_orphan_branch(mut repo: TestRepo) {+ repo.commit("initial");++ // Branch-only candidate: integrated orphan branch without a worktree.+ repo.create_branch("orphan-mixed");++ // Worktree candidate: integrated worktree at the same commit as main.+ repo.add_worktree("merged-mixed");++ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "step",+ &["prune", "--yes", "--min-age=0s"],+ None+ ));++ let parent = repo.root_path().parent().unwrap();+ assert!(+ !parent.join("repo.merged-mixed").exists(),+ "Merged worktree should be removed"+ );+}+/// Prune from a merged worktree removes it last (CandidateKind::Current).////// Skipped on Windows: Windows locks the current working directory, preventingdiff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_mixed_worktree_and_orphan_branch.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_mixed_worktree_and_orphan_branch.snapnew file mode 100644index 000000000..fde23b31c--- /dev/null+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_mixed_worktree_and_orphan_branch.snap@@ -0,0 +1,50 @@+---+source: tests/integration_tests/step_prune.rs+assertion_line: 282+info:+ program: wt+ args:+ - step+ - prune+ - "--yes"+ - "--min-age=0s"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_PAGER: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ NO_COLOR: ""+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[36m◎ Removing [1mmerged-mixed[22m worktree & branch in background (same commit as [1mmain[22m,[39m [2m_[22m[36m)[39m+[32m✓ Removed branch [1morphan-mixed[22m (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39m+[32m✓[39m [32mPruned 1 worktree (with branch), 1 branch[39m