Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(remove): warn when a submodule holds commits on no remote (#4460)
Maximilian Roosab2a1e3a2e77
diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex 72bef8fd1..a9711290d 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -1162,6 +1162,21 @@ impl<'a> WorkingTree<'a> {Ok(has_initialized_submodules_from_status(&output))}+ /// Initialized submodules, recursively, holding commits that no+ /// remote-tracking ref reaches, by display path. Reflog-only commits+ /// count: removing the worktree deletes a module store along with them.+ /// A shallow or SHA-fetched pin can report commits a remote does hold.+ pub fn submodules_with_local_commits(&self) -> anyhow::Result<Vec<String>> {+ let output = self.run_command(&[+ "submodule",+ "foreach",+ "--quiet",+ "--recursive",+ r#"test -z "$(git rev-list --all --reflog --not --remotes --max-count=1)" || echo "$displaypath""#,+ ])?;+ Ok(output.lines().map(String::from).collect())+ }+/// Back up the index, as a squash is about to commit it, to `refs/wt-backup/<branch>`.////// Writes the index as a commit whose parent is `HEAD`, so one commit holdsdiff --git a/src/output/handlers.rs b/src/output/handlers.rsindex bb54aa98d..465ed00a1 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -2140,6 +2140,22 @@ fn handle_removed_worktree_output(return remove_removed_worktree_silently(&repo, &ctx, announcer);}+ // `--force` already consents to losing what the worktree holds.+ let local_submodules = if ctx.force_worktree {+ Vec::new()+ } else {+ repo.worktree_at(ctx.worktree_path)+ .submodules_with_local_commits()?+ };+ for submodule in local_submodules {+ eprintln!(+ "{}",+ warning_message(cformat!(+ "Submodule <bold>{submodule}</> has commits on no remote; removing the worktree deletes them"+ ))+ );+ }+prepare_remove_directory_change(ctx.main_path, ctx.worktree_path, ctx.changed_directory)?;// Handle detached HEAD case (no branch known)diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex ccc3183c7..404fece55 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -717,6 +717,21 @@ pub fn shell_command(cmd}+/// Simulate Git invoking wt while retaining Git's own subcommand helpers.+pub fn configure_git_subcommand(cmd: &mut std::process::Command, repo: &TestRepo) {+ let output = repo+ .git_command()+ .args(["--exec-path"])+ .env_remove("GIT_EXEC_PATH")+ .run()+ .unwrap();+ assert!(output.status.success(), "{output:?}");+ cmd.env(+ "GIT_EXEC_PATH",+ String::from_utf8(output.stdout).unwrap().trim(),+ );+}+// =============================================================================// Snapshot settings functions (insta)// =============================================================================@@ -746,6 +761,7 @@ pub fn add_standard_env_redactions(settings: &mut insta::Settings) {// Windows: etcetera uses APPDATA for config_dir()settings.add_redaction(".env.APPDATA", "[TEST_CONFIG_HOME]");settings.add_redaction(".env.PATH", "[PATH]");+ settings.add_redaction(".env.GIT_EXEC_PATH", "[GIT_EXEC_PATH]");settings.add_redaction(".env.PWD", "[PWD]");// Mock commands directory (temp path for mock gh/glab binaries)settings.add_redaction(".env.WORKTRUNK_TEST_MOCK_CONFIG_DIR", "[TEST_MOCK_CONFIG]");diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex 38dca5ddc..af98ffc55 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -125,7 +125,7 @@ fn test_merge_as_git_subcommand(merge_scenario: (TestRepo, PathBuf)) {// Merge with GIT_EXEC_PATH set (simulating `git wt merge ...`)assert_cmd_snapshot!({let mut cmd = make_snapshot_cmd(&repo, "merge", &["main"], Some(&feature_wt));- cmd.env("GIT_EXEC_PATH", "/usr/lib/git-core");+ crate::common::configure_git_subcommand(&mut cmd, &repo);cmd});}diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex 8d0f50344..d225c096b 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -394,7 +394,7 @@ fn test_remove_as_git_subcommand(mut repo: TestRepo) {let settings = setup_snapshot_settings(&repo);settings.bind(|| {let mut cmd = make_snapshot_cmd(&repo, "remove", &[], Some(&worktree_path));- cmd.env("GIT_EXEC_PATH", "/usr/lib/git-core");+ crate::common::configure_git_subcommand(&mut cmd, &repo);assert_cmd_snapshot!("remove_as_git_subcommand", cmd);});}@@ -4859,7 +4859,61 @@ fn test_remove_foreground_succeeds_with_stuck_directory_detached(mut repo: TestR/// 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 worktree_path = add_worktree_with_submodule(&mut repo, "feature-submod");++ // 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"+ );+ // The submodule's only commit is on its remote.+ assert!(!stderr.contains("has commits on no remote"), "{stderr}");+}++/// A submodule commit reachable from no remote-tracking ref lives only in the+/// worktree's module store, so removal warns before deleting it, and still+/// removes: shallow or SHA-fetched pins can look the same.+#[rstest]+fn test_remove_warns_about_local_submodule_commits(mut repo: TestRepo) {+ let worktree_path = add_worktree_with_submodule(&mut repo, "feature-submod-local");+ let submodule = worktree_path.join("submod");+ repo.run_git_in(&submodule, &["commit", "--allow-empty", "-m", "local only"]);+ // Record the new pin, so the worktree itself is clean.+ repo.run_git_in(&worktree_path, &["commit", "-am", "bump submod"]);++ let output = repo+ .wt_command()+ .args(["remove", "--foreground", "feature-submod-local"])+ .output()+ .unwrap();++ let stderr = String::from_utf8_lossy(&output.stderr)+ .ansi_strip()+ .into_owned();+ assert!(output.status.success(), "{stderr}");+ assert!(+ stderr.contains(+ "Submodule submod has commits on no remote; removing the worktree deletes them"+ ),+ "{stderr}"+ );+ assert!(!worktree_path.exists());+}++/// Add a `submod` submodule cloned from a local source repository, then create+/// a worktree for `branch` with that submodule initialized.+fn add_worktree_with_submodule(repo: &mut TestRepo, branch: &str) -> PathBuf {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", "-b", "main"]);@@ -4887,8 +4941,7 @@ fn test_remove_foreground_with_submodules(mut repo: TestRepo) {);repo.run_git(&["commit", "-m", "add submodule"]);- // Create a worktree and initialize submodules in it- let worktree_path = repo.add_worktree("feature-submod");+ let worktree_path = repo.add_worktree(branch);let output = repo.git_command().current_dir(&worktree_path)@@ -4906,29 +4959,11 @@ fn test_remove_foreground_with_submodules(mut repo: TestRepo) {"Failed to init submodule: {}",String::from_utf8_lossy(&output.stderr));-- // Verify the submodule is actually initializedassert!(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"- );+ worktree_path}/// Regression: `Repository::remove_worktree(path, force=false)` synthesizesdiff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 51e837521..0131ab26a 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -739,7 +739,7 @@ fn test_switch_existing_as_git_subcommand(mut repo: TestRepo) {let settings = setup_snapshot_settings(&repo);settings.bind(|| {let mut cmd = make_snapshot_cmd(&repo, "switch", &["git-subcommand-test"], None);- cmd.env("GIT_EXEC_PATH", "/usr/lib/git-core");+ crate::common::configure_git_subcommand(&mut cmd, &repo);assert_cmd_snapshot!("switch_as_git_subcommand", cmd);});}