Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(remove): add TTY progress spinner to --foreground (#2420)
Maximilian Roos810cdc66369c
diff --git a/.claude/skills/writing-user-outputs/SKILL.md b/.claude/skills/writing-user-outputs/SKILL.mdindex 840f8d5e0..d0eeb3d06 100644--- a/.claude/skills/writing-user-outputs/SKILL.md+++ b/.claude/skills/writing-user-outputs/SKILL.md@@ -600,11 +600,12 @@ message for batch operations, no progress before slow operations.When per-item `progress_message`s don't fit — recursive copy of thousands offiles, a long subprocess with no useful streaming output — a stderr spinner-keeps the user oriented. See `src/copy_progress.rs` (`CopyProgress`) for the-pattern: TTY-gate, skip when `verbosity() >= 1` or `--dry-run`, ≥300 ms-startup delay so fast ops stay silent, IEC bytes (KiB/MiB), clear the line-before printing the summary, and have the summary repeat any counters the-spinner displayed.+keeps the user oriented. See `src/progress.rs` (`Progress`) for the pattern:+the verb (`"Copying"`, `"Removing"`) is fixed at `Progress::start(verb)`,+TTY-gate, skip when `verbosity() >= 1` or `--dry-run`, ≥300 ms startup delay+so fast ops stay silent, IEC bytes (KiB/MiB), clear the line before printing+the summary, and have the summary repeat any counters the spinner displayed+(use `format_stats_paren` for the gray `(N files · X MiB)` suffix).## Defer Non-Essential Work Until After Primary Outputdiff --git a/benches/cow_copy.rs b/benches/cow_copy.rsindex a010f54eb..14a2588f8 100644--- a/benches/cow_copy.rs+++ b/benches/cow_copy.rs@@ -16,7 +16,7 @@ use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};use std::path::Path;use tempfile::TempDir;use worktrunk::copy::copy_dir_recursive;-use worktrunk::copy_progress::CopyProgress;+use worktrunk::progress::Progress;/// Create a narrow directory structure mimicking a Rust target/ directory.///@@ -148,7 +148,7 @@ fn bench_helper(b.iter(|| {let dest = temp.path().join(format!("copy_p_{}", iter));iter += 1;- copy_dir_recursive(src, &dest, false, &CopyProgress::disabled()).unwrap();+ copy_dir_recursive(src, &dest, false, &Progress::disabled()).unwrap();std::fs::remove_dir_all(&dest).ok();});},diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 78b05b236..c1570ae04 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -26,9 +26,9 @@ use rayon::prelude::*;use worktrunk::HookType;use worktrunk::config::{CopyIgnoredConfig, UserConfig};use worktrunk::copy::{copy_dir_recursive, copy_leaf};-use worktrunk::copy_progress::{CopyProgress, format_bytes};use worktrunk::git::{Repository, WorktreeInfo};use worktrunk::path::format_path_for_display;+use worktrunk::progress::{Progress, format_bytes};use worktrunk::shell_exec::Cmd;use worktrunk::styling::{eprintln, format_with_gutter, hint_message, info_message, progress_message, success_message,@@ -808,9 +808,9 @@ pub fn step_copy_ignored(// `start` auto-detects the TTY; verbose/dry-run already print enough.let progress = if verbose >= 1 || dry_run {- CopyProgress::disabled()+ Progress::disabled()} else {- CopyProgress::start()+ Progress::start("Copying")};let mut copied_count = 0usize;@@ -840,7 +840,7 @@ pub fn step_copy_ignored(if let Some(bytes) = copy_leaf(src_entry, &dest_entry, force)? {copied_count += 1;copied_bytes += bytes;- progress.file_copied(bytes);+ progress.record(bytes);}}}@@ -921,7 +921,7 @@ fn move_entry(src: &Path, dest: &Path, is_dir: bool) -> anyhow::Result<()> {/// Copy then delete — fallback when `rename` fails with EXDEV (cross-device).fn copy_and_remove(src: &Path, dest: &Path, is_dir: bool) -> anyhow::Result<()> {if is_dir {- copy_dir_recursive(src, dest, true, &CopyProgress::disabled())?;+ copy_dir_recursive(src, dest, true, &Progress::disabled())?;fs::remove_dir_all(src).context(format!("removing source directory {}", src.display()))?;} else {copy_leaf(src, dest, true)?;diff --git a/src/copy.rs b/src/copy.rsindex 9ac33b7a8..2b8582507 100644--- a/src/copy.rs+++ b/src/copy.rs@@ -12,9 +12,9 @@//! Callers that want low-priority I/O (e.g. `step_copy_ignored`) should call//! [`crate::priority::lower_current_process`] before starting work.//!-//! Callers that want a TTY progress spinner pass a [`CopyProgress`] — every-//! successful leaf copy calls `progress.file_copied(bytes)`. Non-interactive-//! callers pass [`CopyProgress::disabled`] for a zero-overhead no-op.+//! Callers that want a TTY progress spinner pass a [`Progress`] — every+//! successful leaf copy calls `progress.record(bytes)`. Non-interactive+//! callers pass [`Progress::disabled`] for a zero-overhead no-op.use std::fs;use std::io::ErrorKind;@@ -25,7 +25,7 @@ use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};use anyhow::Context;use rayon::prelude::*;-use crate::copy_progress::CopyProgress;+use crate::progress::Progress;/// Capped at 4 threads to avoid saturating the CPU — the global rayon pool is/// much larger (2× CPU cores, tuned for network I/O in `wt list`).@@ -103,14 +103,14 @@ struct CopyLeaf {////// When `force` is true, existing files and symlinks at the destination are/// removed before copying. `progress` receives per-file callbacks; pass-/// [`CopyProgress::disabled`] for a zero-overhead no-op.+/// [`Progress::disabled`] for a zero-overhead no-op.////// Returns `(files_copied, bytes_copied)` — counts exclude skipped entries.pub fn copy_dir_recursive(src: &Path,dest: &Path,force: bool,- progress: &CopyProgress,+ progress: &Progress,) -> anyhow::Result<(usize, u64)> {// Phase 1: Walk directories iteratively, creating dest dirs and collecting leaves.let mut leaves = Vec::new();@@ -153,7 +153,7 @@ pub fn copy_dir_recursive(if let Some(bytes) = copy_leaf(&leaf.src, &leaf.dest, force)? {copied_files.fetch_add(1, Ordering::Relaxed);copied_bytes.fetch_add(bytes, Ordering::Relaxed);- progress.file_copied(bytes);+ progress.record(bytes);}Ok(())})diff --git a/src/lib.rs b/src/lib.rsindex 0b40ac3f2..8466ce677 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -11,11 +11,12 @@ pub mod cache;pub mod command_log;pub mod config;pub mod copy;-pub mod copy_progress;pub mod docs;pub mod git;pub mod path;pub mod priority;+pub mod progress;+pub mod remove_dir;pub mod shell;pub mod shell_exec;pub mod styling;diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex d4d3a263f..938628551 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -29,9 +29,11 @@ use worktrunk::git::{remove_worktree_with_cleanup, stage_worktree_removal,};use worktrunk::path::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, warning_message,+ progress_message, success_message, suggest_command, verbosity, warning_message,};use super::shell_integration::{@@ -39,6 +41,32 @@ use super::shell_integration::{shell_integration_hint, should_show_explicit_path_hint,};+// ============================================================================+// Foreground Trash Cleanup+// ============================================================================++/// Walk the staged trash directory, unlinking files with a TTY spinner.+///+/// Used by the foreground removal path after `remove_worktree_with_cleanup`+/// renames the worktree into `<git-common-dir>/wt/trash/`. The spinner shows+/// `⠼ Removing N files · X MiB` while the walk proceeds; the returned counts+/// drive the post-op summary so the success message matches the spinner.+///+/// Suppresses the spinner when stderr isn't a TTY (auto-detected by+/// `Progress::start`) or when verbosity ≥ 1 (verbose mode prefers structured+/// output over live updates). The walk itself is best-effort — see+/// [`remove_dir_with_progress`].+fn cleanup_staged_with_progress(staged: &Path) -> (usize, u64) {+ let progress = if verbosity() >= 1 {+ Progress::disabled()+ } else {+ Progress::start("Removing")+ };+ let result = remove_dir_with_progress(staged, &progress);+ progress.finish();+ result+}+// ============================================================================// Background Removal Helpers// ============================================================================@@ -1034,7 +1062,18 @@ impl RemovalDisplayInfo {}/// Print the removal message (progress for background, success for foreground).- fn print_message(&self, branch_name: &str, foreground: bool) -> anyhow::Result<()> {+ ///+ /// `stats` carries the trash-cleanup file/byte counts surfaced by the+ /// foreground spinner (see `remove_dir_with_progress`). Pass `None` for+ /// the background path — those don't run a spinner and shouldn't show+ /// stats. The `(N files · X MiB)` suffix is gray, matching the+ /// "stats parentheses" convention in the user-output skill.+ fn print_message(+ &self,+ branch_name: &str,+ foreground: bool,+ stats: Option<(usize, u64)>,+ ) -> anyhow::Result<()> {let flag_note = flag_note(if self.branch_deleted() {BranchDeletionMode::SafeDelete // Doesn't matter, outcome already determined@@ -1049,6 +1088,9 @@ impl RemovalDisplayInfo {} else {""};+ let stats_paren = stats+ .map(|(f, b)| format_stats_paren(f, b))+ .unwrap_or_default();let msg = if foreground {if self.branch_deleted() {@@ -1057,10 +1099,12 @@ impl RemovalDisplayInfo {"Removed <bold>{branch_name}</> worktree{force_text} & branch{flag_text}")).append(&flag_note.after(AnsiColor::Green))+ .append(&stats_paren)} else {success_message(cformat!("Removed <bold>{branch_name}</> worktree{force_text}"))+ .append(&stats_paren)}} else if self.branch_deleted() {let flag_text = &flag_note.text;@@ -1228,15 +1272,19 @@ fn handle_detached_removed_worktree_output(remaining_entries: list_remaining_entries(ctx.worktree_path),error: err.to_string(),})?;- if let Some(staged) = output.staged_path {- let _ = std::fs::remove_dir_all(&staged);- }+ let (files, bytes) = output+ .staged_path+ .as_deref()+ .map(cleanup_staged_with_progress)+ .unwrap_or((0, 0));+ let stats_paren = format_stats_paren(files, bytes);eprintln!("{}",success_message(cformat!("Removed worktree @ <bold>{}</> (detached HEAD, no branch to delete)",format_path_for_display(ctx.worktree_path)))+ .append(&stats_paren));} else {let path_display = format_path_for_display(ctx.worktree_path);@@ -1297,9 +1345,11 @@ fn handle_named_removed_worktree_foreground(remaining_entries: list_remaining_entries(ctx.worktree_path),error: err.to_string(),})?;- if let Some(staged) = output.staged_path {- let _ = std::fs::remove_dir_all(&staged);- }+ let stats = output+ .staged_path+ .as_deref()+ .map(cleanup_staged_with_progress)+ .unwrap_or((0, 0));let display_info = RemovalDisplayInfo::from_branch_result(output.branch_result,@@ -1309,7 +1359,7 @@ fn handle_named_removed_worktree_foreground(ctx.force_worktree,)?;- display_info.print_message(branch_name, true)?;+ display_info.print_message(branch_name, true, Some(stats))?;display_info.print_hints(branch_name, ctx.deletion_mode, ctx.pre_computed_integration)?;print_switch_message_if_changed(ctx.changed_directory, ctx.main_path)?;@@ -1337,7 +1387,7 @@ fn handle_named_removed_worktree_background(ctx.force_worktree,);- display_info.print_message(branch_name, false)?;+ display_info.print_message(branch_name, false, None)?;display_info.print_hints(branch_name, ctx.deletion_mode, ctx.pre_computed_integration)?;print_switch_message_if_changed(ctx.changed_directory, ctx.main_path)?;diff --git a/src/copy_progress.rs b/src/progress.rssimilarity index 62%rename from src/copy_progress.rsrename to src/progress.rsindex 54c8ba2df..597876bbc 100644--- a/src/copy_progress.rs+++ b/src/progress.rs@@ -1,14 +1,15 @@-//! TTY spinner for long-running copy operations.+//! TTY spinner for long-running file-walk operations.//!-//! Shows a single-line stderr spinner (`⠋ Copying 1,234 files · 312 MiB`) that-//! updates in place while files are copied. Copy workers bump atomic counters-//! via [`CopyProgress::file_copied`]; a background thread renders at ~10Hz-//! using crossterm cursor control.+//! Shows a single-line stderr spinner (`⠋ Copying 1,234 files · 312 MiB`,+//! `⠋ Removing 7,272 files · 64.5 MiB`) that updates in place while the work+//! runs. Workers bump atomic counters via [`Progress::record`]; a background+//! thread renders at ~10Hz using crossterm cursor control.//!//! `start` is named deliberately (not `new`) because it spawns a ticker thread-//! as a side effect — `Default`-style semantics would be misleading.+//! as a side effect — `Default`-style semantics would be misleading. The verb+//! (`"Copying"`, `"Removing"`) is fixed for the lifetime of the spinner.//!-//! The progress line is cleared on [`CopyProgress::finish`] or on drop, so the+//! The progress line is cleared on [`Progress::finish`] or on drop, so the//! caller can print a summary message immediately afterward without overlap.use std::io::{IsTerminal, Write};@@ -26,13 +27,14 @@ use crossterm::{const SPINNER_FRAMES: &[char] = &['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];const TICK_INTERVAL: Duration = Duration::from_millis(100);-/// Delay before the first frame renders, so sub-second copies stay silent.+/// Delay before the first frame renders, so sub-second operations stay silent.const STARTUP_DELAY: Duration = Duration::from_millis(300);struct Shared {files: AtomicUsize,bytes: AtomicU64,done: AtomicBool,+ verb: &'static str,}struct Inner {@@ -40,24 +42,41 @@ struct Inner {ticker: JoinHandle<()>,}-/// Live spinner displaying files-copied and bytes-copied counters.+/// Live spinner displaying file and byte counters for a single operation.///-/// See [module docs](crate::copy_progress) for the output format and lifecycle.-pub struct CopyProgress(Option<Inner>);+/// See [module docs](crate::progress) for the output format and lifecycle.+pub struct Progress(Option<Inner>);-impl CopyProgress {+impl Progress {/// Start a progress reporter, enabling the spinner iff stderr is a TTY.///- /// Spawns a background ticker thread when a TTY is detected. When stderr- /// is not a TTY, returns a disabled reporter and does no work.- pub fn start() -> Self {- if !std::io::stderr().is_terminal() {- return Self::disabled();+ /// `verb` is the present-participle label shown to the user (e.g.+ /// `"Copying"`, `"Removing"`). Spawns a background ticker thread when a+ /// TTY is detected. When stderr is not a TTY, returns a disabled reporter+ /// and does no work.+ pub fn start(verb: &'static str) -> Self {+ if std::io::stderr().is_terminal() {+ Self::enabled(verb)+ } else {+ Self::disabled()}+ }++ /// A reporter that does nothing — for benchmarks, tests, and internal moves.+ pub fn disabled() -> Self {+ Self(None)+ }++ /// Constructor for the enabled state, separated so the TTY-gated branch in+ /// [`Self::start`] and the test-only "force enabled" path share one+ /// implementation. Spawns the ticker thread; safe to call from any+ /// context that genuinely wants live output.+ fn enabled(verb: &'static str) -> Self {let shared = Arc::new(Shared {files: AtomicUsize::new(0),bytes: AtomicU64::new(0),done: AtomicBool::new(false),+ verb,});let ticker = {let shared = Arc::clone(&shared);@@ -66,13 +85,8 @@ impl CopyProgress {Self(Some(Inner { shared, ticker }))}- /// A reporter that does nothing — for benchmarks, tests, and internal moves.- pub fn disabled() -> Self {- Self(None)- }-- /// Record that a file (or symlink) was copied. Safe to call from any thread.- pub fn file_copied(&self, bytes: u64) {+ /// Record that a file (or symlink) was processed. Safe to call from any thread.+ pub fn record(&self, bytes: u64) {if let Some(inner) = &self.0 {inner.shared.files.fetch_add(1, Ordering::Relaxed);inner.shared.bytes.fetch_add(bytes, Ordering::Relaxed);@@ -86,7 +100,7 @@ impl CopyProgress {}}-impl Drop for CopyProgress {+impl Drop for Progress {fn drop(&mut self) {// `Inner` is Drop-free, so we can take ownership of its fields and// run shutdown without partial-move conflicts.@@ -101,9 +115,9 @@ impl Drop for CopyProgress {fn ticker_loop(shared: &Shared) {let start = Instant::now();- // Sub-300ms copies render nothing — the line never gets drawn. park_timeout- // returns immediately on `unpark` from drop, so short copies don't block- // shutdown either.+ // Sub-300ms operations render nothing — the line never gets drawn.+ // park_timeout returns immediately on `unpark` from drop, so short+ // operations don't block shutdown either.while start.elapsed() < STARTUP_DELAY {if shared.done.load(Ordering::Relaxed) {return;@@ -115,19 +129,19 @@ fn ticker_loop(shared: &Shared) {% SPINNER_FRAMES.len();let files = shared.files.load(Ordering::Relaxed);let bytes = shared.bytes.load(Ordering::Relaxed);- let line = format_line(files, bytes, SPINNER_FRAMES[frame_idx]);+ let line = format_line(shared.verb, files, bytes, SPINNER_FRAMES[frame_idx]);let _ = render_line(&mut std::io::stderr().lock(), &line);thread::park_timeout(TICK_INTERVAL);}}-fn format_line(files: usize, bytes: u64, spinner: char) -> String {+fn format_line(verb: &str, files: usize, bytes: u64, spinner: char) -> String {if files == 0 {- cformat!("<cyan>{spinner}</> Copying...")+ cformat!("<cyan>{spinner}</> {verb}...")} else {let word = if files == 1 { "file" } else { "files" };cformat!(- "<cyan>{spinner}</> Copying {} {} · {}",+ "<cyan>{spinner}</> {verb} {} {} · {}",format_count(files),word,format_bytes(bytes),@@ -164,7 +178,7 @@ fn format_count(n: usize) -> String {/// Format a byte count using IEC binary prefixes (KiB, MiB, GiB, TiB).////// The divisor is 1024; SI-prefix "MB" would imply 10^6 and doesn't match what-/// we compute. Used by both the spinner line and the post-copy summary.+/// we compute. Used by both the spinner line and the post-operation summary.pub fn format_bytes(n: u64) -> String {const UNITS: &[&str] = &["B", "KiB", "MiB", "GiB", "TiB"];let mut size = n as f64;@@ -180,26 +194,32 @@ pub fn format_bytes(n: u64) -> String {}}+/// Format `(N files · X MiB)` as a gray stats parenthetical, matching the+/// spinner's units.+///+/// Returns an empty string when `files == 0` so callers can unconditionally+/// concatenate it to a success message without producing `(0 files · 0 B)`+/// when nothing was processed.+pub fn format_stats_paren(files: usize, bytes: u64) -> String {+ if files == 0 {+ return String::new();+ }+ let word = if files == 1 { "file" } else { "files" };+ // Split the closing paren into a separate cformat so the optimizer doesn't+ // collapse the two color-print spans (matches the squash-progress pattern+ // in commands/step_commands.rs).+ let close = cformat!("<bright-black>)</>");+ cformat!(+ " <bright-black>({} {word} · {}</>{close}",+ format_count(files),+ format_bytes(bytes),+ )+}+#[cfg(test)]mod tests {use super::*;- /// Construct an enabled instance directly, bypassing the TTY check that- /// would otherwise force a disabled reporter under cargo test. Lives in- /// the test module per the CLAUDE.md rule against test-only library APIs.- fn enabled_for_test() -> CopyProgress {- let shared = Arc::new(Shared {- files: AtomicUsize::new(0),- bytes: AtomicU64::new(0),- done: AtomicBool::new(false),- });- let ticker = {- let shared = Arc::clone(&shared);- thread::spawn(move || ticker_loop(&shared))- };- CopyProgress(Some(Inner { shared, ticker }))- }-#[test]fn test_format_count() {assert_eq!(format_count(0), "0");@@ -222,25 +242,45 @@ mod tests {#[test]fn test_format_line_empty() {- let line = format_line(0, 0, '⠋');+ let line = format_line("Copying", 0, 0, '⠋');assert!(line.contains("Copying..."));assert!(line.contains('⠋'));}#[test]fn test_format_line_singular() {- let line = format_line(1, 42, '⠙');+ let line = format_line("Copying", 1, 42, '⠙');assert!(line.contains("1 file "));assert!(line.contains("42 B"));}#[test]fn test_format_line_plural() {- let line = format_line(2_500, 5 * 1024 * 1024, '⠹');+ let line = format_line("Removing", 2_500, 5 * 1024 * 1024, '⠹');+ assert!(line.contains("Removing"));assert!(line.contains("2,500 files"));assert!(line.contains("5.0 MiB"));}+ #[test]+ fn test_format_stats_paren_empty_is_blank() {+ assert_eq!(format_stats_paren(0, 0), "");+ }++ #[test]+ fn test_format_stats_paren_singular() {+ let s = format_stats_paren(1, 42);+ assert!(s.contains("1 file"));+ assert!(s.contains("42 B"));+ }++ #[test]+ fn test_format_stats_paren_plural() {+ let s = format_stats_paren(2_500, 5 * 1024 * 1024);+ assert!(s.contains("2,500 files"));+ assert!(s.contains("5.0 MiB"));+ }+#[test]fn test_render_line_writes_text_with_prefix_control_bytes() {let mut buf = Vec::new();@@ -257,10 +297,10 @@ mod tests {}#[test]- fn test_disabled_file_copied_is_noop() {- let p = CopyProgress::disabled();- p.file_copied(1_000_000);- p.file_copied(2_000_000);+ fn test_disabled_record_is_noop() {+ let p = Progress::disabled();+ p.record(1_000_000);+ p.record(2_000_000);// No counters to inspect — Disabled has no fields. The assertion is// simply that the call doesn't panic and finish() returns cleanly.p.finish();@@ -268,14 +308,14 @@ mod tests {#[test]fn test_start_in_non_tty_is_disabled() {- assert!(CopyProgress::start().0.is_none());+ assert!(Progress::start("Copying").0.is_none());}#[test]fn test_enabled_lifecycle_counters_propagate() {- let p = enabled_for_test();- p.file_copied(1024);- p.file_copied(2048);+ let p = Progress::enabled("Copying");+ p.record(1024);+ p.record(2048);let inner = p.0.as_ref().expect("expected enabled");assert_eq!(inner.shared.files.load(Ordering::Relaxed), 2);assert_eq!(inner.shared.bytes.load(Ordering::Relaxed), 3072);@@ -284,8 +324,8 @@ mod tests {#[test]fn test_enabled_renders_after_startup_delay() {- let p = enabled_for_test();- p.file_copied(100);+ let p = Progress::enabled("Removing");+ p.record(100);// Wait past the startup delay + one tick so ticker_loop reaches the// render branch — the part that's hardest to cover otherwise.std::thread::sleep(STARTUP_DELAY + TICK_INTERVAL + Duration::from_millis(50));diff --git a/src/remove_dir.rs b/src/remove_dir.rsnew file mode 100644index 000000000..3dc059358--- /dev/null+++ b/src/remove_dir.rs@@ -0,0 +1,193 @@+//! Recursive directory removal with progress reporting.+//!+//! Walks the tree iteratively (no recursion), unlinks files in parallel, then+//! removes the now-empty directories deepest-first. Each unlinked leaf bumps+//! a [`Progress`] counter so a TTY spinner can render live updates; the+//! returned `(files, bytes)` tuple drives the matching post-op summary.+//!+//! Best-effort by design: this is the trash-cleanup phase that runs *after*+//! the worktree has already been pruned from git's metadata, so a partial+//! cleanup leaves the user with a stale directory under `.git/wt/trash/` —+//! recoverable, not catastrophic. read/unlink/rmdir errors are swallowed so+//! the caller can always report the count of leaves we did manage to remove.+//! Parallel unlink runs on a dedicated 4-thread pool — file removal is+//! filesystem latency, not CPU, so a small pool gives most of the speedup+//! without the per-process thread cost of rayon's default `2× CPU cores`+//! global pool (which adds up across many subprocesses in test runs).++use std::fs;+use std::path::{Path, PathBuf};+use std::sync::LazyLock;+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};++use rayon::prelude::*;++use crate::progress::Progress;++/// Capped at 4 threads — same reasoning as `copy::COPY_POOL` (filesystem I/O,+/// don't oversubscribe CPU when many wt subprocesses run in parallel).+static REMOVE_POOL: LazyLock<rayon::ThreadPool> = LazyLock::new(|| {+ rayon::ThreadPoolBuilder::new()+ .num_threads(4)+ .build()+ .expect("failed to build remove thread pool")+});++/// Remove a directory tree, reporting per-file progress.+///+/// Returns `(files_removed, bytes_removed)`. Bytes use `symlink_metadata`, so+/// symlinks count as their own size, not the target's. Any I/O errors are+/// silently skipped — a leaf that can't be unlinked is simply not counted.+pub fn remove_dir_with_progress(path: &Path, progress: &Progress) -> (usize, u64) {+ let mut leaves: Vec<PathBuf> = Vec::new();+ let mut dirs: Vec<PathBuf> = Vec::new();+ let mut stack = vec![path.to_path_buf()];++ while let Some(dir) = stack.pop() {+ // read_dir failure (NotFound, EACCES, anything else) → skip this+ // subtree. We still try to rmdir it later in case it's actually empty.+ let Ok(entries) = fs::read_dir(&dir) else {+ dirs.push(dir);+ continue;+ };+ // Push parents first; we'll reverse before rmdir so children unlink first.+ dirs.push(dir);+ for entry in entries.flatten() {+ // entry.file_type() is an lstat on Unix — symlinks report+ // `is_dir() == false` and fall through to the leaf branch, which+ // is what we want (unlink the link, not the target).+ let Ok(file_type) = entry.file_type() else {+ continue;+ };+ let entry_path = entry.path();+ if file_type.is_dir() {+ stack.push(entry_path);+ } else {+ leaves.push(entry_path);+ }+ }+ }++ let removed_files = AtomicUsize::new(0);+ let removed_bytes = AtomicU64::new(0);+ REMOVE_POOL.install(|| {+ leaves.par_iter().for_each(|leaf| {+ // Capture size before unlinking. Best-effort: symlink_metadata may+ // fail on a racy delete, in which case we still try to unlink and+ // count the leaf with zero bytes.+ let bytes = leaf.symlink_metadata().map(|m| m.len()).unwrap_or(0);+ if fs::remove_file(leaf).is_ok() {+ removed_files.fetch_add(1, Ordering::Relaxed);+ removed_bytes.fetch_add(bytes, Ordering::Relaxed);+ progress.record(bytes);+ }+ });+ });++ // Pop order pushed parents before children, so reversing gives+ // deepest-first — exactly what `rmdir` needs.+ for dir in dirs.iter().rev() {+ let _ = fs::remove_dir(dir);+ }++ (removed_files.into_inner(), removed_bytes.into_inner())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_remove_dir_with_progress_empty_dir() {+ let temp = tempfile::tempdir().unwrap();+ let dir = temp.path().join("empty");+ std::fs::create_dir(&dir).unwrap();++ let (files, bytes) = remove_dir_with_progress(&dir, &Progress::disabled());++ assert_eq!(files, 0);+ assert_eq!(bytes, 0);+ assert!(!dir.exists());+ }++ #[test]+ fn test_remove_dir_with_progress_counts_files_and_bytes() {+ let temp = tempfile::tempdir().unwrap();+ let root = temp.path().join("tree");+ std::fs::create_dir_all(root.join("a/b")).unwrap();+ std::fs::write(root.join("a/file1.txt"), b"hello").unwrap(); // 5 bytes+ std::fs::write(root.join("a/b/file2.txt"), b"world!").unwrap(); // 6 bytes+ std::fs::write(root.join("top.txt"), b"x").unwrap(); // 1 byte++ let (files, bytes) = remove_dir_with_progress(&root, &Progress::disabled());++ assert_eq!(files, 3);+ assert_eq!(bytes, 12);+ assert!(!root.exists());+ }++ #[test]+ fn test_remove_dir_with_progress_missing_root_is_ok() {+ let temp = tempfile::tempdir().unwrap();+ let missing = temp.path().join("does-not-exist");++ let (files, bytes) = remove_dir_with_progress(&missing, &Progress::disabled());++ assert_eq!(files, 0);+ assert_eq!(bytes, 0);+ }++ #[cfg(unix)]+ #[test]+ fn test_remove_dir_with_progress_handles_symlinks() {+ let temp = tempfile::tempdir().unwrap();+ let root = temp.path().join("tree");+ std::fs::create_dir(&root).unwrap();+ std::fs::write(root.join("real.txt"), b"abc").unwrap();+ std::os::unix::fs::symlink(root.join("real.txt"), root.join("link")).unwrap();++ let (files, _bytes) = remove_dir_with_progress(&root, &Progress::disabled());++ // 1 file + 1 symlink = 2 leaves removed; the symlink is unlinked+ // without following.+ assert_eq!(files, 2);+ assert!(!root.exists());+ }++ /// Cover the read_dir-fails path. Permission-denied is the realistic+ /// non-NotFound failure; the function should silently skip the subtree+ /// and still rmdir what it can. Skipped when running as root (the kernel+ /// ignores mode-0 directories for euid 0).+ #[cfg(unix)]+ #[test]+ fn test_remove_dir_with_progress_skips_unreadable_subtree() {+ use std::os::unix::fs::PermissionsExt;++ let temp = tempfile::tempdir().unwrap();+ let root = temp.path().join("tree");+ let blocked = root.join("blocked");+ std::fs::create_dir_all(&blocked).unwrap();+ std::fs::write(blocked.join("hidden.txt"), b"x").unwrap();+ // Make `blocked` unreadable. Also blocks rmdir of `blocked` itself,+ // but that's fine — we want to exercise the read_dir error branch+ // and verify the function returns gracefully.+ std::fs::set_permissions(&blocked, std::fs::Permissions::from_mode(0o000)).unwrap();++ // Skip if running as root: euid 0 ignores DAC mode bits, so the+ // walk would succeed and unlink hidden.txt. Probe via a read attempt+ // — same pattern as the integration tests in tests/.+ if std::fs::read_dir(&blocked).is_ok() {+ std::fs::set_permissions(&blocked, std::fs::Permissions::from_mode(0o755)).ok();+ eprintln!("Skipping - running with elevated privileges");+ return;+ }++ let (files, bytes) = remove_dir_with_progress(&root, &Progress::disabled());++ // Restore so the tempdir's Drop can clean up.+ std::fs::set_permissions(&blocked, std::fs::Permissions::from_mode(0o755)).ok();++ assert_eq!(files, 0, "no leaves should be unlinked when blocked");+ assert_eq!(bytes, 0);+ }+}diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex a192ac07b..e7a51f9c4 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -901,6 +901,8 @@ fn setup_snapshot_settings_for_paths_with_home("post-start-[NAME]-[TIMESTAMP].log",);+ add_remove_stats_byte_filter(&mut settings);+// Filter out Git hint messages that vary across Git versions// These hints appear during rebase conflicts and can differ between versions// Pattern matches lines with gutter formatting + "hint:" + message + newline@@ -1114,10 +1116,29 @@ pub fn setup_temp_snapshot_settings(temp_path: &std::path::Path) -> insta::Settisettings.add_filter(r"wt\.exe", "wt");add_standard_env_redactions(&mut settings);+ add_remove_stats_byte_filter(&mut settings);settings}+/// Normalize byte counts inside the `(N files · X UNIT)` stats parenthetical+/// emitted by `wt remove --foreground`.+///+/// The walk in `remove_dir_with_progress` hits the renamed worktree's `.git`+/// pointer file, whose content is the gitdir's absolute path — so the byte+/// total is sensitive to the temp-dir prefix (macOS `/var/folders/...` vs+/// Linux `/tmp/...` vs Windows). The literal `(...files · X UNIT)` shape is+/// unique enough to leave the deterministic copy-ignored summary+/// (`Copied N files · X B` — no surrounding parens) untouched, so the regex+/// doesn't depend on ANSI styling and works in both colored and `NO_COLOR`+/// test environments.+fn add_remove_stats_byte_filter(settings: &mut insta::Settings) {+ settings.add_filter(+ r"(\(\d+ files? · )\d+(?:\.\d+)? (B|KiB|MiB|GiB|TiB)",+ "${1}[BYTES] $2",+ );+}+// =============================================================================// PTY Test Filters// =============================================================================diff --git a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_executes.snap b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_executes.snapindex 3ec2cb262..c67a9032d 100644--- a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_executes.snap+++ b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_executes.snap@@ -49,4 +49,4 @@ exit_code: 0[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'About to remove worktree'[0m[2m[0mAbout to remove worktree[36m◎[39m [36mRemoving [1mfeature-hook[22m worktree...[39m-[32m✓[39m [32mRemoved [1mfeature-hook[22m worktree & branch (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39m+[32m✓[39m [32mRemoved [1mfeature-hook[22m worktree & branch (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39m [90m(4 files · [BYTES] B[39m[90m)[39mdiff --git a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_runs_for_detached_head.snap b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_runs_for_detached_head.snapindex 4c844361a..65e9968df 100644--- a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_runs_for_detached_head.snap+++ b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_runs_for_detached_head.snap@@ -47,4 +47,4 @@ exit_code: 0[36m◎[39m [36mRunning pre-remove project hook[39m[107m [0m [2m[0m[2m[34mtouch[0m[2m _REPO_/m.txt[0m[36m◎[39m [36mRemoving worktree @ [1m_REPO_.feature-detached-hook[22m... (detached HEAD, no branch to delete)[39m-[32m✓[39m [32mRemoved worktree @ [1m_REPO_.feature-detached-hook[22m (detached HEAD, no branch to delete)[39m+[32m✓[39m [32mRemoved worktree @ [1m_REPO_.feature-detached-hook[22m (detached HEAD, no branch to delete)[39m [90m(4 files · [BYTES] B[39m[90m)[39mdiff --git a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_skipped_with_no_hooks.snap b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_skipped_with_no_hooks.snapindex f52967e9e..21296b57d 100644--- a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_skipped_with_no_hooks.snap+++ b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_skipped_with_no_hooks.snap@@ -47,4 +47,4 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRemoving [1mfeature-skip[22m worktree...[39m-[32m✓[39m [32mRemoved [1mfeature-skip[22m worktree & branch (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39m+[32m✓[39m [32mRemoved [1mfeature-skip[22m worktree & branch (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39m [90m(4 files · [BYTES] B[39m[90m)[39mdiff --git a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_template_variables.snap b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_template_variables.snapindex 7bfb81a69..0e05d887e 100644--- a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_template_variables.snap+++ b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_template_variables.snap@@ -55,4 +55,4 @@ exit_code: 0[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'Name: repo.feature-templates'[0m[2m[0mName: repo.feature-templates[36m◎[39m [36mRemoving [1mfeature-templates[22m worktree...[39m-[32m✓[39m [32mRemoved [1mfeature-templates[22m worktree & branch (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39m+[32m✓[39m [32mRemoved [1mfeature-templates[22m worktree & branch (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39m [90m(4 files · [BYTES] B[39m[90m)[39mdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_default_branch_force_delete.snap b/tests/snapshots/integration__integration_tests__remove__remove_default_branch_force_delete.snapindex 9e8a6cc70..fb85767c4 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_default_branch_force_delete.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_default_branch_force_delete.snap@@ -40,4 +40,4 @@ exit_code: 0----- stderr -----◎ Removing main worktree...-✓ Removed main worktree & branch (--force-delete)+✓ Removed main worktree & branch (--force-delete) (2 files · [BYTES] B)diff --git a/tests/snapshots/integration__integration_tests__remove__remove_detached_worktree_by_relative_path.snap b/tests/snapshots/integration__integration_tests__remove__remove_detached_worktree_by_relative_path.snapindex ca03289ae..aea6b8c47 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_detached_worktree_by_relative_path.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_detached_worktree_by_relative_path.snap@@ -47,4 +47,4 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRemoving worktree @ [1m_REPO_.feature-detached[22m... (detached HEAD, no branch to delete)[39m-[32m✓[39m [32mRemoved worktree @ [1m_REPO_.feature-detached[22m (detached HEAD, no branch to delete)[39m+[32m✓[39m [32mRemoved worktree @ [1m_REPO_.feature-detached[22m (detached HEAD, no branch to delete)[39m [90m(3 files · [BYTES] B[39m[90m)[39mdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_foreground.snap b/tests/snapshots/integration__integration_tests__remove__remove_foreground.snapindex 03406283c..eb7d2d42f 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_foreground.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_foreground.snap@@ -46,4 +46,4 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRemoving [1mfeature-fg[22m worktree...[39m-[32m✓[39m [32mRemoved [1mfeature-fg[22m worktree & branch (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39m+[32m✓[39m [32mRemoved [1mfeature-fg[22m worktree & branch (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39m [90m(3 files · [BYTES] B[39m[90m)[39mdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_foreground_detached_head.snap b/tests/snapshots/integration__integration_tests__remove__remove_foreground_detached_head.snapindex 73543a502..629532bcd 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_foreground_detached_head.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_foreground_detached_head.snap@@ -45,4 +45,4 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRemoving worktree @ [1m_REPO_.feature-detached-fg[22m... (detached HEAD, no branch to delete)[39m-[32m✓[39m [32mRemoved worktree @ [1m_REPO_.feature-detached-fg[22m (detached HEAD, no branch to delete)[39m+[32m✓[39m [32mRemoved worktree @ [1m_REPO_.feature-detached-fg[22m (detached HEAD, no branch to delete)[39m [90m(3 files · [BYTES] B[39m[90m)[39mdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_foreground_no_delete_branch.snap b/tests/snapshots/integration__integration_tests__remove__remove_foreground_no_delete_branch.snapindex a90779b87..c6bea41c5 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_foreground_no_delete_branch.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_foreground_no_delete_branch.snap@@ -47,5 +47,5 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRemoving [1mfeature-fg-keep[22m worktree...[39m-[32m✓[39m [32mRemoved [1mfeature-fg-keep[22m worktree[39m+[32m✓[39m [32mRemoved [1mfeature-fg-keep[22m worktree[39m [90m(3 files · [BYTES] B[39m[90m)[39m[2m↳[22m [2mBranch integrated (same commit as [4mmain[24m, [2m_[22m); retained with [4m--no-delete-branch[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_foreground_no_delete_branch_unmerged.snap b/tests/snapshots/integration__integration_tests__remove__remove_foreground_no_delete_branch_unmerged.snapindex d0fe5a069..1fa3ffcdb 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_foreground_no_delete_branch_unmerged.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_foreground_no_delete_branch_unmerged.snap@@ -47,4 +47,4 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRemoving [1mfeature-fg-unmerged-keep[22m worktree...[39m-[32m✓[39m [32mRemoved [1mfeature-fg-unmerged-keep[22m worktree[39m+[32m✓[39m [32mRemoved [1mfeature-fg-unmerged-keep[22m worktree[39m [90m(4 files · [BYTES] B[39m[90m)[39mdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_foreground_unmerged.snap b/tests/snapshots/integration__integration_tests__remove__remove_foreground_unmerged.snapindex 181e20f7d..a520f9b2e 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_foreground_unmerged.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_foreground_unmerged.snap@@ -46,5 +46,5 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRemoving [1mfeature-unmerged-fg[22m worktree...[39m-[32m✓[39m [32mRemoved [1mfeature-unmerged-fg[22m worktree[39m+[32m✓[39m [32mRemoved [1mfeature-unmerged-fg[22m worktree[39m [90m(4 files · [BYTES] B[39m[90m)[39m[2m↳[22m [2mBranch unmerged; to delete, run [4mwt remove -D feature-unmerged-fg[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_main_vs_linked__from_linked_succeeds.snap b/tests/snapshots/integration__integration_tests__remove__remove_main_vs_linked__from_linked_succeeds.snapindex f515293fa..e9fde80ad 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_main_vs_linked__from_linked_succeeds.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_main_vs_linked__from_linked_succeeds.snap@@ -45,6 +45,6 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRemoving [1mfeature[22m worktree...[39m-[32m✓[39m [32mRemoved [1mfeature[22m worktree & branch (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39m+[32m✓[39m [32mRemoved [1mfeature[22m worktree & branch (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39m [90m(3 files · [BYTES] B[39m[90m)[39m[33m▲[39m [33mCannot change directory — shell integration not installed[39m[2m↳[22m [2mTo enable automatic cd, run [4mwt config shell install[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_path_mismatch_warning_foreground.snap b/tests/snapshots/integration__integration_tests__remove__remove_path_mismatch_warning_foreground.snapindex 6bfdbfd4b..32ae661ec 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_path_mismatch_warning_foreground.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_path_mismatch_warning_foreground.snap@@ -47,4 +47,4 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRemoving [1mfeature-fg[22m worktree...[39m[33m▲[39m [33mBranch-worktree mismatch: [1mfeature-fg[22m @ [1m_PARENT_/another-weird-path[22m, expected @ [1m_REPO_.feature-fg[22m [31m⚑[39m[39m-[32m✓[39m [32mRemoved [1mfeature-fg[22m worktree & branch (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39m+[32m✓[39m [32mRemoved [1mfeature-fg[22m worktree & branch (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39m [90m(3 files · [BYTES] B[39m[90m)[39mdiff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_removes_integrated_detached.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_removes_integrated_detached.snapindex 91c80430f..55be5a4ce 100644--- a/tests/snapshots/integration__integration_tests__step_prune__prune_removes_integrated_detached.snap+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_removes_integrated_detached.snap@@ -49,6 +49,6 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRemoving worktree @ [1m_REPO_.detached-integrated[22m... (detached HEAD, no branch to delete)[39m-[32m✓[39m [32mRemoved worktree @ [1m_REPO_.detached-integrated[22m (detached HEAD, no branch to delete)[39m+[32m✓[39m [32mRemoved worktree @ [1m_REPO_.detached-integrated[22m (detached HEAD, no branch to delete)[39m [90m(3 files · [BYTES] B[39m[90m)[39m[32m✓ Removed branch [1mdetached-integrated[22m (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39m[32m✓[39m [32mPruned 1 worktree, 1 branch[39m