zarust 0.2.0

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
//! 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, StderrLock, 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;

#[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
    }

    /// Writes a line unconditionally, e.g. `list` output that may be piped.
    pub fn line(&mut self, args: Arguments<'_>) -> Outcome {
        self.erase_bar();
        writeln!(self.out, "{args}").map_err(Into::into)
    }

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

    /// Writes a line only under `--verbose`.
    pub fn detail(&mut self, args: Arguments<'_>) -> Outcome {
        if self.verbosity != Verbosity::Verbose {
            return Ok(());
        }
        let Palette { dim, reset, .. } = self.palette;
        self.erase_bar();
        writeln!(self.out, "{dim}{:>10}  {args}{reset}", "·").map_err(Into::into)
    }

    /// A status line with a right-aligned colored label, e.g. `    packed  out.zar`.
    /// The label column lines up with the progress bar's, so the bar appears to
    /// resolve into the result.
    pub fn status(&mut self, color: &str, label: &str, args: Arguments<'_>) -> Outcome {
        if self.verbosity == Verbosity::Quiet {
            return Ok(());
        }
        let Palette { bold, reset, .. } = self.palette;
        self.erase_bar();
        writeln!(self.out, "{color}{bold}{label:>10}{reset}  {args}").map_err(Into::into)
    }

    /// 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.verbosity == Verbosity::Quiet {
            return Ok(());
        }
        let Palette { dim, reset, .. } = self.palette;
        self.erase_bar();
        writeln!(self.out, "{:>10}  {dim}{args}{reset}", "").map_err(Into::into)
    }

    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,
    drawn: bool,
    ansi: 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,
            drawn: false,
            ansi,
        }
    }

    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.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,
        );

        let mut stderr = io::stderr().lock();
        let _ = self.paint(&mut stderr, &line);
        let _ = stderr.flush();
        // Only the uncolored form is ever padded, so counting chars is exact there.
        self.width = 10 + 2 + BAR_CELLS + 2 + stats.chars().count();
        self.drawn = true;
        self.last_draw = Instant::now();
    }

    fn paint(&self, stderr: &mut StderrLock<'_>, line: &str) -> io::Result<()> {
        if self.ansi {
            write!(stderr, "\r\x1b[2K{line}")
        } else {
            // Pad to the previous width so leftovers from a longer line vanish.
            write!(stderr, "\r{line:<width$}", width = self.width)
        }
    }

    fn erase(&mut self) {
        if !self.drawn {
            return;
        }
        let mut stderr = io::stderr().lock();
        if self.ansi {
            let _ = write!(stderr, "\r\x1b[2K");
        } else {
            let _ = write!(stderr, "\r{:width$}\r", "", width = self.width);
        }
        let _ = stderr.flush();
        self.drawn = false;
        self.width = 0;
    }
}

/// Renders a path for display with forward slashes, so a single line never
/// mixes separators after joining a user-supplied path with a generated name.
pub fn display_path(path: &std::path::Path) -> String {
    let text = path.to_string_lossy();
    if cfg!(windows) {
        text.replace('\\', "/")
    } else {
        text.into_owned()
    }
}

/// 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 color_choice_overrides_terminal_detection() {
        assert!(supports_ansi(ColorChoice::Always, false));
        assert!(!supports_ansi(ColorChoice::Never, true));
        assert!(!supports_ansi(ColorChoice::Auto, false));
    }
}