Skip to content

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

fix(progress): gate crossterm spinner internals behind `cli` feature (#2441)

Maximilian Roos7f584f5dee46
diff --git a/src/progress.rs b/src/progress.rs
index 597876bbc..71cce1dc7 100644
--- a/src/progress.rs
+++ b/src/progress.rs
@@ -11,155 +11,261 @@
//!
//! 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};
-use std::sync::Arc;
-use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
-use std::thread::{self, JoinHandle};
-use std::time::{Duration, Instant};
+//!
+//! The full spinner machinery (crossterm, the ticker thread, the render loop)
+//! is gated on the `cli` feature. Without `cli`, [`Progress`] is a zero-cost
+//! stub: `start` always returns a no-op reporter and `record` does nothing.
+//! Pure formatting helpers ([`format_bytes`], [`format_stats_paren`]) are
+//! always available since callers in both modes want them.
use color_print::cformat;
-use crossterm::{
- QueueableCommand,
- cursor::MoveToColumn,
- terminal::{Clear, ClearType},
-};
-
-const SPINNER_FRAMES: &[char] = &['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
-const TICK_INTERVAL: Duration = Duration::from_millis(100);
-/// 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 {
- shared: Arc<Shared>,
- ticker: JoinHandle<()>,
-}
+pub use imp::Progress;
+
+#[cfg(feature = "cli")]
+mod imp {
+ use std::io::{IsTerminal, Write};
+ use std::sync::Arc;
+ use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
+ use std::thread::{self, JoinHandle};
+ use std::time::{Duration, Instant};
+
+ use color_print::cformat;
+ use crossterm::{
+ QueueableCommand,
+ cursor::MoveToColumn,
+ terminal::{Clear, ClearType},
+ };
+
+ use super::{format_bytes, format_count};
+
+ const SPINNER_FRAMES: &[char] = &['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
+ const TICK_INTERVAL: Duration = Duration::from_millis(100);
+ /// 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,
+ }
-/// Live spinner displaying file and byte counters for a single operation.
-///
-/// See [module docs](crate::progress) for the output format and lifecycle.
-pub struct Progress(Option<Inner>);
+ struct Inner {
+ shared: Arc<Shared>,
+ ticker: JoinHandle<()>,
+ }
-impl Progress {
- /// Start a progress reporter, enabling the spinner iff stderr is a TTY.
+ /// Live spinner displaying file and byte counters for a single operation.
///
- /// `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()
+ /// See [module docs](super) for the output format and lifecycle.
+ pub struct Progress(Option<Inner>);
+
+ impl Progress {
+ /// Start a progress reporter, enabling the spinner iff stderr is a TTY.
+ ///
+ /// `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)
- }
+ /// 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);
- thread::spawn(move || ticker_loop(&shared))
- };
- Self(Some(Inner { shared, ticker }))
- }
+ /// 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);
+ thread::spawn(move || ticker_loop(&shared))
+ };
+ Self(Some(Inner { shared, ticker }))
+ }
+
+ /// 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);
+ }
+ }
- /// 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);
+ /// Stop the spinner and clear the progress line.
+ pub fn finish(self) {
+ // Drop runs the same shutdown logic — no need to duplicate it here.
+ drop(self);
}
}
- /// Stop the spinner and clear the progress line.
- pub fn finish(self) {
- // Drop runs the same shutdown logic — no need to duplicate it here.
- drop(self);
+ 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.
+ if let Some(inner) = self.0.take() {
+ inner.shared.done.store(true, Ordering::Relaxed);
+ inner.ticker.thread().unpark();
+ let _ = inner.ticker.join();
+ let _ = clear_line(&mut std::io::stderr().lock());
+ }
+ }
}
-}
-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.
- if let Some(inner) = self.0.take() {
- inner.shared.done.store(true, Ordering::Relaxed);
- inner.ticker.thread().unpark();
- let _ = inner.ticker.join();
- let _ = clear_line(&mut std::io::stderr().lock());
+ fn ticker_loop(shared: &Shared) {
+ let start = Instant::now();
+ // 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;
+ }
+ thread::park_timeout(STARTUP_DELAY - start.elapsed());
+ }
+ while !shared.done.load(Ordering::Relaxed) {
+ let frame_idx = (start.elapsed().as_millis() / TICK_INTERVAL.as_millis()) as usize
+ % SPINNER_FRAMES.len();
+ let files = shared.files.load(Ordering::Relaxed);
+ let bytes = shared.bytes.load(Ordering::Relaxed);
+ 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 ticker_loop(shared: &Shared) {
- let start = Instant::now();
- // 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;
+ fn format_line(verb: &str, files: usize, bytes: u64, spinner: char) -> String {
+ if files == 0 {
+ cformat!("<cyan>{spinner}</> {verb}...")
+ } else {
+ let word = if files == 1 { "file" } else { "files" };
+ cformat!(
+ "<cyan>{spinner}</> {verb} {} {} · {}",
+ format_count(files),
+ word,
+ format_bytes(bytes),
+ )
}
- thread::park_timeout(STARTUP_DELAY - start.elapsed());
}
- while !shared.done.load(Ordering::Relaxed) {
- let frame_idx = (start.elapsed().as_millis() / TICK_INTERVAL.as_millis()) as usize
- % SPINNER_FRAMES.len();
- let files = shared.files.load(Ordering::Relaxed);
- let bytes = shared.bytes.load(Ordering::Relaxed);
- 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 render_line<W: Write>(w: &mut W, line: &str) -> std::io::Result<()> {
+ w.queue(MoveToColumn(0))?;
+ w.queue(Clear(ClearType::CurrentLine))?;
+ write!(w, "{line}")?;
+ w.flush()
}
-}
-fn format_line(verb: &str, files: usize, bytes: u64, spinner: char) -> String {
- if files == 0 {
- cformat!("<cyan>{spinner}</> {verb}...")
- } else {
- let word = if files == 1 { "file" } else { "files" };
- cformat!(
- "<cyan>{spinner}</> {verb} {} {} · {}",
- format_count(files),
- word,
- format_bytes(bytes),
- )
+ fn clear_line<W: Write>(w: &mut W) -> std::io::Result<()> {
+ w.queue(MoveToColumn(0))?;
+ w.queue(Clear(ClearType::CurrentLine))?;
+ w.flush()
}
-}
-fn render_line<W: Write>(w: &mut W, line: &str) -> std::io::Result<()> {
- w.queue(MoveToColumn(0))?;
- w.queue(Clear(ClearType::CurrentLine))?;
- write!(w, "{line}")?;
- w.flush()
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ #[test]
+ fn test_format_line_empty() {
+ let line = format_line("Copying", 0, 0, '⠋');
+ assert!(line.contains("Copying..."));
+ assert!(line.contains('⠋'));
+ }
+
+ #[test]
+ fn test_format_line_singular() {
+ 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("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_render_line_writes_text_with_prefix_control_bytes() {
+ let mut buf = Vec::new();
+ render_line(&mut buf, "hello").unwrap();
+ assert!(buf.ends_with(b"hello"));
+ assert!(buf.len() > b"hello".len());
+ }
+
+ #[test]
+ fn test_clear_line_writes_control_bytes() {
+ let mut buf = Vec::new();
+ clear_line(&mut buf).unwrap();
+ assert!(!buf.is_empty());
+ }
+
+ #[test]
+ fn test_start_in_non_tty_is_disabled() {
+ assert!(Progress::start("Copying").0.is_none());
+ }
+
+ #[test]
+ fn test_enabled_lifecycle_counters_propagate() {
+ 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);
+ p.finish();
+ }
+
+ #[test]
+ fn test_enabled_renders_after_startup_delay() {
+ 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));
+ p.finish();
+ }
+ }
}
-fn clear_line<W: Write>(w: &mut W) -> std::io::Result<()> {
- w.queue(MoveToColumn(0))?;
- w.queue(Clear(ClearType::CurrentLine))?;
- w.flush()
+#[cfg(not(feature = "cli"))]
+mod imp {
+ /// Zero-cost stub when the `cli` feature is off. The spinner depends on
+ /// `crossterm`, which is only pulled in by `cli`; library consumers that
+ /// disable default features get this no-op type instead. Counters are
+ /// dropped on the floor — no allocation, no thread, no rendering.
+ pub struct Progress;
+
+ impl Progress {
+ pub fn start(_verb: &'static str) -> Self {
+ Self
+ }
+
+ pub fn disabled() -> Self {
+ Self
+ }
+
+ pub fn record(&self, _bytes: u64) {}
+
+ pub fn finish(self) {}
+ }
}
fn format_count(n: usize) -> String {
@@ -240,28 +346,6 @@ mod tests {
assert_eq!(format_bytes(1_610_612_736), "1.5 GiB");
}
- #[test]
- fn test_format_line_empty() {
- let line = format_line("Copying", 0, 0, '⠋');
- assert!(line.contains("Copying..."));
- assert!(line.contains('⠋'));
- }
-
- #[test]
- fn test_format_line_singular() {
- 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("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), "");
@@ -281,21 +365,6 @@ mod tests {
assert!(s.contains("5.0 MiB"));
}
- #[test]
- fn test_render_line_writes_text_with_prefix_control_bytes() {
- let mut buf = Vec::new();
- render_line(&mut buf, "hello").unwrap();
- assert!(buf.ends_with(b"hello"));
- assert!(buf.len() > b"hello".len());
- }
-
- #[test]
- fn test_clear_line_writes_control_bytes() {
- let mut buf = Vec::new();
- clear_line(&mut buf).unwrap();
- assert!(!buf.is_empty());
- }
-
#[test]
fn test_disabled_record_is_noop() {
let p = Progress::disabled();
@@ -305,30 +374,4 @@ mod tests {
// simply that the call doesn't panic and finish() returns cleanly.
p.finish();
}
-
- #[test]
- fn test_start_in_non_tty_is_disabled() {
- assert!(Progress::start("Copying").0.is_none());
- }
-
- #[test]
- fn test_enabled_lifecycle_counters_propagate() {
- 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);
- p.finish();
- }
-
- #[test]
- fn test_enabled_renders_after_startup_delay() {
- 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));
- p.finish();
- }
}