Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Detect and reject locked worktrees in wt remove (#408)
Maximilian Roosf996bd404683
diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 142c902bc..b21479912 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -38,9 +38,8 @@ pub use step_commands::{RebaseResult, SquashResult, handle_rebase, handle_squash, step_commit, step_show_squash_prompt,};pub use worktree::{- ResolutionContext, compute_worktree_path, handle_remove, handle_remove_by_path,- handle_remove_current, handle_switch, is_worktree_at_expected_path_with, resolve_worktree_arg,- worktree_display_name,+ ResolutionContext, compute_worktree_path, handle_remove, handle_remove_current, handle_switch,+ is_worktree_at_expected_path_with, resolve_worktree_arg, worktree_display_name,};// Re-export Shell from the canonical locationdiff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex 2e3a7c015..58b5476ca 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -88,6 +88,13 @@ impl RepositoryCliExt for Repository {}.into());}+ if wt.locked.is_some() {+ return Err(GitError::WorktreeLocked {+ branch: branch.into(),+ reason: wt.locked.clone(),+ }+ .into());+ }let is_current = current_path == wt.path;(wt.path.clone(), Some(branch.to_string()), is_current)}@@ -122,6 +129,18 @@ impl RepositoryCliExt for Repository {.ok_or_else(|| {anyhow::anyhow!("Current worktree not found in worktree list")})?;+ if wt.locked.is_some() {+ // Use branch name if available, otherwise use directory name+ let name = wt+ .branch+ .clone()+ .unwrap_or_else(|| wt.dir_name().to_string());+ return Err(GitError::WorktreeLocked {+ branch: name,+ reason: wt.locked.clone(),+ }+ .into());+ }(wt.path.clone(), wt.branch.clone(), true)}};diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex b2ad48911..ec512d50d 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -759,51 +759,6 @@ pub fn handle_remove_current()}-/// Handle removing a worktree by path (for detached non-current worktrees).-///-/// This is used when a worktree is in detached HEAD state and we're not-/// currently in it. We can still remove the worktree, we just don't know-/// which branch (if any) to delete. Branch deletion is not attempted-/// since no branch is associated with a detached HEAD worktree.-pub fn handle_remove_by_path(- path: &std::path::Path,- branch: Option<String>,- force_worktree: bool,- background: bool,-) -> anyhow::Result<RemoveResult> {- let repo = Repository::current();-- if !background {- crate::output::print(progress_message(cformat!(- "Removing worktree @ <bold>{}</>...",- worktrunk::path::format_path_for_display(path)- )))?;- }-- // Check that the worktree is clean- let target_repo = Repository::at(path);- target_repo- .ensure_clean_working_tree("remove worktree", branch.as_deref())- .context("Failed to verify worktree status")?;-- // We're not in this worktree, so no directory change needed- let current_path = repo- .worktree_root()- .context("Failed to determine current worktree")?- .to_path_buf();-- Ok(RemoveResult::RemovedWorktree {- main_path: current_path,- worktree_path: path.to_path_buf(),- changed_directory: false,- branch_name: branch,- deletion_mode: BranchDeletionMode::Keep, // Can't delete branch for detached worktree- target_branch: None,- integration_reason: None, // Not applicable for detached worktrees- force_worktree,- })-}-impl<'a> CommandContext<'a> {/// Execute post-create commands sequentially (blocking)///diff --git a/src/git/error.rs b/src/git/error.rsindex 263f1a165..f7fc4b7a0 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -89,6 +89,10 @@ pub enum GitError {error: String,},CannotRemoveMainWorktree,+ WorktreeLocked {+ branch: String,+ reason: Option<String>,+ },// Merge/push errorsConflictingChanges {@@ -319,6 +323,23 @@ impl std::fmt::Display for GitError {)}+ GitError::WorktreeLocked { branch, reason } => {+ let reason_text = match reason {+ Some(r) if !r.is_empty() => format!(" ({r})"),+ _ => String::new(),+ };+ write!(+ f,+ "{}\n{}",+ error_message(cformat!(+ "Cannot remove <bold>{branch}</>, worktree is locked{reason_text}"+ )),+ hint_message(cformat!(+ "To unlock, run <bright-black>git worktree unlock {branch}</>"+ ))+ )+ }+GitError::ConflictingChanges {target_branch,files,@@ -973,6 +994,38 @@ mod tests {assert!(display.contains("main worktree"));}+ #[test]+ fn test_git_error_worktree_locked_with_reason() {+ let err = GitError::WorktreeLocked {+ branch: "feature".into(),+ reason: Some("Testing lock".into()),+ };+ let display = err.to_string();+ assert!(display.contains("Cannot remove"));+ assert!(display.contains("feature"));+ assert!(display.contains(", worktree is locked"));+ assert!(display.contains("(Testing lock)"));+ assert!(display.contains("git worktree unlock"));+ }++ #[test]+ fn test_git_error_worktree_locked_no_reason() {+ // When git outputs "locked" without a reason, we get Some("")+ let err = GitError::WorktreeLocked {+ branch: "feature".into(),+ reason: Some("".into()),+ };+ let display = err.to_string();+ assert!(display.contains("Cannot remove"));+ assert!(display.contains("feature"));+ assert!(display.contains(", worktree is locked"));+ assert!(+ !display.contains("locked ("),+ "should not show parentheses without reason"+ );+ assert!(display.contains("git worktree unlock"));+ }+#[test]fn test_git_error_conflicting_changes() {let err = GitError::ConflictingChanges {diff --git a/src/main.rs b/src/main.rsindex 2bc2afdba..a275f54e7 100644--- a/src/main.rs+++ b/src/main.rs@@ -32,8 +32,8 @@ use commands::{MergeOptions, RebaseResult, ResolutionContext, SquashResult, add_approvals, approve_hooks,clear_approvals, compute_worktree_path, handle_config_create, handle_config_show,handle_configure_shell, handle_hook_show, handle_init, handle_list, handle_merge,- handle_rebase, handle_remove, handle_remove_by_path, handle_remove_current, handle_show_theme,- handle_squash, handle_state_clear, handle_state_clear_all, handle_state_get, handle_state_set,+ handle_rebase, handle_remove, handle_remove_current, handle_show_theme, handle_squash,+ handle_state_clear, handle_state_clear_all, handle_state_get, handle_state_set,handle_state_show, handle_switch, handle_unconfigure_shell, resolve_worktree_arg, run_hook,step_commit, step_for_each,};@@ -1418,33 +1418,25 @@ fn main() {}// Remove other worktrees first (approval was handled at the gate)- for (path, branch) in &others {- if let Some(branch_name) = branch {- match handle_remove(- branch_name,- !delete_branch,- force_delete,- force,- background,- ) {- Ok(result) => {- handle_remove_output(&result, background, verify)?;- }- Err(e) => {- output::print(e.to_string())?;- all_errors.push(e);- }+ for (_path, branch) in &others {+ // Branch is always Some for non-current worktrees - detached worktrees+ // can only be referenced via "@" which resolves to current+ let branch_name = branch+ .as_ref()+ .expect("non-current worktree should have branch");+ match handle_remove(+ branch_name,+ !delete_branch,+ force_delete,+ force,+ background,+ ) {+ Ok(result) => {+ handle_remove_output(&result, background, verify)?;}- } else {- // Non-current worktree is detached - remove by path (no branch to delete)- match handle_remove_by_path(path, None, force, background) {- Ok(result) => {- handle_remove_output(&result, background, verify)?;- }- Err(e) => {- output::print(e.to_string())?;- all_errors.push(e);- }+ Err(e) => {+ output::print(e.to_string())?;+ all_errors.push(e);}}}diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex 8cf5de92d..427d02f2c 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -73,6 +73,87 @@ fn test_remove_dirty_working_tree(repo: TestRepo) {assert_cmd_snapshot!(make_snapshot_cmd(&repo, "remove", &[], None));}+#[rstest]+fn test_remove_locked_worktree(mut repo: TestRepo) {+ // Create a worktree and lock it+ let _worktree_path = repo.add_worktree("locked-feature");+ repo.lock_worktree("locked-feature", Some("Testing lock"));++ // Try to remove the locked worktree - should fail with helpful error+ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "remove",+ &["locked-feature"],+ None+ ));+}++#[rstest]+fn test_remove_locked_worktree_no_reason(mut repo: TestRepo) {+ // Create a worktree and lock it without a reason+ let _worktree_path = repo.add_worktree("locked-no-reason");+ repo.lock_worktree("locked-no-reason", None);++ // Try to remove - should show error without parenthesized reason+ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "remove",+ &["locked-no-reason"],+ None+ ));+}++#[rstest]+fn test_remove_locked_current_worktree(mut repo: TestRepo) {+ // Create a worktree, switch to it, and lock it+ let worktree_path = repo.add_worktree("locked-current");+ repo.lock_worktree("locked-current", Some("Do not remove"));++ // Try to remove current (locked) worktree - should fail+ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "remove",+ &[],+ Some(&worktree_path)+ ));+}++#[rstest]+fn test_remove_locked_detached_worktree(mut repo: TestRepo) {+ // Create a worktree, detach HEAD, and lock it+ let worktree_path = repo.add_worktree("locked-detached");+ repo.detach_head_in_worktree("locked-detached");+ repo.lock_worktree("locked-detached", Some("Detached and locked"));++ // Try to remove from within the locked detached worktree - should fail+ // This exercises the RemoveTarget::Current path for locked worktrees+ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "remove",+ &[],+ Some(&worktree_path)+ ));+}++#[rstest]+fn test_remove_locked_detached_multi(mut repo: TestRepo) {+ // Test multi-remove where current worktree (@ target) is locked and detached+ let _other_worktree = repo.add_worktree("other");+ let _locked_worktree = repo.add_worktree("locked-detached");+ repo.detach_head_in_worktree("locked-detached");+ repo.lock_worktree("locked-detached", Some("Locked detached"));++ // From the locked detached worktree, try to remove @ and other+ // The @ resolves to current (locked-detached) which is locked+ let locked_path = repo.worktree_path("locked-detached");+ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "remove",+ &["@", "other"],+ Some(locked_path)+ ));+}+#[rstest]fn test_remove_by_name_from_main(mut repo: TestRepo) {// Create a worktreediff --git a/tests/snapshots/integration__integration_tests__remove__remove_locked_current_worktree.snap b/tests/snapshots/integration__integration_tests__remove__remove_locked_current_worktree.snapnew file mode 100644index 000000000..b638b3419--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__remove_locked_current_worktree.snap@@ -0,0 +1,34 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ 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"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ PATH: "[PATH]"+ RUST_LOG: warn+ SOURCE_DATE_EPOCH: "1735776000"+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m✗[39m [31mCannot remove [1mlocked-current[22m, worktree is locked (Do not remove)[39m+[2m↳[22m [2mTo unlock, run [90mgit worktree unlock locked-current[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_locked_detached_multi.snap b/tests/snapshots/integration__integration_tests__remove__remove_locked_detached_multi.snapnew file mode 100644index 000000000..d347b1325--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__remove_locked_detached_multi.snap@@ -0,0 +1,37 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ - "@"+ - other+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ 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"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ PATH: "[PATH]"+ RUST_LOG: warn+ SOURCE_DATE_EPOCH: "1735776000"+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[36m◎ Removing [1mother[22m worktree & branch in background (same commit as [1mmain[22m,[39m [2m_[22m[36m)[39m+[31m✗[39m [31mCannot remove [1mrepo.locked-detached[22m, worktree is locked (Locked detached)[39m+[2m↳[22m [2mTo unlock, run [90mgit worktree unlock repo.locked-detached[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_locked_detached_worktree.snap b/tests/snapshots/integration__integration_tests__remove__remove_locked_detached_worktree.snapnew file mode 100644index 000000000..98a16af0d--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__remove_locked_detached_worktree.snap@@ -0,0 +1,34 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ 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"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ PATH: "[PATH]"+ RUST_LOG: warn+ SOURCE_DATE_EPOCH: "1735776000"+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m✗[39m [31mCannot remove [1mrepo.locked-detached[22m, worktree is locked (Detached and locked)[39m+[2m↳[22m [2mTo unlock, run [90mgit worktree unlock repo.locked-detached[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_locked_worktree.snap b/tests/snapshots/integration__integration_tests__remove__remove_locked_worktree.snapnew file mode 100644index 000000000..fc5a83dc4--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__remove_locked_worktree.snap@@ -0,0 +1,35 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ - locked-feature+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ 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"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ PATH: "[PATH]"+ RUST_LOG: warn+ SOURCE_DATE_EPOCH: "1735776000"+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m✗[39m [31mCannot remove [1mlocked-feature[22m, worktree is locked (Testing lock)[39m+[2m↳[22m [2mTo unlock, run [90mgit worktree unlock locked-feature[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_locked_worktree_no_reason.snap b/tests/snapshots/integration__integration_tests__remove__remove_locked_worktree_no_reason.snapnew file mode 100644index 000000000..48ecae678--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__remove_locked_worktree_no_reason.snap@@ -0,0 +1,35 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ - locked-no-reason+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ 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"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ PATH: "[PATH]"+ RUST_LOG: warn+ SOURCE_DATE_EPOCH: "1735776000"+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m✗[39m [31mCannot remove [1mlocked-no-reason[22m, worktree is locked[39m+[2m↳[22m [2mTo unlock, run [90mgit worktree unlock locked-no-reason[39m[22m