kache 1.2.2

Compiler cache for Rust, C/C++ and CUDA, with S3, GCS, shared-filesystem and OCI remotes.
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
//! Shared layout for human-readable command output: aligned label/value rows,
//! column tables, and the number, byte, duration and path forms every command
//! prints the same way. JSON output does not go through here.

#[cfg(not(test))]
use std::io::IsTerminal;
use std::path::Path;

/// Human messages go to stderr in JSON mode. JSON documents use
/// `machine::emit` directly, so helpers cannot mix prose into stdout.
macro_rules! human_println {
    () => { $crate::term::print_line(format_args!("")) };
    ($($args:tt)*) => { $crate::term::print_line(format_args!($($args)*)) };
}
pub(crate) use human_println;

pub(crate) fn print_line(args: std::fmt::Arguments<'_>) {
    let text = args.to_string();
    if crate::machine::is_json() {
        eprintln!("{}", strip_sgr(&text));
    } else if Output::current().color {
        println!("{text}");
    } else {
        println!("{}", strip_sgr(&text));
    }
}

pub(crate) fn strip_sgr(text: &str) -> String {
    let mut out = String::new();
    let mut rest = text;
    while let Some((plain, code)) = rest.split_once("\x1b[") {
        out.push_str(plain);
        let after_sgr = code
            .find(|c: char| !c.is_ascii_digit() && c != ';')
            .and_then(|end| code[end..].strip_prefix('m'));
        match after_sgr {
            Some(after) => rest = after,
            None => {
                out.push_str("\x1b[");
                rest = code;
            }
        }
    }
    out.push_str(rest);
    out
}

#[derive(Clone, Copy)]
pub(crate) enum Style {
    Heading,
    Value,
    Muted,
    Success,
    Warning,
    Error,
}

#[derive(Clone, Copy)]
struct Output {
    color: bool,
    columns: Option<usize>,
}

impl Output {
    #[cfg(not(test))]
    fn current() -> Self {
        let terminal = std::io::stdout().is_terminal();
        Self {
            color: use_color(
                terminal,
                std::env::var_os("NO_COLOR").is_some_and(|value| !value.is_empty()),
                std::env::var("TERM").ok().as_deref(),
            ),
            columns: terminal
                .then(|| {
                    usable_columns(
                        crossterm::terminal::size().ok().map(|(w, _)| w),
                        std::env::var("COLUMNS").ok().as_deref(),
                    )
                })
                .flatten(),
        }
    }

    // Renderer snapshots use fixed settings. Integration tests exercise the
    // command binary in a real terminal, including color and width detection.
    #[cfg(test)]
    fn current() -> Self {
        Self {
            color: false,
            columns: None,
        }
    }

    fn paint(self, text: &str, style: Style) -> String {
        if !self.color || text.is_empty() {
            return strip_sgr(text);
        }
        let code = match style {
            Style::Heading => "1;36",
            Style::Value => "1",
            Style::Muted => "2",
            Style::Success => "32",
            Style::Warning => "33",
            Style::Error => "31",
        };
        format!("\x1b[{code}m{text}\x1b[0m")
    }
}

/// Narrower than this, a reported width is not a real terminal's: some
/// multiplexers and `script` report 0 columns without an error.
const MIN_COLUMNS: usize = 20;

/// The width to wrap at: the terminal's, then `$COLUMNS`, each only when it
/// is at least [`MIN_COLUMNS`]. `None` means no wrapping.
fn usable_columns(reported: Option<u16>, env_columns: Option<&str>) -> Option<usize> {
    let usable = |columns: usize| (columns >= MIN_COLUMNS).then_some(columns);
    reported
        .map(usize::from)
        .and_then(usable)
        .or_else(|| env_columns?.trim().parse().ok().and_then(usable))
}

fn use_color(terminal: bool, no_color: bool, term: Option<&str>) -> bool {
    terminal && !no_color && term != Some("dumb")
}

pub(crate) fn paint(text: impl AsRef<str>, style: Style) -> String {
    Output::current().paint(text.as_ref(), style)
}

pub(crate) fn heading(text: impl AsRef<str>) -> String {
    paint(text, Style::Heading)
}

pub(crate) fn clap_styles() -> clap::builder::Styles {
    use clap::builder::styling::AnsiColor;
    clap::builder::Styles::styled()
        .header(AnsiColor::Cyan.on_default().bold())
        .usage(AnsiColor::Cyan.on_default().bold())
        .literal(clap::builder::styling::Style::new().bold())
        .placeholder(clap::builder::styling::Style::new())
        .error(AnsiColor::Red.on_default().bold())
}

/// Each section gets a heading and its own columns. Long notes continue
/// beneath the note column, or beneath the value on narrow terminals.
pub(crate) type Row<'a> = (&'a str, String, String);
pub(crate) type NamedSection<'a> = (&'a str, Vec<Row<'a>>);

pub(crate) fn named_sections(sections: &[NamedSection<'_>]) -> Vec<String> {
    let output = Output::current();
    let mut lines = Vec::new();
    for (name, rows) in sections.iter().filter(|(_, rows)| !rows.is_empty()) {
        if !lines.is_empty() {
            lines.push(String::new());
        }
        lines.push(output.paint(name, Style::Heading));
        lines.extend(rows_with(rows, output));
    }
    lines
}

/// Rows without a section heading. Commands print through
/// [`named_sections`]; tests render single rows with this.
#[cfg(test)]
pub(crate) fn rows(rows: &[Row<'_>]) -> Vec<String> {
    rows_with(rows, Output::current())
}

fn rows_with(rows: &[Row<'_>], output: Output) -> Vec<String> {
    let label_width = rows
        .iter()
        .map(|(label, _, _)| width(label))
        .max()
        .unwrap_or(0);
    let value_width = rows
        .iter()
        .filter(|(_, _, note)| !note.is_empty())
        .map(|(_, value, _)| width(value))
        .max()
        .unwrap_or(0);
    rows.iter()
        .flat_map(|(label, value, note)| {
            let prefix = format!(
                "  {}   {}",
                pad(label, label_width),
                output.paint(value, Style::Value)
            );
            if note.is_empty() {
                return vec![prefix.trim_end().to_string()];
            }
            let note_column = 2 + label_width + 3 + value_width + 3;
            let (indent, first) = match output.columns {
                Some(columns) if note_column + 16 > columns => (2 + label_width + 3, false),
                _ => (note_column, true),
            };
            let available = output
                .columns
                .map(|columns| columns.saturating_sub(indent).max(1));
            let wrapped = wrap(note, available);
            let mut lines = vec![if first {
                format!(
                    "{prefix}{}   {}",
                    " ".repeat(value_width.saturating_sub(width(value))),
                    output.paint(&wrapped[0], Style::Muted)
                )
            } else {
                prefix
            }];
            let start = usize::from(first);
            lines.extend(
                wrapped[start..].iter().map(|line| {
                    format!("{}{}", " ".repeat(indent), output.paint(line, Style::Muted))
                }),
            );
            lines
        })
        .collect()
}

/// Wrap prose at spaces; keep paths and other indivisible values intact.
fn wrap(text: &str, columns: Option<usize>) -> Vec<String> {
    let Some(columns) = columns else {
        return vec![text.to_owned()];
    };
    let mut lines = Vec::new();
    let mut line = String::new();
    for word in text.split_whitespace() {
        if !line.is_empty() && width(&line) + 1 + width(word) > columns {
            lines.push(std::mem::take(&mut line));
        }
        if !line.is_empty() {
            line.push(' ');
        }
        line.push_str(word);
    }
    lines.push(line);
    lines
}

/// How a table column lines up.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Align {
    Left,
    Right,
}

/// A header row and body rows under a two-space indent, each column as wide
/// as its widest cell. The last column is not padded.
pub(crate) fn table(header: &[&str], align: &[Align], body: &[Vec<String>]) -> Vec<String> {
    let columns = header.len();
    let mut widths: Vec<usize> = header.iter().map(|cell| width(cell)).collect();
    for row in body {
        for (column, cell) in row.iter().enumerate().take(columns) {
            widths[column] = widths[column].max(width(cell));
        }
    }
    let line = |cells: &mut dyn Iterator<Item = &str>| {
        let mut out = String::from("  ");
        for (column, cell) in cells.enumerate().take(columns) {
            if column > 0 {
                out.push_str("   ");
            }
            match align.get(column).copied().unwrap_or(Align::Left) {
                Align::Right => out.push_str(&pad_left(cell, widths[column])),
                Align::Left => out.push_str(&pad(cell, widths[column])),
            }
        }
        out.trim_end().to_string()
    };
    let mut lines = vec![heading(line(&mut header.iter().copied()))];
    for row in body {
        lines.push(line(&mut row.iter().map(String::as_str)));
    }
    lines
}

/// `3,018`: thousands grouped with commas.
pub(crate) fn count(n: u64) -> String {
    let digits = n.to_string();
    let mut out = String::with_capacity(digits.len() + digits.len() / 3);
    for (index, digit) in digits.chars().enumerate() {
        if index > 0 && (digits.len() - index).is_multiple_of(3) {
            out.push(',');
        }
        out.push(digit);
    }
    out
}

/// `1 entry`, `3,018 entries`: a grouped count and the noun that agrees
/// with it.
pub(crate) fn counted(n: u64, one: &str, many: &str) -> String {
    format!("{} {}", count(n), if n == 1 { one } else { many })
}

/// `1.2 GiB`: binary units, the same form in every command.
pub(crate) fn bytes(n: u64) -> String {
    bytesize::ByteSize(n).to_string()
}

/// `~9 min`, `2.0 s`, `45 ms`: the largest unit that keeps the number short.
/// Seconds carry one decimal, so 1,989 ms reads `2.0 s`, not `1 s`. Minutes
/// and hours are rounded, so they carry a `~`.
pub(crate) fn duration_ms(ms: u64) -> String {
    let secs = ms / 1000;
    let tenths = ms.saturating_add(50) / 100;
    if secs >= 3600 {
        format!("~{:.1} h", secs as f64 / 3600.0)
    } else if tenths >= 600 {
        format!("~{} min", (secs + 30) / 60)
    } else if ms >= 1000 {
        format!("{:.1} s", tenths as f64 / 10.0)
    } else {
        format!("{ms} ms")
    }
}

/// The first 12 characters of a cache key: the one short form every human
/// report prints. A shorter key is printed whole.
pub(crate) fn short_key(key: &str) -> &str {
    key.get(..12).unwrap_or(key)
}

/// `2026-10-14 17:18:56` in this machine's zone.
pub(crate) fn local_datetime(at: chrono::DateTime<chrono::Utc>) -> String {
    datetime_in(at, &chrono::Local)
}

/// `17:18:56` in this machine's zone.
pub(crate) fn local_clock(at: chrono::DateTime<chrono::Utc>) -> String {
    clock_in(at, &chrono::Local)
}

/// A store timestamp (`2026-10-14 15:18:56`, UTC as SQLite writes it) in this
/// machine's zone; the input unchanged when it does not parse.
pub(crate) fn local_store_time(utc: &str) -> String {
    store_time_in(utc, &chrono::Local)
}

fn datetime_in<Tz: chrono::TimeZone>(at: chrono::DateTime<chrono::Utc>, zone: &Tz) -> String
where
    Tz::Offset: std::fmt::Display,
{
    at.with_timezone(zone)
        .format("%Y-%m-%d %H:%M:%S")
        .to_string()
}

fn clock_in<Tz: chrono::TimeZone>(at: chrono::DateTime<chrono::Utc>, zone: &Tz) -> String
where
    Tz::Offset: std::fmt::Display,
{
    at.with_timezone(zone).format("%H:%M:%S").to_string()
}

fn store_time_in<Tz: chrono::TimeZone>(utc: &str, zone: &Tz) -> String
where
    Tz::Offset: std::fmt::Display,
{
    chrono::NaiveDateTime::parse_from_str(utc, "%Y-%m-%d %H:%M:%S")
        .map(|naive| datetime_in(naive.and_utc(), zone))
        .unwrap_or_else(|_| utc.to_string())
}

/// `12.5%`.
pub(crate) fn percent(value: f64) -> String {
    format!("{value:.1}%")
}

/// `path` with the home directory written as `~`.
pub(crate) fn home_path(path: &Path) -> String {
    home_path_in(path, dirs::home_dir().as_deref())
}

/// `path` with the home directory written as `$HOME`, for a command people
/// paste into a shell: unlike `~`, it also expands inside double quotes.
pub(crate) fn shell_home_path(path: &Path) -> String {
    shell_home_path_in(path, dirs::home_dir().as_deref())
}

fn shell_home_path_in(path: &Path, home: Option<&Path>) -> String {
    match home.and_then(|home| path.strip_prefix(home).ok()) {
        Some(rest) if rest.as_os_str().is_empty() => "$HOME".to_string(),
        Some(rest) => format!("$HOME/{}", rest.display()),
        None => path.display().to_string(),
    }
}

fn home_path_in(path: &Path, home: Option<&Path>) -> String {
    match home.and_then(|home| path.strip_prefix(home).ok()) {
        Some(rest) if rest.as_os_str().is_empty() => "~".to_string(),
        Some(rest) => format!("~{}{}", std::path::MAIN_SEPARATOR, rest.display()),
        None => path.display().to_string(),
    }
}

fn width(text: &str) -> usize {
    ratatui::text::Span::raw(strip_sgr(text)).width()
}

fn pad(text: &str, to: usize) -> String {
    format!("{text}{}", " ".repeat(to.saturating_sub(width(text))))
}

fn pad_left(text: &str, to: usize) -> String {
    format!("{}{text}", " ".repeat(to.saturating_sub(width(text))))
}

/// A spinner and the time so far on stderr while a slow step runs, so a
/// command that is working does not look hung. It draws only on an
/// interactive stderr and outside JSON mode, and clears its line when
/// dropped, before the step prints its result.
pub(crate) struct Ticker {
    stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
    thread: Option<std::thread::JoinHandle<()>>,
}

impl Ticker {
    pub(crate) fn start(label: impl Into<String>) -> Self {
        #[cfg(not(test))]
        let draws = std::io::stderr().is_terminal() && !crate::machine::is_json();
        #[cfg(test)]
        let draws = false;
        Self::start_if(draws, label.into())
    }

    fn start_if(draws: bool, label: String) -> Self {
        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let thread = draws.then(|| {
            let stop = stop.clone();
            std::thread::spawn(move || {
                use std::io::Write;
                const FRAMES: [char; 10] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
                let started = std::time::Instant::now();
                let mut frame = 0;
                while !stop.load(std::sync::atomic::Ordering::Relaxed) {
                    let elapsed = duration_ms(started.elapsed().as_millis() as u64);
                    let mut err = std::io::stderr().lock();
                    let _ = write!(err, "\r\x1b[2K{} {label} {elapsed}", FRAMES[frame]);
                    let _ = err.flush();
                    drop(err);
                    frame = (frame + 1) % FRAMES.len();
                    std::thread::sleep(std::time::Duration::from_millis(100));
                }
                let _ = write!(std::io::stderr(), "\r\x1b[2K");
            })
        });
        Self { stop, thread }
    }
}

impl Drop for Ticker {
    fn drop(&mut self) {
        self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}

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

    #[test]
    fn a_ticker_stops_and_clears_when_dropped() {
        let quiet = Ticker::start_if(false, "Running GC".into());
        assert!(quiet.thread.is_none());
        let drawing = Ticker::start_if(true, "Running GC".into());
        assert!(drawing.thread.is_some());
        let stop = drawing.stop.clone();
        drop(drawing);
        assert!(stop.load(std::sync::atomic::Ordering::Relaxed));
    }

    #[test]
    fn help_styles_use_the_shared_heading_color() {
        use clap::builder::styling::{AnsiColor, Color};
        let styles = clap_styles();
        assert_eq!(
            styles.get_header().get_fg_color(),
            Some(Color::Ansi(AnsiColor::Cyan))
        );
        assert_eq!(
            styles.get_usage().get_fg_color(),
            Some(Color::Ansi(AnsiColor::Cyan))
        );
    }

    #[test]
    fn a_zero_or_tiny_width_falls_back_to_columns_then_no_wrapping() {
        assert_eq!(usable_columns(Some(80), Some("120")), Some(80));
        assert_eq!(usable_columns(Some(20), None), Some(20));
        assert_eq!(usable_columns(Some(0), Some("100")), Some(100));
        assert_eq!(usable_columns(Some(19), Some(" 90 ")), Some(90));
        assert_eq!(usable_columns(None, Some("100")), Some(100));
        assert_eq!(usable_columns(Some(0), Some("0")), None);
        assert_eq!(usable_columns(Some(0), Some("19")), None);
        assert_eq!(usable_columns(Some(0), Some("wide")), None);
        assert_eq!(usable_columns(Some(0), None), None);
    }

    #[test]
    fn notes_use_the_inline_column_at_exactly_sixteen_remaining_cells() {
        let rows = [("A", "v".into(), "0123456789012345".into())];
        assert_eq!(
            rows_with(
                &rows,
                Output {
                    color: false,
                    columns: Some(26)
                }
            ),
            ["  A   v   0123456789012345"]
        );
        assert_eq!(
            rows_with(
                &rows,
                Output {
                    color: false,
                    columns: Some(25)
                }
            ),
            ["  A   v", "      0123456789012345"]
        );
    }

    #[test]
    fn color_requires_a_capable_terminal_without_no_color() {
        assert!(use_color(true, false, Some("xterm-256color")));
        assert!(use_color(true, false, None));
        assert!(!use_color(false, false, Some("xterm")));
        assert!(!use_color(true, true, Some("xterm")));
        assert!(!use_color(true, false, Some("dumb")));
    }

    #[test]
    fn styled_rows_keep_alignment_and_wrap_notes() {
        let output = Output {
            color: true,
            columns: Some(45),
        };
        let rows = vec![(
            "Daemon",
            output.paint("✓", Style::Success),
            "running with the configured cache directory".into(),
        )];
        let lines = rows_with(&rows, output);
        assert_eq!(
            lines.iter().map(|line| strip_sgr(line)).collect::<Vec<_>>(),
            [
                "  Daemon   ✓   running with the configured",
                "               cache directory",
            ]
        );
        assert!(lines[0].contains("\x1b[32m✓\x1b[0m"));
        assert!(lines[0].contains("\x1b[2m"));
        assert!(lines.iter().all(|line| width(line) <= 45));
        let narrow = rows_with(
            &rows,
            Output {
                color: false,
                columns: Some(24),
            },
        );
        assert_eq!(narrow[0], "  Daemon   ✓");
        assert_eq!(narrow[1], "           running with");
        assert!(narrow.iter().all(|line| width(line) <= 24));
    }

    #[test]
    fn plain_output_keeps_text_and_complete_paths() {
        let plain = Output {
            color: false,
            columns: None,
        };
        assert_eq!(plain.paint("ready", Style::Success), "ready");
        assert_eq!(
            Output {
                color: true,
                columns: None
            }
            .paint("", Style::Value),
            ""
        );
        assert_eq!(strip_sgr("\x1b[1;36mTitle\x1b[0m ✓"), "Title ✓");
        assert_eq!(strip_sgr("a\x1b[2Jb"), "a\x1b[2Jb");
        assert_eq!(strip_sgr("\x1b[31"), "\x1b[31");
        assert_eq!(
            strip_sgr("prefix\x1b[31mred\x1b[0m suffix"),
            "prefixred suffix"
        );
        assert_eq!(strip_sgr("\x1b[mplain"), "plain");
        assert_eq!(strip_sgr("a\x1b[2J\x1b[31mred\x1b[0m"), "a\x1b[2Jred");
        assert_eq!(wrap("one two three", Some(7)), ["one two", "three"]);
        assert_eq!(wrap("/a/very/long/path", Some(4)), ["/a/very/long/path"]);
        assert_eq!(wrap("a  b", None), ["a  b"]);
        assert_eq!(wrap("", Some(20)), [""]);
        assert_eq!(width("缓存"), 4);
        assert_eq!(width("\x1b[32m✓\x1b[0m"), 1);
    }

    #[test]
    fn named_sections_skip_empty_groups_and_keep_local_columns() {
        let lines = named_sections(&[
            ("Empty", Vec::new()),
            ("Builds", vec![("Hits", "1".into(), "cached".into())]),
            (
                "Services",
                vec![("Daemon", "running".into(), String::new())],
            ),
        ]);
        assert_eq!(
            lines,
            [
                "Builds",
                "  Hits   1   cached",
                "",
                "Services",
                "  Daemon   running"
            ]
        );
        assert!(named_sections(&[]).is_empty());
    }

    #[test]
    fn tables_right_align_numbers_and_leave_the_last_column_open() {
        let lines = table(
            &["FREEABLE", "IDLE", "PATH"],
            &[Align::Right, Align::Right, Align::Left],
            &[
                vec!["10.3 GiB".into(), "12h".into(), "~/a".into()],
                vec!["0 B".into(), "3d".into(), "~/longer/path".into()],
            ],
        );
        assert_eq!(
            lines,
            [
                "  FREEABLE   IDLE   PATH",
                "  10.3 GiB    12h   ~/a",
                "       0 B     3d   ~/longer/path",
            ]
        );
        let left = table(
            &["A", "B"],
            &[Align::Left, Align::Left],
            &[vec!["long".into(), "x".into()]],
        );
        assert_eq!(left, ["  A      B", "  long   x"]);
    }

    #[test]
    fn counts_group_thousands() {
        assert_eq!(count(0), "0");
        assert_eq!(count(999), "999");
        assert_eq!(count(1_000), "1,000");
        assert_eq!(count(3_018), "3,018");
        assert_eq!(count(1_234_567), "1,234,567");
    }

    #[test]
    fn counted_nouns_agree_with_the_count() {
        assert_eq!(counted(0, "entry", "entries"), "0 entries");
        assert_eq!(counted(1, "entry", "entries"), "1 entry");
        assert_eq!(counted(2, "entry", "entries"), "2 entries");
        assert_eq!(counted(1_000, "key", "keys"), "1,000 keys");
    }

    #[test]
    fn durations_pick_the_largest_short_unit() {
        assert_eq!(duration_ms(0), "0 ms");
        assert_eq!(duration_ms(999), "999 ms");
        assert_eq!(duration_ms(1_000), "1.0 s");
        assert_eq!(duration_ms(1_989), "2.0 s");
        assert_eq!(duration_ms(1_949), "1.9 s");
        assert_eq!(duration_ms(12_340), "12.3 s");
        assert_eq!(duration_ms(59_949), "59.9 s");
        assert_eq!(duration_ms(59_950), "~1 min");
        assert_eq!(duration_ms(60_000), "~1 min");
        assert_eq!(duration_ms(89_000), "~1 min");
        assert_eq!(duration_ms(90_000), "~2 min");
        assert_eq!(duration_ms(3_599_000), "~60 min");
        assert_eq!(duration_ms(3_600_000), "~1.0 h");
        assert_eq!(duration_ms(5_400_000), "~1.5 h");
    }

    #[test]
    fn cache_keys_have_one_short_form() {
        assert_eq!(short_key("96b68103bea22193ffee"), "96b68103bea2");
        assert_eq!(short_key("96b68103bea2"), "96b68103bea2");
        assert_eq!(short_key("abc"), "abc");
        assert_eq!(short_key(""), "");
    }

    #[test]
    fn times_render_in_the_given_zone() {
        let zone = chrono::FixedOffset::east_opt(2 * 3600).unwrap();
        let at = chrono::DateTime::parse_from_rfc3339("2026-10-14T15:18:56Z")
            .unwrap()
            .with_timezone(&chrono::Utc);
        assert_eq!(datetime_in(at, &zone), "2026-10-14 17:18:56");
        assert_eq!(clock_in(at, &zone), "17:18:56");
        assert_eq!(
            store_time_in("2026-10-14 15:18:56", &zone),
            "2026-10-14 17:18:56"
        );
        assert_eq!(store_time_in("not a time", &zone), "not a time");
        assert_eq!(local_datetime(at), datetime_in(at, &chrono::Local));
        assert_eq!(local_clock(at), clock_in(at, &chrono::Local));
        assert_eq!(
            local_store_time("2026-10-14 15:18:56"),
            datetime_in(at, &chrono::Local)
        );
    }

    #[test]
    fn percents_and_bytes_have_one_form() {
        assert_eq!(percent(88.8), "88.8%");
        assert_eq!(percent(0.0), "0.0%");
        assert_eq!(bytes(0), "0 B");
        assert_eq!(bytes(1536), "1.5 KiB");
        assert_eq!(bytes(3 << 30), "3.0 GiB");
    }

    #[test]
    fn a_path_under_home_starts_with_a_tilde() {
        let home = Path::new("/Users/me");
        assert_eq!(
            home_path_in(Path::new("/Users/me/src/app"), Some(home)),
            format!("~{}src/app", std::path::MAIN_SEPARATOR)
        );
        assert_eq!(home_path_in(Path::new("/Users/me"), Some(home)), "~");
        assert_eq!(
            home_path_in(Path::new("/Users/meadow/x"), Some(home)),
            "/Users/meadow/x"
        );
        assert_eq!(home_path_in(Path::new("/tmp/x"), None), "/tmp/x");
    }

    #[test]
    fn the_shell_path_uses_this_users_home() {
        let outside = Path::new("/kache-test-outside-home/x");
        assert_eq!(shell_home_path(outside), "/kache-test-outside-home/x");
        if let Some(home) = dirs::home_dir() {
            assert_eq!(shell_home_path(&home.join("shims")), "$HOME/shims");
        }
    }

    #[test]
    fn a_shell_path_under_home_starts_with_the_home_variable() {
        let home = Path::new("/home/me");
        assert_eq!(
            shell_home_path_in(Path::new("/home/me/.local/shims"), Some(home)),
            "$HOME/.local/shims"
        );
        assert_eq!(shell_home_path_in(home, Some(home)), "$HOME");
        assert_eq!(
            shell_home_path_in(Path::new("/home/meadow"), Some(home)),
            "/home/meadow"
        );
        assert_eq!(shell_home_path_in(Path::new("/opt/x"), None), "/opt/x");
    }
}