Skip to content

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

Report removal failures with the surviving checkout and branch state (#4457)

Maximilian Roos16d52e58b012
diff --git a/src/git/error.rs b/src/git/error.rs
index de25d8fb5..acc6e26a6 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -529,6 +529,12 @@ pub enum GitError {
directory_remains: bool,
work: StaleWorktreeWork,
},
+ /// Branch deletion failed, possibly after its checkout was removed.
+ BranchDeletionFailed {
+ branch: String,
+ removed_worktree: Option<PathBuf>,
+ error: anyhow::Error,
+ },
RemoteOnlyBranch {
branch: String,
remote: String,
@@ -573,7 +579,7 @@ pub enum GitError {
branch: String,
path: PathBuf,
error: anyhow::Error,
- /// Top-level entries remaining in the directory (for "Directory not empty" diagnostics)
+ /// Top-level entries left after Git attempted to remove the directory.
remaining_entries: Option<Vec<String>>,
},
CannotRemoveMainWorktree,
@@ -758,7 +764,8 @@ pub enum GitError {
impl std::error::Error for GitError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
- Self::WorktreeRemovalFailed { error, .. } => Some(error.as_ref()),
+ Self::WorktreeRemovalFailed { error, .. }
+ | Self::BranchDeletionFailed { error, .. } => Some(error.as_ref()),
_ => None,
}
}
@@ -886,6 +893,18 @@ impl GitError {
),
},
+ GitError::BranchDeletionFailed {
+ branch,
+ removed_worktree,
+ ..
+ } => match removed_worktree {
+ Some(path) => cformat!(
+ "Worktree removed @ <bold>{}</>; failed to delete branch <bold>{branch}</>",
+ format_path_for_display(path)
+ ),
+ None => cformat!("Failed to delete branch <bold>{branch}</>"),
+ },
+
GitError::RemoteOnlyBranch { branch, remote } => {
cformat!("Branch <bold>{branch}</> exists only on remote ({remote}/{branch})")
}
@@ -1388,6 +1407,15 @@ impl GitError {
)
}
+ GitError::BranchDeletionFailed { error, .. } => {
+ let title = self.title();
+ write!(
+ f,
+ "{}",
+ format_error_block(error_message(&title), &error.display_message())
+ )
+ }
+
GitError::WorktreeRemovalFailed {
error,
remaining_entries,
@@ -1411,14 +1439,8 @@ impl GitError {
hint_message(cformat!("Remaining in directory: <underline>{listing}</>"))
)?;
}
- // Fragile by necessity: matches git's English, which is
- // localized and could be reworded. The text is `git worktree
- // remove`'s own stderr — the failure never passes through a
- // Rust `io::Error`, and git offers no porcelain or exit code
- // that separates ENOTEMPTY from the rest. `remaining_entries`
- // is not a substitute either: a permission-denied failure also
- // leaves entries behind, and this hint is only right for
- // ENOTEMPTY. A miss costs one hint.
+ // Git offers no structured discriminator for ENOTEMPTY. Matching
+ // its localized stderr affects this optional process hint only.
if error.contains("not empty") {
write!(
f,
@@ -2591,6 +2613,21 @@ mod tests {
);
}
+ #[test]
+ fn branch_deletion_error_preserves_cancellation() {
+ let error: anyhow::Error = GitError::BranchDeletionFailed {
+ branch: "feature".into(),
+ removed_worktree: None,
+ error: WorktrunkError::Interrupted {
+ signal: 15,
+ hint: None,
+ }
+ .into(),
+ }
+ .into();
+ assert_eq!(error.interrupt_signal(), Some(15));
+ }
+
#[test]
fn test_format_error_block() {
let header = "Error occurred".to_string();
diff --git a/src/git/remove.rs b/src/git/remove.rs
index 772bb6bad..0d028a5d7 100644
--- a/src/git/remove.rs
+++ b/src/git/remove.rs
@@ -344,10 +344,9 @@ pub struct RemoveOptions {
/// Result of [`remove_worktree_with_cleanup`].
///
/// `branch_result` is `None` when deletion was skipped (no branch supplied, or
-/// `deletion_mode.should_keep()`). Otherwise it carries the raw result so
-/// callers can decide how to surface branch-deletion failures — the
-/// foreground removal path reports them to the user, the TUI picker ignores
-/// them (best-effort), and external tools can do whatever fits.
+/// `deletion_mode.should_keep()`). A deletion failure carries
+/// [`GitError::BranchDeletionFailed`] with the removed worktree's path.
+/// Callers finish teardown and cleanup before propagating it.
///
/// `staged_path` is `Some` only on the fast path. Callers are responsible for
/// cleaning up the staged directory; `wt remove` does this with a detached
@@ -372,8 +371,8 @@ pub struct RemovalOutput {
/// `git worktree remove` also fails.
/// - Branch-deletion errors are captured in
/// [`RemovalOutput::branch_result`] rather than returned — worktree removal
-/// is considered the primary operation, and callers can decide how to
-/// handle a residual branch-deletion failure.
+/// is already complete. Callers finish teardown and cleanup before
+/// propagating the contextual deletion failure.
pub fn remove_worktree_with_cleanup(
repo: &Repository,
snapshot: &crate::git::RefSnapshot,
@@ -395,13 +394,23 @@ pub fn remove_worktree_with_cleanup(
&& !options.deletion_mode.should_keep()
{
let target = options.target_branch.as_deref().unwrap_or("HEAD");
- Some(delete_branch_if_safe(
- repo,
- snapshot,
- branch,
- target,
- options.deletion_mode.is_force(),
- ))
+ Some(
+ delete_branch_if_safe(
+ repo,
+ snapshot,
+ branch,
+ target,
+ options.deletion_mode.is_force(),
+ )
+ .map_err(|error| {
+ GitError::BranchDeletionFailed {
+ branch: branch.to_owned(),
+ removed_worktree: Some(worktree_path.to_path_buf()),
+ error,
+ }
+ .into()
+ }),
+ )
} else {
None
};
diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rs
index 0efc6ec44..5dd9f85b7 100644
--- a/src/git/repository/worktrees.rs
+++ b/src/git/repository/worktrees.rs
@@ -21,6 +21,27 @@ use crate::path::{format_path_for_display, paths_match};
use crate::shell_exec::Cmd;
use crate::styling::{eprintln, format_with_gutter, hint_message, warning_message};
+/// List top-level entries remaining in a directory after a failed removal.
+///
+/// Returns None if the directory doesn't exist, can't be read, or is empty.
+/// Entries are sorted, with directories suffixed with `/`.
+fn list_remaining_entries(path: &Path) -> Option<Vec<String>> {
+ let mut entries: Vec<String> = std::fs::read_dir(path)
+ .ok()?
+ .filter_map(|e| {
+ let e = e.ok()?;
+ let name = e.file_name().to_string_lossy().into_owned();
+ if e.file_type().ok()?.is_dir() {
+ Some(format!("{name}/"))
+ } else {
+ Some(name)
+ }
+ })
+ .collect();
+ entries.sort();
+ (!entries.is_empty()).then_some(entries)
+}
+
impl Repository {
/// List all worktrees for this repository.
///
@@ -405,7 +426,18 @@ impl Repository {
tracing::debug!("Using --force for worktree removal due to initialized submodules");
}
- self.run_command(&args)?;
+ // Capture the display identity before Git may remove its `.git` entry.
+ let branch = self
+ .worktree_at(path)
+ .branch()?
+ .unwrap_or_else(|| crate::git::path_dir_name(path).to_string());
+ self.run_command(&args)
+ .map_err(|error| GitError::WorktreeRemovalFailed {
+ branch,
+ path: path.to_path_buf(),
+ error,
+ remaining_entries: list_remaining_entries(path),
+ })?;
Ok(())
}
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index da0723609..d534723e8 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -25,11 +25,9 @@ use crate::commands::worktree::{
BranchFate, RemovalPlan, RetainedReason, SharedBranchCheckout, SwitchBranchInfo, SwitchResult,
};
use worktrunk::config::UserConfig;
-use worktrunk::git::ErrorExt;
use worktrunk::git::GitError;
use worktrunk::git::IntegrationReason;
use worktrunk::git::Repository;
-use worktrunk::git::path_dir_name;
use worktrunk::git::{
BranchDeletionMode, BranchDeletionOutcome, BranchDeletionResult, RemoveOptions,
delete_branch_if_safe, execute_branch_deletion, remove_worktree_with_cleanup,
@@ -39,8 +37,8 @@ use worktrunk::path::{canonicalize_with_parents, format_path_for_display};
use worktrunk::progress::{Progress, format_stats_paren};
use worktrunk::remove_dir::remove_dir_with_progress;
use worktrunk::styling::{
- FormattedMessage, eprintln, error_message, format_with_gutter, hint_message, info_message,
- progress_message, success_message, suggest_command, verbosity, warning_message,
+ FormattedMessage, eprintln, hint_message, info_message, progress_message, success_message,
+ suggest_command, verbosity, warning_message,
};
use super::{CommandFailure, CommandResult};
@@ -256,14 +254,14 @@ fn execute_instant_removal_or_fallback(
let fate = if let Some(branch) = branch_name
&& !deletion_mode.should_keep()
{
- let result = execute_branch_deletion(
+ delete_removed_worktree_branch(
repo,
branch,
- target_branch.unwrap_or("HEAD"),
- deletion_mode.is_force(),
- );
- warn_if_branch_retained(branch, &result, planner_expected_retention);
- result.map(|result| BranchFate::from_outcome(&result.outcome))
+ worktree_path,
+ target_branch,
+ deletion_mode,
+ planner_expected_retention,
+ )
} else {
Ok(BranchFate::NotAttempted)
};
@@ -291,9 +289,10 @@ fn execute_instant_removal_or_fallback(
let fate = if let Some(branch) = branch_name
&& !deletion_mode.should_keep()
{
- delete_branch_in_synchronous_fallback(
+ delete_removed_worktree_branch(
repo,
branch,
+ worktree_path,
target_branch,
deletion_mode,
planner_expected_retention,
@@ -349,17 +348,12 @@ fn execute_instant_removal_or_fallback(
}
}
-/// Delete the just-removed worktree's branch in the synchronous fallback path.
-///
-/// Only `wt step prune` reaches this (via `SynchronousForNonCurrent`). Mirrors
-/// the fast path above via `execute_branch_deletion` (fresh refs + CAS), so
-/// squash-merged / patch-id-matched branches that prune accepted as candidates
-/// are deleted here too — a plain `git branch -d` would refuse them on
-/// reachability from HEAD alone and leave the branch behind while the worktree
-/// was already removed. The caller filters out `None` branches and `Keep` modes.
-fn delete_branch_in_synchronous_fallback(
+/// Delete a removed worktree's branch, retaining its path on hard failures.
+/// The fast staging path and synchronous fallback share this producer.
+fn delete_removed_worktree_branch(
repo: &Repository,
branch: &str,
+ worktree_path: &Path,
target_branch: Option<&str>,
deletion_mode: BranchDeletionMode,
planner_expected_retention: bool,
@@ -371,7 +365,16 @@ fn delete_branch_in_synchronous_fallback(
deletion_mode.is_force(),
);
warn_if_branch_retained(branch, &result, planner_expected_retention);
- result.map(|result| BranchFate::from_outcome(&result.outcome))
+ result
+ .map(|result| BranchFate::from_outcome(&result.outcome))
+ .map_err(|error| {
+ GitError::BranchDeletionFailed {
+ branch: branch.to_owned(),
+ removed_worktree: Some(worktree_path.to_path_buf()),
+ error,
+ }
+ .into()
+ })
}
/// Surface the residual branch when `delete_branch_if_safe` returned an
@@ -514,27 +517,6 @@ pub(crate) fn delete_branch_from_detached_fallback(
Ok(())
}
-/// List top-level entries remaining in a directory after a failed removal.
-///
-/// Returns None if the directory doesn't exist, can't be read, or is empty.
-/// Entries are sorted, with directories suffixed with `/`.
-fn list_remaining_entries(path: &Path) -> Option<Vec<String>> {
- let mut entries: Vec<String> = std::fs::read_dir(path)
- .ok()?
- .filter_map(|e| {
- let e = e.ok()?;
- let name = e.file_name().to_string_lossy().into_owned();
- if e.file_type().ok()?.is_dir() {
- Some(format!("{name}/"))
- } else {
- Some(name)
- }
- })
- .collect();
- entries.sort();
- (!entries.is_empty()).then_some(entries)
-}
-
// ============================================================================
// Switch Output Handlers
// ============================================================================
@@ -850,26 +832,20 @@ fn retained_checked_out_branch_message(
/// refused because the ref moved (a hook or concurrent process advanced it).
/// Callers surface this with [`retained_raced_branch_message`], not the
/// unmerged hint, so it is *not* folded into `show_unmerged_hint`.
-/// - `Err(e)`: Git command failed - show warning with actual error
+/// - `Err(e)`: return one contextual diagnostic for the caller to render.
fn handle_branch_deletion_result(
result: anyhow::Result<BranchDeletionResult>,
branch_name: &str,
) -> anyhow::Result<BranchDeletionDisplay> {
- match result {
- Ok(result) => Ok(BranchDeletionDisplay {
- show_unmerged_hint: matches!(result.outcome, BranchDeletionOutcome::NotDeleted),
- result,
- }),
- Err(e) => {
- // Git command failed - this is an error (we decided to delete but couldn't)
- eprintln!(
- "{}",
- error_message(cformat!("Failed to delete branch <bold>{branch_name}</>"))
- );
- eprintln!("{}", format_with_gutter(&e.display_message(), None));
- Err(e)
- }
- }
+ let result = result.map_err(|error| GitError::BranchDeletionFailed {
+ branch: branch_name.to_owned(),
+ removed_worktree: None,
+ error,
+ })?;
+ Ok(BranchDeletionDisplay {
+ show_unmerged_hint: matches!(result.outcome, BranchDeletionOutcome::NotDeleted),
+ result,
+ })
}
struct FlagNote {
@@ -1203,8 +1179,8 @@ pub fn execute_user_command(
/// than what the plan intended — the prune summary and `--format=json` both
/// read it. Worktree-removal failures and hard branch-deletion failures
/// propagate as `Err`; an intentionally retained, unmerged, or moved branch
-/// is a fate. Silent worktree removal keeps its best-effort deletion contract,
-/// reporting a hard branch failure as a retained fate to the picker.
+/// is a fate. Synchronous branch failures carry the worktree removal context,
+/// including silent picker removal; detached fallback failures go to its log.
///
/// Approval is handled at the gate (command entry point), not here. The
/// `announcer`'s `show_branch` setting (set by the caller) controls whether
@@ -1646,25 +1622,20 @@ impl RemovalDisplayInfo {
/// Build display info from actual deletion result (foreground mode).
fn from_branch_result(
- branch_deletion: Option<anyhow::Result<BranchDeletionResult>>,
- branch_name: &str,
+ branch_deletion: Option<BranchDeletionResult>,
pre_computed_integration: Option<IntegrationReason>,
target_branch: Option<&str>,
force_worktree: bool,
- ) -> anyhow::Result<Self> {
+ ) -> Self {
let branch_was_integrated = pre_computed_integration.is_some();
let (outcome, integration_target, show_unmerged_hint) = match branch_deletion {
Some(result) => {
- let deletion = handle_branch_deletion_result(result, branch_name)?;
- // Only use integration_target for display if we had a real target (not "HEAD" fallback)
- let display_target =
- target_branch.map(|_| deletion.result.integration_target.clone());
- (
- deletion.result.outcome,
- display_target,
- deletion.show_unmerged_hint,
- )
+ // Only display a real target, not the "HEAD" fallback.
+ let display_target = target_branch.map(|_| result.integration_target);
+ let show_unmerged_hint =
+ matches!(result.outcome, BranchDeletionOutcome::NotDeleted);
+ (result.outcome, display_target, show_unmerged_hint)
}
None => (
BranchDeletionOutcome::NotDeleted,
@@ -1673,13 +1644,13 @@ impl RemovalDisplayInfo {
),
};
- Ok(Self {
+ Self {
outcome,
integration_target,
branch_was_integrated,
show_unmerged_hint,
force_worktree,
- })
+ }
}
/// Whether the branch will be/was deleted.
@@ -1950,13 +1921,7 @@ fn handle_detached_removed_worktree_output(
target_branch: ctx.target_branch.map(String::from),
force_worktree: ctx.force_worktree,
},
- )
- .map_err(|err| GitError::WorktreeRemovalFailed {
- branch: path_dir_name(ctx.worktree_path).to_string(),
- path: ctx.worktree_path.to_path_buf(),
- remaining_entries: list_remaining_entries(ctx.worktree_path),
- error: err,
- })?;
+ )?;
let (files, bytes) = output
.staged_path
.as_deref()
@@ -2038,13 +2003,7 @@ fn handle_named_removed_worktree_foreground(
target_branch: ctx.target_branch.map(String::from),
force_worktree: ctx.force_worktree,
},
- )
- .map_err(|err| GitError::WorktreeRemovalFailed {
- branch: branch_name.into(),
- path: ctx.worktree_path.to_path_buf(),
- remaining_entries: list_remaining_entries(ctx.worktree_path),
- error: err,
- })?;
+ )?;
let stats = output
.staged_path
.as_deref()
@@ -2056,13 +2015,13 @@ fn handle_named_removed_worktree_foreground(
let finish = (|| -> anyhow::Result<()> {
spawn_hooks_after_remove(repo, ctx, Some(branch_name), announcer)?;
+ let branch_result = output.branch_result.transpose()?;
let display_info = RemovalDisplayInfo::from_branch_result(
- output.branch_result,
- branch_name,
+ branch_result,
ctx.integration_reason,
ctx.target_branch,
ctx.force_worktree,
- )?;
+ );
display_info.print_message(branch_name, true, Some(stats))?;
display_info.print_hints(branch_name, ctx.deletion_mode, ctx.integration_reason)?;
@@ -2218,9 +2177,7 @@ fn handle_removed_worktree_output(
/// This does the synchronous git worktree removal and registers `post-remove` /
/// `post-switch` hooks onto `announcer`, but with no progress/success message
/// and no trash-cleanup spinner — `eprintln!` while skim owns the terminal
-/// would corrupt the frame. A removal failure propagates as-is (the picker logs
-/// it); there's no TTY to render the foreground path's nicer "remaining
-/// entries" error against.
+/// would corrupt the frame. Removal failures propagate to the picker.
fn remove_removed_worktree_silently(
repo: &Repository,
ctx: &WorktreeRemovalContext<'_>,
@@ -2240,15 +2197,15 @@ fn remove_removed_worktree_silently(
let _ = std::fs::remove_dir_all(&staged);
}
- // A best-effort deletion's failure is deliberately not narrated here
- // (no terminal to narrate to); the fate still reports the branch as
- // surviving.
- let fate = BranchFate::from_result(output.branch_result.as_ref());
-
// Post-remove (and post-switch when the picker cd'd away) hooks — registered
// onto the caller's announcer, which `flush`es after this returns.
+ let fate = BranchFate::from_result(output.branch_result.as_ref());
spawn_hooks_after_remove(repo, ctx, ctx.branch_name, announcer)
.map_err(|error| CommandFailure::with_result(error, fate))?;
+ output
+ .branch_result
+ .transpose()
+ .map_err(|error| CommandFailure::with_result(error, fate))?;
Ok(fate)
}
@@ -2395,6 +2352,52 @@ mod tests {
use super::*;
use insta::assert_snapshot;
+ /// Silent removal reports a hard ref failure after removing the checkout.
+ #[test]
+ fn silent_branch_failure_preserves_removal_context() {
+ use crate::commands::repository_ext::{RemoveTarget, RepositoryCliExt};
+
+ let mut test = worktrunk::testing::TestRepo::with_initial_commit();
+ let path = test.add_worktree("feature");
+ let repo = Repository::at(test.path()).unwrap();
+ let plan = repo
+ .prepare_worktree_removal(
+ RemoveTarget::WorktreePath(path.clone()),
+ BranchDeletionMode::SafeDelete,
+ false,
+ test.path(),
+ None,
+ None,
+ )
+ .unwrap();
+ std::fs::write(
+ repo.git_common_dir().join("refs/heads/feature.lock"),
+ "another writer",
+ )
+ .unwrap();
+ let mut announcer = HookAnnouncer::new(&repo, false);
+ let error = handle_remove_output(
+ &plan,
+ RemovalExecution::Silent,
+ ForegroundStdin::Inherit,
+ &ApprovedHookPlan::empty(),
+ true,
+ &mut announcer,
+ )
+ .unwrap_err();
+ assert_eq!(
+ error.result.as_deref(),
+ Some(&BranchFate::Retained(RetainedReason::Failed))
+ );
+ assert!(matches!(
+ error.error.downcast_ref::<GitError>(),
+ Some(GitError::BranchDeletionFailed { branch, removed_worktree: Some(removed), .. })
+ if branch == "feature" && removed == &path
+ ));
+ assert!(!path.exists());
+ assert!(repo.branch("feature").exists_locally().unwrap());
+ }
+
/// Exercises each arm of [`warn_if_branch_retained`] for coverage and
/// to pin the suppression rule. Output goes to stderr and isn't captured
/// here — the assertion is that the call doesn't panic on any arm.
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 1b4e34ce0..943f5a203 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -6376,6 +6376,62 @@ fn test_force_remove_interrupted_status_preserves_worktrees(
assert!(!stderr.contains("Removing later-worktree"));
}
+/// A failed branch mutation is reported once after removal, with teardown hooks
+/// still running. Branch-only failures must not claim a checkout was removed.
+#[rstest]
+#[case::foreground(true, true)]
+#[case::background(false, true)]
+#[case::branch_only(true, false)]
+fn test_remove_branch_deletion_failure_context(
+ mut repo: TestRepo,
+ #[case] foreground: bool,
+ #[case] with_worktree: bool,
+) {
+ repo.write_project_config("post-remove = 'printf complete > removed-marker'");
+ repo.commit("Add post-remove hook");
+ let worktree = if with_worktree {
+ Some(repo.add_worktree("feature"))
+ } else {
+ repo.create_branch("feature");
+ None
+ };
+ fs::write(
+ repo.root_path().join(".git/refs/heads/feature.lock"),
+ "another writer",
+ )
+ .unwrap();
+ let mut command = repo.wt_command();
+ command.args(["remove", "feature", "--yes"]);
+ if foreground {
+ command.arg("--foreground");
+ }
+ let output = command.output().unwrap();
+ let stderr = String::from_utf8(output.stderr).unwrap();
+ let plain = stderr.ansi_strip();
+ assert_eq!(output.status.code(), Some(1), "{plain}");
+ assert_eq!(
+ plain.contains("Worktree removed @"),
+ with_worktree,
+ "{plain}"
+ );
+ assert_eq!(
+ plain.matches("failed to delete branch").count()
+ + plain.matches("Failed to delete branch").count(),
+ 1,
+ "{plain}"
+ );
+ assert_eq!(plain.matches("cannot lock ref").count(), 1, "{plain}");
+ assert!(!repo.git_output(&["branch", "--list", "feature"]).is_empty());
+ if let Some(worktree) = worktree {
+ assert!(!worktree.exists());
+ crate::common::wait_for_file_content(&repo.root_path().join("removed-marker"));
+ assert_eq!(
+ fs::read_to_string(repo.root_path().join("removed-marker")).unwrap(),
+ "complete"
+ );
+ }
+}
+
/// With fsmonitor configured, a file written while the daemon shuts down is
/// refused by a rescan after the stop. The shim stands in for the daemon and
/// keeps every other Git command from starting a real one.
@@ -6578,3 +6634,43 @@ fn test_remove_no_argument_in_moved_worktree_refuses(mut repo: TestRepo) {
String::from_utf8_lossy(&status.stderr)
);
}
+
+/// A failed destructive Git command reports the checkout and entries that
+/// survive it. A registration lock reaches Git's actual removal failure.
+#[rstest]
+fn test_remove_worktree_git_failure_preserves_context(mut repo: TestRepo) {
+ use worktrunk::git::{GitError, Repository};
+
+ let path = repo.add_worktree("locked-worktree");
+ repo.run_git(&["worktree", "lock", path.to_str().unwrap()]);
+ fs::create_dir(path.join("remaining-directory")).unwrap();
+ fs::write(path.join("remaining-file"), "surviving data").unwrap();
+ let repository = Repository::at(repo.root_path()).unwrap();
+ let error = repository.remove_worktree(&path, true).unwrap_err();
+
+ let Some(GitError::WorktreeRemovalFailed {
+ branch,
+ path: failed_path,
+ remaining_entries: Some(entries),
+ ..
+ }) = error.downcast_ref::<GitError>()
+ else {
+ panic!("expected contextual removal failure: {error:?}");
+ };
+ assert_eq!(branch, "locked-worktree");
+ assert_eq!(failed_path, &path);
+ assert!(entries.iter().any(|entry| entry == "remaining-directory/"));
+ assert!(entries.iter().any(|entry| entry == "remaining-file"));
+ assert!(entries.windows(2).all(|entries| entries[0] <= entries[1]));
+ assert_eq!(
+ fs::read_to_string(path.join("remaining-file")).unwrap(),
+ "surviving data"
+ );
+ assert!(path.join(".git").exists());
+ assert!(
+ repository
+ .branch("locked-worktree")
+ .exists_locally()
+ .unwrap()
+ );
+}
diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rs
index 0a2b4c734..b76ecbf78 100644
--- a/tests/integration_tests/step_prune.rs
+++ b/tests/integration_tests/step_prune.rs
@@ -244,7 +244,7 @@ fn test_prune_removes_multiple_detached(mut repo: TestRepo) {
/// fallback when the rename-into-trash fast path is blocked.
///
/// A detached worktree has no branch, so the fallback's branch deletion is a
-/// no-op — this covers that arm of `delete_branch_in_synchronous_fallback`.
+/// no-op — this covers that arm of `delete_removed_worktree_branch`.
#[rstest]
fn test_prune_detached_worktree_rename_fallback(mut repo: TestRepo) {
repo.commit("initial");
@@ -3211,7 +3211,9 @@ fn test_prune_removal_failure_aborts_remaining_queue(repo: TestRepo) {
"a failed removal must fail the run:\n{stderr}"
);
assert!(
- stderr.contains("removing branch abort-a"),
+ stderr
+ .ansi_strip()
+ .contains("Failed to delete branch abort-a"),
"the error should carry the failing candidate's context:\n{stderr}"
);
assert!(
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_continues_dirty_foreground.snap b/tests/snapshots/integration__integration_tests__remove__remove_continues_dirty_foreground.snap
index 068202f05..6dd93d2c7 100644
--- a/tests/snapshots/integration__integration_tests__remove__remove_continues_dirty_foreground.snap
+++ b/tests/snapshots/integration__integration_tests__remove__remove_continues_dirty_foreground.snap
@@ -5,9 +5,9 @@ expression: stderr
◎ Running pre-remove project hook @ _REPO_.failed-a
  case 'failed-a' in failed-*) printf uncommitted > dirty.txt ;; esac
◎ Removing failed-a worktree...
-✗ Failed to remove worktree for failed-a @ _REPO_.failed-a
-  Cannot remove worktree: failed-a has uncommitted changes
-↳ Remaining in directory: .config/, .git, .gitattributes, dirty.txt, file.txt
+✗ Cannot remove worktree: failed-a has uncommitted changes
+  ?? dirty.txt
+↳ Commit or run git stash -u in the dirty worktree first, or to lose uncommitted changes, run wt remove --force failed-a
◎ Running pre-remove project hook @ _REPO_.valid
  case 'valid' in failed-*) printf uncommitted > dirty.txt ;; esac
◎ Removing valid worktree...
@@ -15,9 +15,9 @@ expression: stderr
◎ Running pre-remove project hook @ _REPO_.failed-b
  case 'failed-b' in failed-*) printf uncommitted > dirty.txt ;; esac
◎ Removing failed-b worktree...
-✗ Failed to remove worktree for failed-b @ _REPO_.failed-b
-  Cannot remove worktree: failed-b has uncommitted changes
-↳ Remaining in directory: .config/, .git, .gitattributes, dirty.txt, file.txt
+✗ Cannot remove worktree: failed-b has uncommitted changes
+  ?? dirty.txt
+↳ Commit or run git stash -u in the dirty worktree first, or to lose uncommitted changes, run wt remove --force failed-b
○ No worktree found for branch branch-only
✓ Removed branch branch-only (same commit as main, _)
◎ Running pre-remove project hook