Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: refuse to remove default branch worktree unless -D (#1460)
Maximilian Roosa0a217820c51
diff --git a/src/commands/branch_deletion.rs b/src/commands/branch_deletion.rsindex c149bb084..9682dc32c 100644--- a/src/commands/branch_deletion.rs+++ b/src/commands/branch_deletion.rs@@ -34,19 +34,24 @@ pub fn delete_branch_if_safe(target: &str,force_delete: bool,) -> anyhow::Result<BranchDeletionResult> {+ // Force-delete: skip integration check entirely (matches compute_integration_reason+ // behavior for the Worktree path). The user explicitly chose -D.+ if force_delete {+ repo.run_command(&["branch", "-D", branch_name])?;+ return Ok(BranchDeletionResult {+ outcome: BranchDeletionOutcome::ForceDeleted,+ integration_target: target.to_string(),+ });+ }+let (effective_target, reason) = repo.integration_reason(branch_name, target)?;- // Determine outcome based on integration and force flag- let outcome = match (reason, force_delete) {- (Some(r), _) => {+ let outcome = match reason {+ Some(r) => {repo.run_command(&["branch", "-D", branch_name])?;BranchDeletionOutcome::Integrated(r)}- (None, true) => {- repo.run_command(&["branch", "-D", branch_name])?;- BranchDeletionOutcome::ForceDeleted- }- (None, false) => BranchDeletionOutcome::NotDeleted,+ None => BranchDeletionOutcome::NotDeleted,};Ok(BranchDeletionResult {diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex 8b6d4e892..285606bc4 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -84,8 +84,21 @@ impl RepositoryCliExt for Repository {// then repo base for bare repos with no worktrees.let home_worktree_path = self.home_path()?;- // Resolve target to worktree path and branch- let (worktree_path, branch_name, is_current) = match target {+ // Phase 1: Resolve target to branch name and worktree disposition.+ // BranchOnly variants don't early-return — they go through shared validation below.+ enum Resolved {+ Worktree {+ path: PathBuf,+ branch: Option<String>,+ is_current: bool,+ },+ BranchOnly {+ branch: String,+ pruned: bool,+ },+ }++ let resolved = match target {RemoveTarget::Branch(branch) => {match worktrees.iter()@@ -95,47 +108,50 @@ impl RepositoryCliExt for Repository {if !wt.path.exists() {// Directory missing - prune and continueself.prune_worktrees()?;- return Ok(RemoveResult::BranchOnly {- branch_name: branch.to_string(),- deletion_mode,+ Resolved::BranchOnly {+ branch: branch.to_string(),pruned: true,- });- }- if wt.locked.is_some() {+ }+ } else if wt.locked.is_some() {return Err(GitError::WorktreeLocked {branch: branch.into(),path: wt.path.clone(),reason: wt.locked.clone(),}.into());+ } else {+ let is_current = current_path == wt.path;+ Resolved::Worktree {+ path: wt.path.clone(),+ branch: Some(branch.to_string()),+ is_current,+ }}- let is_current = current_path == wt.path;- (wt.path.clone(), Some(branch.to_string()), is_current)}None => {// No worktree found - check if the branch exists locallylet branch_handle = self.branch(branch);if branch_handle.exists_locally()? {- return Ok(RemoveResult::BranchOnly {- branch_name: branch.to_string(),- deletion_mode,+ Resolved::BranchOnly {+ branch: branch.to_string(),pruned: false,- });- }- // Check if branch exists on a remote- let remotes = branch_handle.remotes()?;- if !remotes.is_empty() {- return Err(GitError::RemoteOnlyBranch {+ }+ } else {+ // Check if branch exists on a remote+ let remotes = branch_handle.remotes()?;+ if !remotes.is_empty() {+ return Err(GitError::RemoteOnlyBranch {+ branch: branch.into(),+ remote: remotes[0].clone(),+ }+ .into());+ }+ return Err(GitError::BranchNotFound {branch: branch.into(),- remote: remotes[0].clone(),+ show_create_hint: false,}.into());}- return Err(GitError::BranchNotFound {- branch: branch.into(),- show_create_hint: false,- }- .into());}}}@@ -163,20 +179,51 @@ impl RepositoryCliExt for Repository {.into());}let is_current = wt.path == current_path;- (wt.path.clone(), wt.branch.clone(), is_current)+ Resolved::Worktree {+ path: wt.path.clone(),+ branch: wt.branch.clone(),+ is_current,+ }}};- // Cannot remove the main working tree (only linked worktrees can be removed)- let target_wt = self.worktree_at(&worktree_path);- if !target_wt.is_linked()? {+ // Phase 2: Main-worktree guard (before default-branch check, since+ // -D can't override the main worktree restriction).+ if let Resolved::Worktree { ref path, .. } = resolved+ && !self.worktree_at(path).is_linked()?+ {return Err(GitError::CannotRemoveMainWorktree.into());}- // 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.+ // Phase 3: Branch-level validation (applies to ALL paths).+ let branch_name = match &resolved {+ Resolved::Worktree { branch, .. } => branch.as_deref(),+ Resolved::BranchOnly { branch, .. } => Some(branch.as_str()),+ };+ if let Some(branch) = branch_name {+ check_not_default_branch(self, branch, &deletion_mode)?;+ }++ // Phase 4: Return BranchOnly early (after validation), or continue to+ // worktree-level checks.+ let (worktree_path, branch_name, is_current) = match resolved {+ Resolved::BranchOnly { branch, pruned } => {+ return Ok(RemoveResult::BranchOnly {+ branch_name: branch,+ deletion_mode,+ pruned,+ });+ }+ Resolved::Worktree {+ path,+ branch,+ is_current,+ } => (path, branch, is_current),+ };++ // Phase 5: Remaining worktree-level validation.+ let target_wt = self.worktree_at(&worktree_path);+if !force_worktree {target_wt.ensure_clean("remove worktree", branch_name.as_deref(), true)?;}@@ -189,7 +236,6 @@ impl RepositoryCliExt for Repository {};// Resolve target branch for integration reason display- // Skip if removing the default branch itself (avoids tautological "main (ancestor of main)")let default_branch = self.default_branch();let target_branch = match (&default_branch, &branch_name) {(Some(db), Some(bn)) if db == bn => None,@@ -373,6 +419,24 @@ fn compute_integration_reason(reason}+/// Reject removing the default branch unless force-delete is set.+///+/// The default branch is the integration target — checking it against itself is+/// tautological (same logic as `wt list`'s `is_main` guard in `check_integration_state`).+fn check_not_default_branch(+ repo: &Repository,+ branch: &str,+ deletion_mode: &BranchDeletionMode,+) -> anyhow::Result<()> {+ if !deletion_mode.is_force() && repo.default_branch().as_deref() == Some(branch) {+ return Err(GitError::CannotRemoveDefaultBranch {+ branch: branch.to_string(),+ }+ .into());+ }+ Ok(())+}+/// Warn about untracked files that will be auto-staged.fn warn_about_untracked_files(status_output: &str) -> anyhow::Result<()> {let files = parse_untracked_files(status_output);diff --git a/src/git/error.rs b/src/git/error.rsindex c8ee48723..5e9706eea 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -223,6 +223,9 @@ pub enum GitError {remaining_entries: Option<Vec<String>>,},CannotRemoveMainWorktree,+ CannotRemoveDefaultBranch {+ branch: String,+ },WorktreeLocked {branch: String,path: PathBuf,@@ -590,6 +593,22 @@ impl GitError {)}+ GitError::CannotRemoveDefaultBranch { branch } => {+ let cmd = suggest_command("remove", &[branch], &["-D"]);+ write!(+ f,+ "{}",+ error_message(cformat!(+ "Cannot remove the default branch <bold>{branch}</>"+ ))+ )?;+ write!(+ f,+ "\n{}",+ hint_message(cformat!("To force-delete, run <underline>{cmd}</>"))+ )+ }+GitError::WorktreeLocked {branch,path,diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex d7041fea9..0955afb07 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -1013,14 +1013,13 @@ fn test_remove_main_worktree_vs_linked_worktree(mut repo: TestRepo) {);}-///-/// When removing a worktree for "main" branch, we should NOT show "(ancestor of main)"-/// because that would be tautological. The message should just be "Removed main worktree & branch".+/// Removing the default branch worktree should be refused — the default branch+/// is the integration target, not something to remove.////// This requires a bare repo setup since you can't have a linked worktree for the default/// branch in a normal repo (the main worktree already has it checked out).#[test]-fn test_remove_default_branch_no_tautology() {+fn test_remove_default_branch_refused() {let test = BareRepoTest::new();// Create worktrees for main and feature branches@@ -1028,15 +1027,57 @@ fn test_remove_default_branch_no_tautology() {test.commit_in(&main_worktree, "Initial commit on main");let feature_worktree = test.create_worktree("feature", "feature");- // Remove main worktree by name from feature worktree (foreground for snapshot)- // Should NOT show "(ancestor of main)" - that would be tautologicallet settings = setup_temp_snapshot_settings(test.temp_path());++ // Without -D: should failsettings.bind(|| {let mut cmd = test.wt_command();cmd.args(["remove", "--foreground", "main"]).current_dir(&feature_worktree);- assert_cmd_snapshot!("remove_default_branch_no_tautology", cmd);+ assert_cmd_snapshot!("remove_default_branch_refused", cmd);+ });++ // With -D: should succeed (user explicitly force-deletes)+ settings.bind(|| {+ let mut cmd = test.wt_command();+ cmd.args(["remove", "--foreground", "-D", "main"])+ .current_dir(&feature_worktree);++ assert_cmd_snapshot!("remove_default_branch_force_delete", cmd);+ });+}++/// BranchOnly path: when the default branch has no worktree (directory deleted),+/// removal should be refused without -D, and allowed with -D.+#[test]+fn test_remove_default_branch_branch_only() {+ let test = BareRepoTest::new();++ let main_worktree = test.create_worktree("main", "main");+ test.commit_in(&main_worktree, "Initial commit on main");+ let feature_worktree = test.create_worktree("feature", "feature");++ // Delete main worktree directory so it becomes a BranchOnly removal+ std::fs::remove_dir_all(&main_worktree).unwrap();++ let settings = setup_temp_snapshot_settings(test.temp_path());++ // Without -D: should be refused+ settings.bind(|| {+ let mut cmd = test.wt_command();+ cmd.args(["remove", "main"]).current_dir(&feature_worktree);++ assert_cmd_snapshot!("remove_default_branch_branch_only_refused", cmd);+ });++ // With -D: should succeed (force-delete the default branch)+ settings.bind(|| {+ let mut cmd = test.wt_command();+ cmd.args(["remove", "-D", "main"])+ .current_dir(&feature_worktree);++ assert_cmd_snapshot!("remove_default_branch_branch_only_force_delete", cmd);});}diff --git a/tests/snapshots/integration__integration_tests__remove__remove_default_branch_branch_only_force_delete.snap b/tests/snapshots/integration__integration_tests__remove__remove_default_branch_branch_only_force_delete.snapnew file mode 100644index 000000000..467d79c53--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__remove_default_branch_branch_only_force_delete.snap@@ -0,0 +1,41 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ - "-D"+ - main+ env:+ CLICOLOR_FORCE: ""+ 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_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ LANG: C+ LC_ALL: C+ NO_COLOR: ""+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ 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"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+○ No worktree found for branch main+✓ Removed branch main (--force-delete)diff --git a/tests/snapshots/integration__integration_tests__remove__remove_default_branch_branch_only_refused.snap b/tests/snapshots/integration__integration_tests__remove__remove_default_branch_branch_only_refused.snapnew file mode 100644index 000000000..5e8607edf--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__remove_default_branch_branch_only_refused.snap@@ -0,0 +1,40 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ - main+ env:+ CLICOLOR_FORCE: ""+ 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_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ LANG: C+ LC_ALL: C+ NO_COLOR: ""+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ 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"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+✗ Cannot remove the default branch main+↳ To force-delete, run wt remove -D maindiff --git a/tests/snapshots/integration__integration_tests__remove__remove_default_branch_no_tautology.snap b/tests/snapshots/integration__integration_tests__remove__remove_default_branch_force_delete.snapsimilarity index 80%rename from tests/snapshots/integration__integration_tests__remove__remove_default_branch_no_tautology.snaprename to tests/snapshots/integration__integration_tests__remove__remove_default_branch_force_delete.snapindex 6c9504fc7..212bb771a 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_default_branch_no_tautology.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_default_branch_force_delete.snap@@ -5,6 +5,7 @@ info:args:- remove- "--foreground"+ - "-D"- mainenv:CLICOLOR_FORCE: ""@@ -22,10 +23,13 @@ info:RUST_LOG: warnSHELL: ""TERM: alacritty+ 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"---@@ -35,4 +39,4 @@ exit_code: 0----- stderr -----◎ Removing main worktree...-✓ Removed main worktree & branch+✓ Removed main worktree & branch (--force-delete)diff --git a/tests/snapshots/integration__integration_tests__remove__remove_default_branch_refused.snap b/tests/snapshots/integration__integration_tests__remove__remove_default_branch_refused.snapnew file mode 100644index 000000000..42b804c17--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__remove_default_branch_refused.snap@@ -0,0 +1,41 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ - "--foreground"+ - main+ env:+ CLICOLOR_FORCE: ""+ 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_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ LANG: C+ LC_ALL: C+ NO_COLOR: ""+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ 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"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+✗ Cannot remove the default branch main+↳ To force-delete, run wt remove -D maindiff --git a/tests/snapshots/integration__integration_tests__remove__remove_main_vs_linked__main_by_name_from_linked_fails.snap b/tests/snapshots/integration__integration_tests__remove__remove_main_vs_linked__main_by_name_from_linked_fails.snapindex 7a62335ae..9921c672c 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_main_vs_linked__main_by_name_from_linked_fails.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_main_vs_linked__main_by_name_from_linked_fails.snap@@ -19,16 +19,20 @@ info:LANG: CLC_ALL: CMOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ NO_COLOR: ""PATH: "[PATH]"PSModulePath: ""RUST_LOG: warnSHELL: ""TERM: alacrittyUSERPROFILE: "[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]"