worktrunk 0.61.0

A CLI for Git worktree management, designed for parallel AI agent workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! TTY spinner and file/byte counters for long-running file-walk operations.
//!
//! 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.
//!
//! `Progress` is the single owner of operation counts: every state (spinner
//! enabled, disabled, and the no-`cli` stub) accumulates files/bytes, and
//! [`Progress::totals`] reads the running totals from `&self` mid-operation.
//! Callers report from `totals()` rather than keeping their own counters.
//! Counts accumulate for the lifetime of the reporter, so each counted
//! operation (or batch reported as one) gets its own `Progress`.
//!
//! `start` is named deliberately (not `new`) because it spawns a ticker thread
//! 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 [`Progress::finish`] or on drop, so the
//! caller can print a summary message immediately afterward without overlap.
//!
//! The spinner machinery (crossterm, the ticker thread, the render loop) is
//! gated on the `cli` feature. Without `cli`, [`Progress`] keeps the counters
//! but never renders. Pure formatting helpers ([`format_bytes`],
//! [`format_stats_paren`]) are always available since callers in both modes
//! want them.

use color_print::cformat;

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,
    }

    impl Shared {
        fn new() -> Self {
            Self {
                files: AtomicUsize::new(0),
                bytes: AtomicU64::new(0),
                done: AtomicBool::new(false),
            }
        }
    }

    /// Live spinner displaying file and byte counters for a single operation.
    ///
    /// Counters accumulate in every state; only the rendering is conditional.
    /// See [module docs](super) for the output format and lifecycle.
    pub struct Progress {
        shared: Arc<Shared>,
        /// Render thread; present only when the spinner is enabled (stderr TTY).
        ticker: Option<JoinHandle<()>>,
    }

    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 that still counts but renders nothing.
        pub fn start(verb: &'static str) -> Self {
            Self::start_with(verb, std::io::stderr().is_terminal())
        }

        /// Dispatch helper that picks the enabled or disabled branch from an
        /// explicit `is_tty` flag. Extracted so tests can exercise both branches
        /// without depending on the ambient stderr fd — sandboxes (Nix builds,
        /// some CI runners) hand the test process a PTY-backed stderr, which
        /// would flip the gate in `start` and break a test that hard-coded the
        /// disabled outcome. See #2615.
        fn start_with(verb: &'static str, is_tty: bool) -> Self {
            if is_tty {
                Self::enabled(verb)
            } else {
                Self::disabled()
            }
        }

        /// A reporter that renders nothing but still counts — for non-TTY
        /// contexts, benchmarks, tests, and internal moves.
        pub fn disabled() -> Self {
            Self {
                shared: Arc::new(Shared::new()),
                ticker: 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::new());
            let ticker = {
                let shared = Arc::clone(&shared);
                thread::spawn(move || ticker_loop(&shared, verb))
            };
            Self {
                shared,
                ticker: Some(ticker),
            }
        }

        /// Record that a file (or symlink) was processed. Safe to call from any thread.
        pub fn record(&self, bytes: u64) {
            self.shared.files.fetch_add(1, Ordering::Relaxed);
            self.shared.bytes.fetch_add(bytes, Ordering::Relaxed);
        }

        /// Running `(files, bytes)` totals recorded so far.
        ///
        /// Relaxed loads — exact only once the recording threads have finished
        /// (e.g. after the rayon pool call returns).
        pub fn totals(&self) -> (usize, u64) {
            (
                self.shared.files.load(Ordering::Relaxed),
                self.shared.bytes.load(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);
        }
    }

    impl Drop for Progress {
        fn drop(&mut self) {
            if let Some(ticker) = self.ticker.take() {
                self.shared.done.store(true, Ordering::Relaxed);
                ticker.thread().unpark();
                let _ = ticker.join();
                let _ = clear_line(&mut std::io::stderr().lock());
            }
        }
    }

    fn ticker_loop(shared: &Shared, verb: &str) {
        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(verb, files, bytes, SPINNER_FRAMES[frame_idx]);
            let _ = render_line(&mut std::io::stderr().lock(), &line);
            thread::park_timeout(TICK_INTERVAL);
        }
    }

    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 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 clear_line<W: Write>(w: &mut W) -> std::io::Result<()> {
        w.queue(MoveToColumn(0))?;
        w.queue(Clear(ClearType::CurrentLine))?;
        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_with_non_tty_is_disabled() {
            assert!(Progress::start_with("Copying", false).ticker.is_none());
        }

        #[test]
        fn test_start_with_tty_is_enabled() {
            let p = Progress::start_with("Copying", true);
            assert!(p.ticker.is_some());
            p.finish();
        }

        #[test]
        fn test_enabled_lifecycle_counters_propagate() {
            let p = Progress::enabled("Copying");
            p.record(1024);
            p.record(2048);
            assert_eq!(p.totals(), (2, 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();
        }
    }
}

#[cfg(not(feature = "cli"))]
mod imp {
    use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};

    /// Spinner-less 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 thread-free, render-free type. The
    /// counters still accumulate so [`Progress::totals`] reports the same
    /// numbers in both builds.
    pub struct Progress {
        files: AtomicUsize,
        bytes: AtomicU64,
    }

    impl Progress {
        pub fn start(_verb: &'static str) -> Self {
            Self::disabled()
        }

        pub fn disabled() -> Self {
            Self {
                files: AtomicUsize::new(0),
                bytes: AtomicU64::new(0),
            }
        }

        pub fn record(&self, bytes: u64) {
            self.files.fetch_add(1, Ordering::Relaxed);
            self.bytes.fetch_add(bytes, Ordering::Relaxed);
        }

        pub fn totals(&self) -> (usize, u64) {
            (
                self.files.load(Ordering::Relaxed),
                self.bytes.load(Ordering::Relaxed),
            )
        }

        pub fn finish(self) {}
    }
}

fn format_count(n: usize) -> String {
    let s = n.to_string();
    let bytes = s.as_bytes();
    let mut out = String::with_capacity(s.len() + s.len() / 3);
    for (i, b) in bytes.iter().enumerate() {
        if i > 0 && (bytes.len() - i).is_multiple_of(3) {
            out.push(',');
        }
        out.push(*b as char);
    }
    out
}

/// 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-operation summary.
pub fn format_bytes(n: u64) -> String {
    const UNITS: &[&str] = &["B", "KiB", "MiB", "GiB", "TiB"];
    let mut size = n as f64;
    let mut unit = 0;
    while size >= 1024.0 && unit < UNITS.len() - 1 {
        size /= 1024.0;
        unit += 1;
    }
    if unit == 0 {
        format!("{n} {}", UNITS[unit])
    } else {
        format!("{size:.1} {}", UNITS[unit])
    }
}

/// 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/squash.rs).
    let close = cformat!("<bright-black>)</>");
    cformat!(
        " <bright-black>({} {word} · {}</>{close}",
        format_count(files),
        format_bytes(bytes),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_format_count() {
        assert_eq!(format_count(0), "0");
        assert_eq!(format_count(42), "42");
        assert_eq!(format_count(999), "999");
        assert_eq!(format_count(1_000), "1,000");
        assert_eq!(format_count(12_345), "12,345");
        assert_eq!(format_count(1_234_567), "1,234,567");
    }

    #[test]
    fn test_format_bytes() {
        assert_eq!(format_bytes(0), "0 B");
        assert_eq!(format_bytes(512), "512 B");
        assert_eq!(format_bytes(1024), "1.0 KiB");
        assert_eq!(format_bytes(1_536), "1.5 KiB");
        assert_eq!(format_bytes(1_048_576), "1.0 MiB");
        assert_eq!(format_bytes(1_610_612_736), "1.5 GiB");
    }

    #[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"));
    }

    // Not cfg-gated: covers the disabled-state counting contract in both the
    // `cli` implementation and the no-`cli` stub.
    #[test]
    fn test_disabled_still_counts() {
        let p = Progress::disabled();
        p.record(1_000_000);
        p.record(2_000_000);
        assert_eq!(p.totals(), (2, 3_000_000));
        p.finish();
    }
}