zarust 0.2.1

Rust implementation of the ZArchive format
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//! Terminal output: color detection, human-readable formatting, and a progress
//! bar that only appears when a human is watching.

use std::{
    env,
    fmt::Arguments,
    io::{self, BufWriter, IsTerminal, StdoutLock, Write},
    time::{Duration, Instant},
};

use crate::cli::{Outcome, args::Verbosity};

/// How often the bar may repaint. Fast enough to look live, slow enough that
/// drawing never shows up in a profile.
const REDRAW_INTERVAL: Duration = Duration::from_millis(50);
const BAR_CELLS: usize = 24;

/// Width of the leading label column. The progress bar and every status line
/// share it, so a finished bar appears to resolve into its result line.
const LABEL_COLUMN: usize = 10;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ColorChoice {
    Auto,
    Always,
    Never,
}

/// ANSI escapes, or empty strings when color is off, so callers can interpolate
/// them unconditionally without allocating.
#[derive(Clone, Copy)]
pub struct Palette {
    pub reset: &'static str,
    pub bold: &'static str,
    pub dim: &'static str,
    /// Errors and failed checks.
    pub red: &'static str,
    /// Successful outcomes and the filled part of the progress bar.
    pub green: &'static str,
    /// Numbers worth noticing: sizes, ratios, counts.
    pub yellow: &'static str,
    /// Directories, and the active verb while work is in flight.
    pub cyan: &'static str,
    /// Command and option names in help.
    pub magenta: &'static str,
}

impl Palette {
    pub const OFF: Self = Self {
        reset: "",
        bold: "",
        dim: "",
        red: "",
        green: "",
        yellow: "",
        cyan: "",
        magenta: "",
    };

    /// Bright variants read well on both light and dark backgrounds.
    pub const ON: Self = Self {
        reset: "\x1b[0m",
        bold: "\x1b[1m",
        dim: "\x1b[2m",
        red: "\x1b[91m",
        green: "\x1b[92m",
        yellow: "\x1b[93m",
        cyan: "\x1b[96m",
        magenta: "\x1b[95m",
    };
}

/// Decides whether ANSI escapes are safe to emit on `stream`.
fn supports_ansi(choice: ColorChoice, is_terminal: bool) -> bool {
    match choice {
        ColorChoice::Never => return false,
        ColorChoice::Always => return true,
        ColorChoice::Auto => {}
    }
    if !is_terminal {
        return false;
    }
    // https://no-color.org: any non-empty value disables color.
    if env::var_os("NO_COLOR").is_some_and(|value| !value.is_empty()) {
        return false;
    }
    if cfg!(windows) {
        // Legacy conhost needs VT processing turned on explicitly, which we
        // cannot do without a system-call crate. Terminals that already handle
        // escapes announce themselves through the environment.
        [
            "WT_SESSION",
            "TERM_PROGRAM",
            "ConEmuANSI",
            "ANSICON",
            "TERM",
        ]
        .iter()
        .any(|name| env::var_os(name).is_some())
    } else {
        env::var("TERM").as_deref() != Ok("dumb")
    }
}

/// The palette to use when writing errors and other stderr diagnostics.
pub fn stderr_palette(choice: ColorChoice) -> Palette {
    if supports_ansi(choice, io::stderr().is_terminal()) {
        Palette::ON
    } else {
        Palette::OFF
    }
}

/// Owns every output stream the CLI writes to, so the progress bar on stderr and
/// ordinary lines on stdout never interleave mid-line.
pub struct Reporter {
    out: BufWriter<StdoutLock<'static>>,
    palette: Palette,
    verbosity: Verbosity,
    bar: Option<Bar>,
}

impl Reporter {
    pub fn new(color: ColorChoice, verbosity: Verbosity, progress: bool) -> Self {
        let stdout = io::stdout();
        let palette = if supports_ansi(color, stdout.is_terminal()) {
            Palette::ON
        } else {
            Palette::OFF
        };
        let stderr = io::stderr();
        // A bar is only useful on an interactive stderr; in a pipe or a log it
        // is noise, so we drop it entirely rather than printing periodic lines.
        let bar = (progress && stderr.is_terminal() && verbosity != Verbosity::Quiet)
            .then(|| Bar::new(supports_ansi(color, true)));
        Self {
            out: BufWriter::new(stdout.lock()),
            palette,
            verbosity,
            bar,
        }
    }

    pub fn palette(&self) -> Palette {
        self.palette
    }

    pub fn is_verbose(&self) -> bool {
        self.verbosity == Verbosity::Verbose
    }

    /// The shared tail of every printing method: the bar must come down before
    /// anything lands on stdout, or the two interleave mid-line.
    fn write(&mut self, args: Arguments<'_>) -> Outcome {
        self.erase_bar();
        self.out.write_fmt(args)?;
        self.out.write_all(b"\n").map_err(Into::into)
    }

    fn quiet(&self) -> bool {
        self.verbosity == Verbosity::Quiet
    }

    /// Writes a line unconditionally, e.g. `list` output that may be piped.
    pub fn line(&mut self, args: Arguments<'_>) -> Outcome {
        self.write(args)
    }

    /// Writes a line unless `--quiet` was given.
    pub fn info(&mut self, args: Arguments<'_>) -> Outcome {
        if self.quiet() {
            return Ok(());
        }
        self.write(args)
    }

    /// Writes a line only under `--verbose`.
    ///
    /// Callers gate on [`is_verbose`](Self::is_verbose) first when building the
    /// argument costs an allocation, since `Arguments` are evaluated eagerly.
    pub fn detail(&mut self, args: Arguments<'_>) -> Outcome {
        if self.verbosity != Verbosity::Verbose {
            return Ok(());
        }
        let Palette { dim, reset, .. } = self.palette;
        self.write(format_args!("{dim}{:>LABEL_COLUMN$}  {args}{reset}", "·"))
    }

    /// A status line with a right-aligned colored label, e.g. `    packed  out.zar`.
    pub fn status(&mut self, color: &str, label: &str, args: Arguments<'_>) -> Outcome {
        if self.quiet() {
            return Ok(());
        }
        let Palette { bold, reset, .. } = self.palette;
        self.write(format_args!(
            "{color}{bold}{label:>LABEL_COLUMN$}{reset}  {args}"
        ))
    }

    /// A dimmed continuation line under the preceding [`status`](Self::status),
    /// indented to the same column.
    pub fn sub(&mut self, args: Arguments<'_>) -> Outcome {
        if self.quiet() {
            return Ok(());
        }
        let Palette { dim, reset, .. } = self.palette;
        self.write(format_args!("{:>LABEL_COLUMN$}  {dim}{args}{reset}", ""))
    }

    /// The two-line block every command ends with: a green label naming what
    /// was produced, then a dimmed detail line.
    pub fn success(&mut self, label: &str, path: &std::path::Path, detail: &str) -> Outcome {
        let Palette {
            green, bold, reset, ..
        } = self.palette;
        self.status(
            green,
            label,
            format_args!("{bold}{}{reset}", super::path::display(path)),
        )?;
        self.sub(format_args!("{detail}"))
    }

    pub fn start_bar(&mut self, label: &'static str, total: u64) {
        if let Some(bar) = &mut self.bar {
            bar.start(label, total);
        }
    }

    pub fn advance(&mut self, bytes: u64) {
        if let Some(bar) = &mut self.bar {
            bar.advance(bytes);
        }
    }

    pub fn finish_bar(&mut self) {
        if let Some(bar) = &mut self.bar {
            bar.erase();
        }
    }

    fn erase_bar(&mut self) {
        // stdout is buffered, so flush it before touching stderr; otherwise a
        // repainted bar can land in front of text written earlier.
        if let Some(bar) = &mut self.bar
            && bar.drawn()
        {
            let _ = self.out.flush();
            bar.erase();
        }
    }

    pub fn flush(&mut self) -> io::Result<()> {
        self.finish_bar();
        self.out.flush()
    }
}

impl Drop for Reporter {
    fn drop(&mut self) {
        let _ = self.flush();
    }
}

struct Bar {
    label: &'static str,
    total: u64,
    done: u64,
    started: Instant,
    last_draw: Instant,
    width: usize,
    ansi: bool,
    /// The last frame rendered. Empty means nothing is on screen, so it doubles
    /// as the "is the bar currently drawn" flag.
    last_line: String,
    cursor_hidden: bool,
}

impl Bar {
    fn new(ansi: bool) -> Self {
        let now = Instant::now();
        Self {
            label: "",
            total: 0,
            done: 0,
            started: now,
            last_draw: now,
            width: 0,
            ansi,
            last_line: String::new(),
            cursor_hidden: false,
        }
    }

    /// Whether a frame is currently on screen.
    fn drawn(&self) -> bool {
        !self.last_line.is_empty()
    }

    fn start(&mut self, label: &'static str, total: u64) {
        let now = Instant::now();
        self.label = label;
        self.total = total;
        self.done = 0;
        self.started = now;
        self.last_draw = now - REDRAW_INTERVAL;
        self.last_line.clear();
        self.draw();
    }

    fn advance(&mut self, bytes: u64) {
        self.done = self.done.saturating_add(bytes);
        if self.last_draw.elapsed() >= REDRAW_INTERVAL {
            self.draw();
        }
    }

    fn draw(&mut self) {
        let fraction = if self.total == 0 {
            1.0
        } else {
            (self.done as f64 / self.total as f64).clamp(0.0, 1.0)
        };
        let elapsed = self.started.elapsed().as_secs_f64();
        let speed = if elapsed > 0.0 {
            self.done as f64 / elapsed
        } else {
            0.0
        };
        let eta = if self.done == 0 || fraction >= 1.0 {
            None
        } else {
            Some(Duration::from_secs_f64(
                elapsed * (self.total - self.done) as f64 / self.done as f64,
            ))
        };

        let filled = (fraction * BAR_CELLS as f64).round() as usize;
        let (full, empty) = if self.ansi {
            ('â–ˆ', 'â–‘')
        } else {
            ('#', '.')
        };
        let done: String = std::iter::repeat_n(full, filled).collect();
        let todo: String = std::iter::repeat_n(empty, BAR_CELLS - filled).collect();

        let p = if self.ansi { Palette::ON } else { Palette::OFF };
        let stats = format!(
            "{:>3.0}%  {} / {}  {}/s  eta {}",
            fraction * 100.0,
            format_bytes(self.done as f64),
            format_bytes(self.total as f64),
            format_bytes(speed),
            format_duration(eta),
        );
        let line = format!(
            "{c}{b}{:>10}{r}  {g}{done}{r}{d}{todo}{r}  {y}{stats}{r}",
            self.label,
            c = p.cyan,
            b = p.bold,
            g = p.green,
            d = p.dim,
            y = p.yellow,
            r = p.reset,
        );

        self.last_draw = Instant::now();
        // Nothing visibly changed, so repainting would only make the terminal
        // flicker for no reason.
        if line == self.last_line {
            return;
        }

        let frame = self.frame(&line);
        let mut stderr = io::stderr().lock();
        // One write per frame: several small writes let the terminal render a
        // half-drawn bar, which reads as tearing.
        let _ = stderr.write_all(frame.as_bytes());
        let _ = stderr.flush();

        self.last_line = line;
    }

    /// Builds one complete frame, including its control sequences.
    fn frame(&mut self, line: &str) -> String {
        let mut frame = String::with_capacity(line.len() + 16);
        frame.push('\r');
        if self.ansi {
            // A parked cursor blinking at the end of the bar reads as flicker.
            if !self.cursor_hidden {
                frame.push_str("\x1b[?25l");
                self.cursor_hidden = true;
            }
            frame.push_str(line);
            // Clear *after* writing rather than erasing first, so the line is
            // never momentarily blank.
            frame.push_str("\x1b[K");
        } else {
            // Without escapes the rendered width is just the character count,
            // so pad over whatever the previous, possibly longer, frame left.
            let visible = line.chars().count();
            frame.push_str(line);
            for _ in visible..self.width {
                frame.push(' ');
            }
            self.width = visible;
        }
        frame
    }

    fn erase(&mut self) {
        if !self.drawn() && !self.cursor_hidden {
            return;
        }
        let mut frame = String::with_capacity(24);
        if self.ansi {
            frame.push_str("\r\x1b[K");
            if self.cursor_hidden {
                frame.push_str("\x1b[?25h");
                self.cursor_hidden = false;
            }
        } else {
            frame.push('\r');
            for _ in 0..self.width {
                frame.push(' ');
            }
            frame.push('\r');
        }
        let mut stderr = io::stderr().lock();
        let _ = stderr.write_all(frame.as_bytes());
        let _ = stderr.flush();
        self.width = 0;
        self.last_line.clear();
    }
}

impl Drop for Bar {
    /// The cursor belongs to the user's shell, so restore it even if the command
    /// unwinds before it can erase the bar itself.
    fn drop(&mut self) {
        if self.cursor_hidden {
            let mut stderr = io::stderr().lock();
            let _ = stderr.write_all(b"\r\x1b[K\x1b[?25h");
            let _ = stderr.flush();
        }
    }
}

/// Formats a byte count with a binary unit, e.g. `1.4 GiB`.
pub fn format_bytes(mut bytes: f64) -> String {
    const UNITS: [&str; 7] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"];
    let mut unit = 0;
    while bytes >= 1024.0 && unit + 1 < UNITS.len() {
        bytes /= 1024.0;
        unit += 1;
    }
    if unit == 0 {
        format!("{bytes:.0} B")
    } else {
        format!("{bytes:.1} {}", UNITS[unit])
    }
}

/// Formats a duration as `1m04s` / `2h11m` / `840ms`, or `--` when unknown.
pub fn format_duration(duration: Option<Duration>) -> String {
    let Some(duration) = duration else {
        return "--".to_owned();
    };
    let seconds = duration.as_secs();
    if seconds >= 3600 {
        format!("{}h{:02}m", seconds / 3600, seconds / 60 % 60)
    } else if seconds >= 60 {
        format!("{}m{:02}s", seconds / 60, seconds % 60)
    } else if seconds > 0 {
        format!("{:.1}s", duration.as_secs_f64())
    } else {
        format!("{}ms", duration.as_millis())
    }
}

/// Formats a count with its noun: `1 file`, `3 files`, `2 directories`.
pub fn counted(count: u64, singular: &str, plural: &str) -> String {
    if count == 1 {
        format!("{count} {singular}")
    } else {
        format!("{count} {plural}")
    }
}

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

    #[test]
    fn formats_byte_counts_at_each_scale() {
        assert_eq!(format_bytes(0.0), "0 B");
        assert_eq!(format_bytes(999.0), "999 B");
        assert_eq!(format_bytes(1024.0), "1.0 KiB");
        assert_eq!(format_bytes(1536.0), "1.5 KiB");
        assert_eq!(format_bytes(3.0 * 1024.0 * 1024.0 * 1024.0), "3.0 GiB");
    }

    #[test]
    fn formats_durations_by_magnitude() {
        assert_eq!(format_duration(None), "--");
        assert_eq!(format_duration(Some(Duration::from_millis(840))), "840ms");
        assert_eq!(format_duration(Some(Duration::from_secs(9))), "9.0s");
        assert_eq!(format_duration(Some(Duration::from_secs(64))), "1m04s");
        assert_eq!(format_duration(Some(Duration::from_secs(7860))), "2h11m");
    }

    #[test]
    fn pluralizes_only_when_needed() {
        assert_eq!(counted(1, "file", "files"), "1 file");
        assert_eq!(counted(0, "file", "files"), "0 files");
        assert_eq!(counted(2, "directory", "directories"), "2 directories");
    }

    #[test]
    fn a_frame_writes_over_the_line_instead_of_blanking_it() {
        let mut bar = Bar::new(true);
        let frame = bar.frame("packing");
        // Clearing before the text would show an empty line for one refresh.
        assert!(
            !frame.contains("\x1b[2K"),
            "frame erases the whole line first: {frame:?}"
        );
        let content = frame.find("packing").unwrap();
        let clear = frame.find("\x1b[K").unwrap();
        assert!(clear > content, "clear must follow the text: {frame:?}");
    }

    #[test]
    fn the_cursor_is_hidden_once_and_restored_on_erase() {
        let mut bar = Bar::new(true);
        assert!(bar.frame("a").contains("\x1b[?25l"));
        // Re-emitting the hide sequence every frame is itself a source of flicker.
        assert!(!bar.frame("b").contains("\x1b[?25l"));

        bar.last_line.push_str("something");
        bar.erase();
        assert!(!bar.cursor_hidden);
    }

    #[test]
    fn an_unchanged_frame_is_not_repainted() {
        let mut bar = Bar::new(true);
        bar.start("packing", 1000);
        let painted = bar.last_line.clone();
        assert!(bar.drawn());

        // Advancing by nothing cannot change the rendering, so the frame stands.
        bar.last_draw = Instant::now() - REDRAW_INTERVAL * 2;
        bar.advance(0);
        assert_eq!(bar.last_line, painted);
    }

    #[test]
    fn without_ansi_a_frame_pads_over_the_previous_one() {
        let mut bar = Bar::new(false);
        bar.width = 20;
        let frame = bar.frame("short");
        assert!(!frame.contains('\x1b'), "escapes leaked: {frame:?}");
        assert_eq!(frame, format!("\r{:<20}", "short"));
    }

    #[test]
    fn color_choice_overrides_terminal_detection() {
        assert!(supports_ansi(ColorChoice::Always, false));
        assert!(!supports_ansi(ColorChoice::Never, true));
        assert!(!supports_ansi(ColorChoice::Auto, false));
    }
}