fdu 0.2.0

Fastest native du replacement and detailed file analytics for Python and Rust
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
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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
//! The one-line progress indicator: whether a run may draw it, and what a frame says.
//!
//! The engine reports how much work a run has done; this module owns every presentation
//! decision about showing that, the way `cli` owns color. Two decisions are pure and live
//! here so tests can pin them without a terminal: [`should_draw`], from the `--progress`
//! flag and the [`TerminalFacts`] the process read once, and [`render_frame`], from a
//! snapshot's facts, the elapsed time, the spinner step, the width, and the color flag.
//!
//! Nothing here writes to a stream. The ticker in `progress_ticker` takes a
//! [`ProgressPlan`] resolved before the report starts, redraws through [`render_frame`],
//! and clears the line before anything else is written.

use std::env;
use std::ffi::{OsStr, OsString};
use std::io::{self, IsTerminal};
use std::path::{Path, PathBuf};
use std::time::Duration;

use clap::ValueEnum;
use clap::builder::styling::{AnsiColor, Style as AnsiStyle};

use fdu_core::query::SizeMetric;
use fdu_core::report_format::{STYLE_NAME, byte_style, human_bytes, human_count};
use fdu_core::throughput_rates;

use crate::cli::{paint, progress_duration};

/// When the indicator may be drawn, as `--progress` spells it.
///
/// Mirrors `--color`'s three words, with one deliberate difference: no value draws into
/// a pipe, a file, a log, or CI. `always` lifts only the machine-format rule, for a
/// person who wants the line while watching JSON arrive at their own terminal.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
pub enum ProgressMode {
    /// Draw for a person at an interactive terminal, for human formats only.
    #[default]
    Auto,
    /// Draw for every format, still only at an interactive terminal.
    Always,
    /// Never draw.
    Never,
}

/// What the process learned about stderr, read once and passed in.
///
/// Read in `run_process` rather than wherever the answer is needed, so a test can say
/// what the terminal is instead of inheriting whatever the test runner's is. The
/// default is the least interactive reading, which is also what every existing test
/// ran under before these facts existed.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TerminalFacts {
    /// Whether stderr is a terminal.
    pub stderr_is_terminal: bool,
    /// `TERM` as set, or `None` when unset.
    pub term: Option<OsString>,
    /// Whether an unset `TERM` still allows drawing.
    ///
    /// True on Windows, whose consoles (cmd, PowerShell, Windows Terminal) set no `TERM`;
    /// there whether the console accepts escape sequences is the terminal test. `dumb`
    /// still means non-interactive everywhere.
    pub term_may_be_unset: bool,
    /// `CI` as set, or `None` when unset.
    pub ci: Option<OsString>,
    /// Whether the console will interpret the escape sequences a frame is drawn with.
    ///
    /// Always true off Windows. On Windows it is whether virtual terminal processing
    /// could be enabled for the console; a legacy console that refuses would print the
    /// erase sequence as text, so it counts as non-interactive.
    pub vt_enabled: bool,
}

impl TerminalFacts {
    /// Read the facts from the process, once.
    ///
    /// On Windows this asks the console to enable virtual terminal processing, which
    /// `anstyle-query` does for stdout and stderr together: a run whose stdout is a pipe
    /// reads as non-interactive there even with stderr at a console. Off Windows it
    /// reads nothing but stderr and two variables.
    pub fn detect() -> Self {
        let stderr_is_terminal = io::stderr().is_terminal();
        Self {
            stderr_is_terminal,
            term: env::var_os("TERM"),
            term_may_be_unset: cfg!(windows),
            ci: env::var_os("CI"),
            vt_enabled: virtual_terminal_enabled(stderr_is_terminal),
        }
    }

    /// Whether a person is watching stderr at a terminal that will render a frame.
    ///
    /// Stderr must be a terminal, `TERM` must be set and not `dumb` (or, on Windows,
    /// may be unset), `CI` must be unset or empty, and the console must accept escape
    /// sequences. A `TERM` set to nothing is an unset one: the two are the same thing
    /// everywhere a shell exports variables, so they get the same answer on every
    /// platform. An agent shell observed in this repository runs with `TERM=dumb` and
    /// no terminal, so no agent detection is needed beyond this rule.
    pub fn is_interactive(&self) -> bool {
        let term_allows = match self.term.as_deref().filter(|term| !term.is_empty()) {
            None => self.term_may_be_unset,
            Some(term) => term != "dumb",
        };
        self.stderr_is_terminal
            && term_allows
            && self.ci.as_deref().is_none_or(OsStr::is_empty)
            && self.vt_enabled
    }
}

/// Whether the console will interpret escape sequences, asked only when it matters.
///
/// Off Windows every terminal does, and asking costs nothing. On Windows the question is
/// only worth a console-mode call when stderr is a terminal at all.
#[cfg(not(windows))]
fn virtual_terminal_enabled(_stderr_is_terminal: bool) -> bool {
    true
}

#[cfg(windows)]
fn virtual_terminal_enabled(stderr_is_terminal: bool) -> bool {
    stderr_is_terminal && anstyle_query::windows::enable_ansi_colors() == Some(true)
}

/// Whether a run draws the indicator at all.
///
/// A non-interactive run never draws, whatever the flag says; a command that walks
/// nothing (`--docs`, `--skill`, `--cache-status`, `--cache-clear`) has nothing to show.
/// On an interactive walking run, `auto` draws for the human formats and not for the
/// machine ones, because some agent harnesses run commands under a pseudo-terminal and a
/// redrawn line would pollute their captured stderr; `always` lifts only that rule.
pub(crate) fn should_draw(
    mode: ProgressMode,
    terminal: &TerminalFacts,
    format_is_machine: bool,
    command_walks: bool,
) -> bool {
    if !command_walks || !terminal.is_interactive() {
        return false;
    }
    match mode {
        ProgressMode::Never => false,
        ProgressMode::Always => true,
        ProgressMode::Auto => !format_is_machine,
    }
}

/// What a run resolved about its indicator before any work started.
///
/// The ticker takes this, not the flag and the facts, so the decision is made once in
/// `Cli::run` beside the color decision and never re-derived deeper in.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ProgressPlan {
    /// Whether the ticker draws at all.
    pub draw: bool,
    /// The root as the frame shows it.
    pub root: String,
    /// Whether the frame is colored, under the rule that colors fdu's warnings.
    pub color: bool,
    /// The size metric the answer is measured in, which the frame's bytes follow: a
    /// sparse disk image counted apparent beside an allocated answer can show more
    /// bytes than the disk holds.
    pub size: SizeMetric,
}

/// The root as a frame shows it: under `~` when the home directory is a prefix,
/// otherwise the path as given.
///
/// A prefix is a path prefix, component by component, so a sibling of the home
/// directory that merely shares its spelling is left alone. The report shows paths as
/// given and has no abbreviation of its own; this one exists because the root is the
/// first thing on a line that has to fit.
pub(crate) fn display_root(root: &Path, home: Option<&Path>) -> String {
    if let Some(home) = home.filter(|home| !home.as_os_str().is_empty()) {
        if let Ok(rest) = root.strip_prefix(home) {
            if rest.as_os_str().is_empty() {
                return "~".to_string();
            }
            return Path::new("~").join(rest).display().to_string();
        }
    }
    root.display().to_string()
}

/// The home directory the frame abbreviates, from the variables the cache path uses.
pub(crate) fn home_directory() -> Option<PathBuf> {
    let home = env::var_os("HOME").filter(|value| !value.is_empty());
    #[cfg(windows)]
    let home = home.or_else(|| env::var_os("USERPROFILE").filter(|value| !value.is_empty()));
    home.map(PathBuf::from)
}

/// The phase a run is in, as the frame names it.
///
/// A local mirror of the engine's phase, so the renderer is a pure function the
/// integration maps a snapshot onto rather than a consumer of the engine's type.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Phase {
    /// Reading a snapshot from the cache.
    Loading,
    /// Walking the tree cold.
    Scanning,
    /// Verifying a loaded snapshot against the tree.
    Revalidating,
    /// Reading file bodies.
    Analyzing,
    /// Writing the snapshot.
    Saving,
    /// Assembling the index once the walk is over.
    Indexing,
    /// Building the answer from the index.
    Summarizing,
}

impl Phase {
    /// The longest phase word, which every other one is padded to.
    const PADDED_WIDTH: usize = 12;

    const fn word(self) -> &'static str {
        match self {
            Self::Loading => "Loading",
            Self::Scanning => "Scanning",
            Self::Revalidating => "Revalidating",
            Self::Analyzing => "Analyzing",
            Self::Saving => "Saving",
            Self::Indexing => "Indexing",
            Self::Summarizing => "Summarizing",
        }
    }
}

/// The facts a frame is drawn from: a local mirror of the engine's progress snapshot.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct FrameFacts {
    /// The phase most recently entered.
    pub phase: Phase,
    /// Directories walked so far.
    pub directories: u64,
    /// Files walked so far.
    pub files: u64,
    /// Bytes walked so far, in the size metric the answer is measured in.
    pub bytes: u64,
    /// Content files analyzed, and the candidates known when analysis began.
    pub analysis: Option<(u64, u64)>,
}

/// The braille dots spinner, one cell per redraw.
const SPINNER: [char; 10] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];

/// The narrowest a root is elided to before the facts start giving way.
const MIN_ROOT_COLUMNS: usize = 12;

/// Below this width only the spinner and the phase word are drawn.
const MIN_FULL_WIDTH: usize = 20;

/// Columns a file or directory count is right-aligned in: seven figures with their
/// separators, `9,999,999`. A larger count widens its column rather than being cut.
const COUNT_COLUMNS: usize = 9;

/// Columns a size is right-aligned in: the widest `human_bytes` gives below 1024 PiB,
/// `1023 GiB`.
const BYTES_COLUMNS: usize = 8;

const STYLE_SPINNER: AnsiStyle = AnsiColor::Cyan.on_default();
const STYLE_ROOT: AnsiStyle = STYLE_NAME;
const STYLE_PHASE: AnsiStyle = AnsiStyle::new().bold();
const STYLE_DIM: AnsiStyle = AnsiColor::BrightBlack.on_default();

/// A whole percentage that never reaches 100 before `done` equals `total`.
///
/// Truncated rather than rounded, which is what keeps `99.9%` at `99%`. Nothing of
/// nothing is `100%`: the engine reports `(0, 0)` when the content sidecar answered
/// every candidate and no file needed reading, which is analysis with nothing left to
/// do, not analysis that has not begun. A count past its total is capped at the total.
fn whole_percent(done: u64, total: u64) -> u64 {
    if total == 0 {
        return 100;
    }
    let done = done.min(total);
    u64::try_from(u128::from(done) * 100 / u128::from(total)).unwrap_or(100)
}

/// Columns one character of a root path occupies: one for ASCII, two otherwise.
///
/// Deliberately an overestimate for accented letters, because a frame that reserves a
/// column it does not use is invisible and one that wraps is not.
const fn char_columns(c: char) -> usize {
    if c.is_ascii() { 1 } else { 2 }
}

fn path_columns(text: &str) -> usize {
    text.chars().map(char_columns).sum()
}

/// A root slot: its text, and the columns it occupies.
#[derive(Clone, Debug)]
struct RootSlot {
    text: String,
    columns: usize,
}

impl RootSlot {
    fn new(root: &str) -> Self {
        Self { text: root.to_string(), columns: path_columns(root) }
    }

    /// The root elided in the middle with `…` to at most `target` columns, which must
    /// be fewer than it occupies.
    ///
    /// Whole characters only, so a wide character that would straddle the budget is
    /// left out and the result may come up a column short on either side rather than over.
    fn elided(root: &str, target: usize) -> Self {
        let budget = target.saturating_sub(1);
        let tail_budget = budget / 2;
        let head_budget = budget - tail_budget;

        let mut head = String::new();
        let mut head_columns = 0;
        for c in root.chars() {
            if head_columns + char_columns(c) > head_budget {
                break;
            }
            head.push(c);
            head_columns += char_columns(c);
        }
        let mut tail = Vec::new();
        let mut tail_columns = 0;
        for c in root.chars().rev() {
            if tail_columns + char_columns(c) > tail_budget {
                break;
            }
            tail.push(c);
            tail_columns += char_columns(c);
        }
        let tail: String = tail.into_iter().rev().collect();
        Self { text: format!("{head}…{tail}"), columns: head_columns + 1 + tail_columns }
    }

    /// Columns beyond the character count: one per wide character.
    fn extra_columns(&self) -> usize {
        self.columns - self.text.chars().count()
    }
}

/// The facts slot, in the shape the shrink order works on.
#[derive(Clone, Debug)]
enum FactsSlot {
    None,
    Walk { files: String, dirs: Option<String>, bytes: Option<(String, Option<AnsiStyle>)> },
    Analysis { percent: String, done: String, total: String },
}

impl FactsSlot {
    fn drop_dirs(&mut self) {
        if let Self::Walk { dirs, .. } = self {
            *dirs = None;
        }
    }

    fn drop_bytes(&mut self) {
        if let Self::Walk { bytes, .. } = self {
            *bytes = None;
        }
    }
}

/// One frame's slots, before and after shrinking.
#[derive(Clone, Debug)]
struct Slots {
    spinner: char,
    root: Option<RootSlot>,
    phase: &'static str,
    /// Whether the phase word is padded to the longest one, so the facts start in one
    /// column whatever the phase.
    phase_padded: bool,
    /// Whether each count and size is right-aligned in a fixed column, so the line does
    /// not shift as the counts grow a digit.
    aligned: bool,
    facts: FactsSlot,
    elapsed: Option<String>,
    /// Optional cumulative walk rate, dropped before any established frame slot.
    rates: Option<String>,
}

impl Slots {
    fn full(root: &str, facts: &FrameFacts, elapsed: Duration, step: usize) -> Self {
        let facts_slot = match (facts.phase, facts.analysis) {
            // A run that walked nothing (a cache-only report, or a root it could not
            // list) would show zeros that read as an empty tree rather than as no walk.
            (Phase::Summarizing, _) if facts.directories == 0 => FactsSlot::None,
            // Indexing and Summarizing keep the walk's final counts: the walk is over,
            // and the phase word is what changes.
            (Phase::Scanning | Phase::Revalidating | Phase::Indexing | Phase::Summarizing, _) => {
                let size_style = byte_style(facts.bytes, false);
                FactsSlot::Walk {
                    files: human_count(facts.files),
                    dirs: Some(human_count(facts.directories)),
                    bytes: Some((
                        human_bytes(facts.bytes),
                        (size_style != AnsiStyle::new()).then_some(size_style),
                    )),
                }
            }
            (Phase::Analyzing, Some((done, total))) => FactsSlot::Analysis {
                percent: format!("{:>3}%", whole_percent(done, total)),
                done: human_count(done),
                total: human_count(total),
            },
            (Phase::Loading | Phase::Saving | Phase::Analyzing, _) => FactsSlot::None,
        };
        Self {
            spinner: SPINNER[step % SPINNER.len()],
            root: Some(RootSlot::new(root)),
            phase: facts.phase.word(),
            phase_padded: true,
            aligned: true,
            rates: walk_rates(facts, elapsed),
            facts: facts_slot,
            elapsed: Some(progress_duration(elapsed)),
        }
    }

    /// The form for a terminal too narrow for anything else.
    fn minimal(phase: Phase, step: usize) -> Self {
        Self {
            spinner: SPINNER[step % SPINNER.len()],
            root: None,
            phase: phase.word(),
            phase_padded: false,
            aligned: false,
            facts: FactsSlot::None,
            elapsed: None,
            rates: None,
        }
    }

    /// The frame's text in order, each piece with the style it takes when colored.
    fn segments(&self) -> Vec<(String, Option<AnsiStyle>)> {
        let mut segments = vec![(self.spinner.to_string(), Some(STYLE_SPINNER))];
        segments.push((" ".to_string(), None));
        if let Some(root) = &self.root {
            segments.push((root.text.clone(), Some(STYLE_ROOT)));
            segments.push(("  ".to_string(), None));
        }
        segments.push((self.phase.to_string(), Some(STYLE_PHASE)));
        if self.phase_padded {
            let padding = Phase::PADDED_WIDTH.saturating_sub(self.phase.len());
            segments.push((" ".repeat(padding), None));
        }
        let align = |text: &str, columns: usize| {
            if self.aligned { format!("{text:>columns$}") } else { text.to_string() }
        };
        match &self.facts {
            FactsSlot::None => {}
            FactsSlot::Walk { files, dirs, bytes } => {
                segments.push((format!("  {}", align(files, COUNT_COLUMNS)), None));
                segments.push((" files".to_string(), Some(STYLE_DIM)));
                if let Some(dirs) = dirs {
                    segments.push((" · ".to_string(), Some(STYLE_DIM)));
                    segments.push((align(dirs, COUNT_COLUMNS), None));
                    segments.push((" dirs".to_string(), Some(STYLE_DIM)));
                }
                if let Some(bytes) = bytes {
                    segments.push((" · ".to_string(), Some(STYLE_DIM)));
                    segments.push((align(&bytes.0, BYTES_COLUMNS), bytes.1));
                }
            }
            FactsSlot::Analysis { percent, done, total } => {
                // The total is fixed for the whole phase, so a count aligned to its width
                // holds the line still while it climbs.
                let done = align(done, total.chars().count());
                segments.push((format!("  {percent}  {done}"), None));
                segments.push((" / ".to_string(), Some(STYLE_DIM)));
                segments.push((total.clone(), None));
                segments.push((" files".to_string(), Some(STYLE_DIM)));
            }
        }
        if let Some(elapsed) = &self.elapsed {
            let facts_present = !matches!(&self.facts, FactsSlot::None);
            segments.push(if facts_present {
                (" · ".to_string(), Some(STYLE_DIM))
            } else {
                ("  ".to_string(), None)
            });
            segments.push((elapsed.clone(), Some(STYLE_DIM)));
            if let Some(rates) = &self.rates {
                segments.push((format!(" ({rates})"), Some(STYLE_DIM)));
            }
        }
        segments
    }

    /// The frame as bytes, with adjacent same-style pieces painted as one run.
    fn render(&self, color: bool) -> String {
        let mut out = String::new();
        let mut run: Option<(String, Option<AnsiStyle>)> = None;
        for (text, style) in self.segments() {
            match &mut run {
                Some((current, current_style)) if *current_style == style => {
                    current.push_str(&text);
                }
                _ => {
                    if let Some((current, current_style)) = run.take() {
                        out.push_str(&paint_segment(&current, current_style, color));
                    }
                    run = Some((text, style));
                }
            }
        }
        if let Some((current, current_style)) = run {
            out.push_str(&paint_segment(&current, current_style, color));
        }
        out
    }

    /// Columns the frame occupies, measured without color codes.
    fn columns(&self) -> usize {
        let plain = self.render(false);
        plain.chars().count() + self.root.as_ref().map_or(0, RootSlot::extra_columns)
    }
}

fn paint_segment(text: &str, style: Option<AnsiStyle>, color: bool) -> String {
    match style {
        Some(style) => paint(text, style, color),
        None => text.to_string(),
    }
}

/// Cumulative walk rates from the selected size metric and the frame's actual elapsed time.
/// The optional annotation starts only after five seconds, when retained walk facts exist.
fn walk_rates(facts: &FrameFacts, elapsed: Duration) -> Option<String> {
    if elapsed <= Duration::from_secs(5)
        || facts.directories == 0
        || !matches!(
            facts.phase,
            Phase::Scanning | Phase::Revalidating | Phase::Indexing | Phase::Summarizing
        )
    {
        return None;
    }
    throughput_rates(facts.files, facts.bytes, elapsed)
        .map(|(files, gib)| format!("{files} files/s, {gib} GiB/s"))
}

/// One frame, exactly as the Appearance section of the plan specifies it.
///
/// Slots in order: spinner, root, phase word padded to `Revalidating`, the phase's
/// facts, elapsed time, and optional cumulative walk rates. Counts are right-aligned
/// in columns wide enough for seven figures (`9,999,999`) and sizes in columns wide
/// enough for `1023 GiB`, so the line
/// holds still as they grow; an analyzed count is aligned to its total. The frame is
/// measured without its color codes, with each non-ASCII character of the root counted
/// as two columns, and always leaves the last column empty; when it is wider than that
/// it shrinks in order until it fits: optional rates go first, then phase padding,
/// then the root is elided in the middle with `…` down to 12 columns, the alignment
/// goes, the `dirs` count goes, the bytes go, and below 20 columns only the spinner
/// and the phase word are drawn. Once
/// elided, the root keeps its length while the later steps apply, so it holds still as
/// the counts widen. A frame never wraps.
///
/// The string excludes the leading `\r\x1b[2K`; the ticker adds it, so a frame is the
/// same bytes whether it is drawn or pinned by a test.
pub(crate) fn render_frame(
    root: &str,
    facts: &FrameFacts,
    elapsed: Duration,
    step: usize,
    width: usize,
    color: bool,
) -> String {
    let limit = width.saturating_sub(1);
    let mut slots = Slots::full(root, facts, elapsed, step);

    // Rates are optional; preserve the established facts and root before shrinking them.
    if slots.columns() > limit {
        slots.rates = None;
    }

    // The phase padding goes first: it only lines the facts up across phases, which
    // change a handful of times a run, while the counts change on every frame.
    if slots.columns() > limit {
        slots.phase_padded = false;
    }
    if slots.columns() > limit {
        let excess = slots.columns() - limit;
        let occupied = slots.root.as_ref().map_or(0, |root| root.columns);
        let target = occupied.saturating_sub(excess).max(MIN_ROOT_COLUMNS);
        if target < occupied {
            slots.root = Some(RootSlot::elided(root, target));
        }
    }
    if slots.columns() > limit {
        // The root keeps the length it was elided to. Fitting it to the room the
        // alignment frees would elide it again each time a count gained a digit, and
        // move the start of the line, which is what the alignment exists to prevent.
        slots.aligned = false;
    }
    if slots.columns() > limit {
        slots.facts.drop_dirs();
    }
    if slots.columns() > limit {
        slots.facts.drop_bytes();
    }
    if width < MIN_FULL_WIDTH || slots.columns() > limit {
        slots = Slots::minimal(facts.phase, step);
    }
    if slots.columns() > limit {
        // Narrower than the phase word itself. Nobody reads a terminal this narrow, but
        // the rule is that a frame never wraps, so it is cut rather than allowed to.
        return slots.render(false).chars().take(limit).collect();
    }
    slots.render(color)
}

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

    fn interactive() -> TerminalFacts {
        TerminalFacts {
            stderr_is_terminal: true,
            term: Some(OsString::from("xterm-256color")),
            term_may_be_unset: false,
            ci: None,
            vt_enabled: true,
        }
    }

    /// Every reading of the five facts, and whether that reading is interactive.
    fn every_terminal() -> Vec<(TerminalFacts, bool)> {
        let mut readings = Vec::new();
        for stderr_is_terminal in [false, true] {
            for term in [None, Some("dumb"), Some(""), Some("xterm-256color")] {
                for term_may_be_unset in [false, true] {
                    for ci in [None, Some(""), Some("true")] {
                        for vt_enabled in [false, true] {
                            let facts = TerminalFacts {
                                stderr_is_terminal,
                                term: term.map(OsString::from),
                                term_may_be_unset,
                                ci: ci.map(OsString::from),
                                vt_enabled,
                            };
                            let term_unset = term.is_none_or(str::is_empty);
                            let term_allows =
                                term == Some("xterm-256color") || (term_unset && term_may_be_unset);
                            let interactive = stderr_is_terminal
                                && term_allows
                                && ci != Some("true")
                                && vt_enabled;
                            readings.push((facts, interactive));
                        }
                    }
                }
            }
        }
        readings
    }

    #[test]
    fn interactive_needs_a_terminal_a_real_term_no_ci_and_escape_support() {
        assert!(interactive().is_interactive());
        let readings = every_terminal();
        assert_eq!(readings.len(), 96);
        // A real TERM with CI unset or empty, on either platform (4), or a TERM that is
        // unset or empty where the platform allows it, with CI unset or empty (4).
        assert_eq!(readings.iter().filter(|(_, interactive)| *interactive).count(), 8);
        let empty_term = TerminalFacts { term: Some(OsString::new()), ..interactive() };
        assert!(!empty_term.is_interactive(), "off Windows an empty TERM is an unset one");
        assert!(
            TerminalFacts { term_may_be_unset: true, ..empty_term }.is_interactive(),
            "on Windows an empty TERM is an unset one too"
        );
        for (facts, interactive) in readings {
            assert_eq!(facts.is_interactive(), interactive, "{facts:?}");
        }
        assert!(!TerminalFacts::default().is_interactive());
    }

    #[test]
    fn gating_covers_every_combination_and_never_draws_non_interactively() {
        let modes = [ProgressMode::Auto, ProgressMode::Always, ProgressMode::Never];
        for (facts, interactive) in every_terminal() {
            for mode in modes {
                for machine in [false, true] {
                    for walks in [false, true] {
                        let expected = interactive
                            && walks
                            && match mode {
                                ProgressMode::Never => false,
                                ProgressMode::Always => true,
                                ProgressMode::Auto => !machine,
                            };
                        assert_eq!(
                            should_draw(mode, &facts, machine, walks),
                            expected,
                            "{facts:?} {mode:?} machine={machine} walks={walks}"
                        );
                        if !interactive {
                            assert!(!should_draw(mode, &facts, machine, walks));
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn interactive_gating_draws_human_formats_under_auto_and_everything_under_always() {
        let facts = interactive();
        assert!(should_draw(ProgressMode::Auto, &facts, false, true));
        assert!(!should_draw(ProgressMode::Auto, &facts, true, true));
        assert!(should_draw(ProgressMode::Always, &facts, false, true));
        assert!(should_draw(ProgressMode::Always, &facts, true, true));
        assert!(!should_draw(ProgressMode::Never, &facts, false, true));
        assert!(!should_draw(ProgressMode::Never, &facts, true, true));
        for mode in [ProgressMode::Auto, ProgressMode::Always, ProgressMode::Never] {
            assert!(!should_draw(mode, &facts, false, false), "a non-walking command drew");
        }
    }

    #[cfg(not(windows))]
    #[test]
    fn the_root_is_abbreviated_under_home_by_path_component_only() {
        let home = Some(Path::new("/Users/levy"));
        assert_eq!(display_root(Path::new("/Users/levy/wrk/github"), home), "~/wrk/github");
        assert_eq!(display_root(Path::new("/Users/levy"), home), "~");
        assert_eq!(display_root(Path::new("/Users/levy2/wrk"), home), "/Users/levy2/wrk");
        assert_eq!(display_root(Path::new("/srv/data"), home), "/srv/data");
        assert_eq!(display_root(Path::new("."), home), ".");
        assert_eq!(display_root(Path::new("wrk/github"), home), "wrk/github");
        assert_eq!(display_root(Path::new("/Users/levy/wrk"), None), "/Users/levy/wrk");
        assert_eq!(
            display_root(Path::new("/Users/levy/wrk"), Some(Path::new(""))),
            "/Users/levy/wrk"
        );
    }

    #[cfg(windows)]
    #[test]
    fn the_root_is_abbreviated_under_home_by_path_component_only() {
        let home = Some(Path::new(r"C:\Users\levy"));
        assert_eq!(display_root(Path::new(r"C:\Users\levy\wrk\github"), home), r"~\wrk\github");
        assert_eq!(display_root(Path::new(r"C:\Users\levy"), home), "~");
        assert_eq!(display_root(Path::new(r"C:\Users\levy2\wrk"), home), r"C:\Users\levy2\wrk");
        assert_eq!(display_root(Path::new(r"D:\data"), home), r"D:\data");
        assert_eq!(display_root(Path::new("."), home), ".");
        assert_eq!(display_root(Path::new(r"C:\Users\levy\wrk"), None), r"C:\Users\levy\wrk");
    }

    const ROOT: &str = "~/wrk/github";
    /// 38 GiB and 256 MiB, which `human_bytes` shows without a decimal at that scale.
    const BYTES_38_GIB: u64 = 41_070_624_768;

    fn walk(phase: Phase) -> FrameFacts {
        FrameFacts {
            phase,
            directories: 12_041,
            files: 412_309,
            bytes: BYTES_38_GIB,
            analysis: None,
        }
    }

    fn analyzing(done: u64, total: u64) -> FrameFacts {
        FrameFacts {
            phase: Phase::Analyzing,
            analysis: Some((done, total)),
            ..walk(Phase::Analyzing)
        }
    }

    fn ms(millis: u64) -> Duration {
        Duration::from_millis(millis)
    }

    #[test]
    fn every_phase_uses_the_same_slots_in_the_same_order() {
        assert_eq!(
            render_frame(ROOT, &walk(Phase::Loading), ms(600), 2, 100, false),
            "⠹ ~/wrk/github  Loading       0.6 s"
        );
        assert_eq!(
            render_frame(ROOT, &walk(Phase::Scanning), ms(3_100), 4, 100, false),
            "⠼ ~/wrk/github  Scanning        412,309 files ·    12,041 dirs ·   38 GiB · 3.1 s"
        );
        assert_eq!(
            render_frame(ROOT, &walk(Phase::Revalidating), ms(1_400), 4, 100, false),
            "⠼ ~/wrk/github  Revalidating    412,309 files ·    12,041 dirs ·   38 GiB · 1.4 s"
        );
        assert_eq!(
            render_frame(ROOT, &analyzing(12_044, 50_110), ms(7_900), 7, 100, false),
            "⠧ ~/wrk/github  Analyzing      24%  12,044 / 50,110 files · 7.9 s"
        );
        assert_eq!(
            render_frame(ROOT, &walk(Phase::Saving), ms(8_100), 9, 100, false),
            "⠏ ~/wrk/github  Saving        8.1 s"
        );
        assert_eq!(
            render_frame(ROOT, &walk(Phase::Indexing), ms(3_800), 3, 100, false),
            "⠸ ~/wrk/github  Indexing        412,309 files ·    12,041 dirs ·   38 GiB · 3.8 s"
        );
        assert_eq!(
            render_frame(ROOT, &walk(Phase::Summarizing), ms(8_600), 5, 100, false),
            "⠴ ~/wrk/github  Summarizing     412,309 files ·    12,041 dirs ·   38 GiB · 8.6 s"
        );
        // A cache-only run walked nothing: no zeros that read as an empty tree.
        let unwalked =
            FrameFacts { directories: 0, files: 0, bytes: 0, ..walk(Phase::Summarizing) };
        assert_eq!(
            render_frame(ROOT, &unwalked, ms(1_200), 5, 100, false),
            "⠴ ~/wrk/github  Summarizing   1.2 s"
        );
        assert_eq!(
            render_frame(ROOT, &walk(Phase::Scanning), ms(3_100), 4, 100, false),
            render_frame(ROOT, &walk(Phase::Scanning), ms(3_100), 4, 100, false),
            "a frame is a pure function of its inputs"
        );
    }

    #[test]
    fn a_colored_frame_paints_each_slot_in_the_report_palette() {
        const CYAN: &str = "\u{1b}[36m";
        const BOLD: &str = "\u{1b}[1m";
        const DIM: &str = "\u{1b}[90m";
        const RESET: &str = "\u{1b}[0m";
        let root_style = format!("{STYLE_ROOT}");
        let root_reset = format!("{STYLE_ROOT:#}");

        assert_eq!(
            render_frame(ROOT, &walk(Phase::Loading), ms(600), 2, 100, true),
            format!(
                "{CYAN}⠹{RESET} {root_style}~/wrk/github{root_reset}  {BOLD}Loading{RESET}       \
                 {DIM}0.6 s{RESET}"
            )
        );
        assert_eq!(
            render_frame(ROOT, &walk(Phase::Scanning), ms(3_100), 4, 100, true),
            format!(
                "{CYAN}⠼{RESET} {root_style}~/wrk/github{root_reset}  {BOLD}Scanning{RESET}        412,309\
                 {DIM} files · {RESET}   12,041{DIM} dirs · {RESET}{BOLD}  38 GiB{RESET}{DIM} · 3.1 s{RESET}"
            )
        );
        assert_eq!(
            render_frame(ROOT, &walk(Phase::Revalidating), ms(1_400), 4, 100, true),
            format!(
                "{CYAN}⠼{RESET} {root_style}~/wrk/github{root_reset}  {BOLD}Revalidating{RESET}    412,309\
                 {DIM} files · {RESET}   12,041{DIM} dirs · {RESET}{BOLD}  38 GiB{RESET}{DIM} · 1.4 s{RESET}"
            )
        );
        assert_eq!(
            render_frame(ROOT, &analyzing(12_044, 50_110), ms(7_900), 7, 100, true),
            format!(
                "{CYAN}⠧{RESET} {root_style}~/wrk/github{root_reset}  {BOLD}Analyzing{RESET}      24%  \
                 12,044{DIM} / {RESET}50,110{DIM} files · 7.9 s{RESET}"
            )
        );
        assert_eq!(
            render_frame(ROOT, &walk(Phase::Saving), ms(8_100), 9, 100, true),
            format!(
                "{CYAN}⠏{RESET} {root_style}~/wrk/github{root_reset}  {BOLD}Saving{RESET}        \
                 {DIM}8.1 s{RESET}"
            )
        );
        let zero = render_frame(
            ROOT,
            &FrameFacts { bytes: 0, ..walk(Phase::Scanning) },
            ms(3_100),
            4,
            100,
            true,
        );
        assert!(zero.contains(&format!("{DIM} dirs ·      0 B · 3.1 s{RESET}")), "{zero:?}");
    }

    /// The full Scanning frame over this root is 113 columns; each width below takes
    /// exactly one more step of the shrink order.
    #[test]
    fn a_frame_shrinks_in_the_specified_order_until_it_fits() {
        let root = "/Volumes/archive/projects/example/repository";
        let facts = walk(Phase::Scanning);
        let frame = |width| render_frame(root, &facts, ms(3_100), 4, width, false);

        let full = "⠼ /Volumes/archive/projects/example/repository  Scanning        \
                    412,309 files ·    12,041 dirs ·   38 GiB · 3.1 s";
        assert_eq!(full.chars().count(), 113);
        assert_eq!(frame(114), full, "fits with the last column empty");
        // 1. The phase padding goes; the counts keep their columns.
        let unpadded = "⠼ /Volumes/archive/projects/example/repository  Scanning    \
                        412,309 files ·    12,041 dirs ·   38 GiB · 3.1 s";
        assert_eq!(frame(113), unpadded);
        assert_eq!(frame(110), unpadded);
        // 2. The root is elided in the middle, by exactly the excess...
        assert_eq!(
            frame(104),
            "⠼ /Volumes/archive/pr…example/repository  Scanning    \
             412,309 files ·    12,041 dirs ·   38 GiB · 3.1 s"
        );
        // ...and no further than 12 columns.
        assert_eq!(
            frame(78),
            "⠼ /Volum…itory  Scanning    412,309 files ·    12,041 dirs ·   38 GiB · 3.1 s"
        );
        // 3. The alignment goes. The root keeps its 12 columns rather than taking back
        // what that frees: refitted, it would be elided again whenever a count gained a
        // digit, and the start of the line would move.
        assert_eq!(
            frame(77),
            "⠼ /Volum…itory  Scanning  412,309 files · 12,041 dirs · 38 GiB · 3.1 s"
        );
        assert_eq!(
            frame(71),
            "⠼ /Volum…itory  Scanning  412,309 files · 12,041 dirs · 38 GiB · 3.1 s"
        );
        // 4. The dirs count goes.
        assert_eq!(frame(70), "⠼ /Volum…itory  Scanning  412,309 files · 38 GiB · 3.1 s");
        assert_eq!(frame(57), "⠼ /Volum…itory  Scanning  412,309 files · 38 GiB · 3.1 s");
        // 5. The bytes go.
        assert_eq!(frame(56), "⠼ /Volum…itory  Scanning  412,309 files · 3.1 s");
        assert_eq!(frame(48), "⠼ /Volum…itory  Scanning  412,309 files · 3.1 s");
        // 6. Nothing else can give way, so only the spinner and the phase word remain.
        assert_eq!(frame(47), "⠼ Scanning");
        assert_eq!(frame(20), "⠼ Scanning");
    }

    /// What an 80-column terminal keeps, with counts under ten million. `Scanning` keeps
    /// its counts aligned as the root and duration grow: phase padding goes first, then
    /// the root is elided to preserve the facts. `Revalidating` has no padding to give
    /// up, so over a root of 12 columns or more a warm run drops the alignment instead.
    #[test]
    fn an_eighty_column_terminal_keeps_what_fits() {
        assert_eq!(
            render_frame(ROOT, &walk(Phase::Scanning), ms(3_100), 4, 80, false),
            "⠼ ~/wrk/github  Scanning    412,309 files ·    12,041 dirs ·   38 GiB · 3.1 s"
        );
        assert_eq!(
            render_frame(ROOT, &walk(Phase::Revalidating), ms(1_400), 4, 80, false),
            "⠼ ~/wrk/github  Revalidating  412,309 files · 12,041 dirs · 38 GiB · 1.4 s"
        );
        // Both durations elide the root at this width.
        let root = "~/wrk/github12";
        assert_eq!(
            render_frame(root, &walk(Phase::Scanning), ms(59_900), 4, 80, false),
            "⠼ ~/wrk/…thub12  Scanning    412,309 files ·    12,041 dirs ·   38 GiB · 59.9 s"
        );
        assert_eq!(
            render_frame(root, &walk(Phase::Scanning), ms(60_000), 4, 80, false),
            "⠼ ~/wrk/…thub12  Scanning    412,309 files ·    12,041 dirs ·   38 GiB · 60.0 s"
        );
    }

    /// Counts and sizes hold their columns as they grow, so nothing after them moves:
    /// the frame is one width from the first file to seven figures, and from bytes to
    /// `999 GiB`. Grouped four-digit sizes widen rather than cutting a number.
    #[test]
    fn counts_and_sizes_are_right_aligned_in_fixed_columns() {
        let frame = |files, directories, bytes| {
            let facts = FrameFacts { directories, files, bytes, ..walk(Phase::Scanning) };
            render_frame(".", &facts, ms(3_100), 4, 200, false)
        };
        assert_eq!(
            frame(7, 1, 512),
            "⠼ .  Scanning              7 files ·         1 dirs ·    512 B · 3.1 s"
        );
        assert_eq!(
            frame(672_132, 111_897, 8_796_093_022_208),
            "⠼ .  Scanning        672,132 files ·   111,897 dirs ·  8.0 TiB · 3.1 s"
        );
        assert_eq!(
            frame(9_999_999, 9_999_999, 1_098_437_885_952),
            "⠼ .  Scanning      9,999,999 files · 9,999,999 dirs · 1,023 GiB · 3.1 s"
        );
        let widths: Vec<usize> = [(7, 1, 512), (672_132, 111_897, 41_070_624_768)]
            .into_iter()
            .map(|(files, dirs, bytes)| frame(files, dirs, bytes).chars().count())
            .collect();
        assert_eq!(widths, [70, 70]);
        assert_eq!(
            frame(12_345_678, 1, 1),
            "⠼ .  Scanning      12,345,678 files ·         1 dirs ·      1 B · 3.1 s"
        );
        // An analyzed count is aligned to its total, which is fixed for the phase.
        assert_eq!(
            render_frame(".", &analyzing(3_508, 50_110), ms(3_100), 4, 200, false),
            "⠼ .  Analyzing       7%   3,508 / 50,110 files · 3.1 s"
        );
    }

    #[test]
    fn below_twenty_columns_only_the_spinner_and_phase_word_are_drawn() {
        let facts = walk(Phase::Saving);
        assert_eq!(render_frame("~", &facts, ms(100), 0, 29, false), "⠋ ~  Saving        0.1 s");
        assert_eq!(render_frame("~", &facts, ms(100), 0, 26, false), "⠋ ~  Saving        0.1 s");
        assert_eq!(render_frame("~", &facts, ms(100), 0, 20, false), "⠋ ~  Saving  0.1 s");
        assert_eq!(render_frame("~", &facts, ms(100), 0, 19, false), "⠋ Saving");
        assert_eq!(
            render_frame("~", &facts, ms(100), 0, 19, true),
            "\u{1b}[36m⠋\u{1b}[0m \u{1b}[1mSaving\u{1b}[0m"
        );
        let long = walk(Phase::Revalidating);
        assert_eq!(render_frame("~", &long, ms(100), 0, 15, false), "⠋ Revalidating");
        assert_eq!(render_frame("~", &long, ms(100), 0, 10, false), "⠋ Revalid");
        assert_eq!(render_frame("~", &long, ms(100), 0, 0, false), "");
    }

    #[test]
    fn analysis_facts_give_way_only_as_a_whole() {
        let facts = analyzing(12_044, 50_110);
        let frame = |width| render_frame(ROOT, &facts, ms(7_900), 7, width, false);
        assert_eq!(frame(66), "⠧ ~/wrk/github  Analyzing      24%  12,044 / 50,110 files · 7.9 s");
        assert_eq!(frame(65), "⠧ ~/wrk/github  Analyzing   24%  12,044 / 50,110 files · 7.9 s");
        assert_eq!(frame(63), "⠧ ~/wrk/github  Analyzing   24%  12,044 / 50,110 files · 7.9 s");
        assert_eq!(frame(62), "⠧ Analyzing");
    }

    #[test]
    fn percentages_are_whole_and_never_complete_early() {
        let percent = |done, total| {
            let frame = render_frame(ROOT, &analyzing(done, total), ms(0), 0, 100, false);
            frame.split_once("Analyzing     ").expect("the facts follow the phase").1[..4]
                .to_string()
        };
        assert_eq!(percent(0, 50_110), "  0%");
        assert_eq!(percent(3_508, 50_110), "  7%");
        assert_eq!(percent(12_044, 50_110), " 24%");
        assert_eq!(percent(999, 1_000), " 99%");
        assert_eq!(percent(99_999, 100_000), " 99%");
        assert_eq!(percent(50_110, 50_110), "100%");
        assert_eq!(percent(0, 0), "100%", "the sidecar answered everything: nothing left to do");
        assert_eq!(whole_percent(0, 0), 100);
        assert_eq!(whole_percent(7, 5), 100);
        assert_eq!(whole_percent(u64::MAX - 1, u64::MAX), 99);
    }

    #[test]
    fn progress_elapsed_is_seconds_with_one_decimal_at_every_duration() {
        assert_eq!(progress_duration(Duration::ZERO), "0.0 s");
        assert_eq!(progress_duration(Duration::from_nanos(999)), "0.0 s");
        assert_eq!(progress_duration(ms(49)), "0.0 s");
        assert_eq!(progress_duration(ms(50)), "0.1 s");
        assert_eq!(progress_duration(ms(100)), "0.1 s");
        assert_eq!(progress_duration(ms(500)), "0.5 s");
        assert_eq!(progress_duration(ms(3_100)), "3.1 s");
        assert_eq!(progress_duration(ms(3_149)), "3.1 s");
        assert_eq!(progress_duration(ms(59_940)), "59.9 s");
        assert_eq!(progress_duration(ms(64_000)), "64.0 s");
        assert_eq!(progress_duration(ms(129_400)), "129.4 s");
        assert_eq!(progress_duration(ms(151_330)), "151.3 s");
        assert_eq!(progress_duration(ms(3_725_000)), "3725.0 s");
    }

    #[test]
    fn cumulative_walk_rates_start_strictly_after_five_seconds_and_use_binary_bytes() {
        let facts = FrameFacts {
            directories: 1,
            files: 12_345,
            bytes: 9 * (1 << 30),
            ..walk(Phase::Scanning)
        };
        assert_eq!(walk_rates(&facts, Duration::ZERO), None);
        assert_eq!(walk_rates(&facts, Duration::from_secs(5)), None);
        assert!(walk_rates(&facts, Duration::from_secs(5) + Duration::from_nanos(1)).is_some());
        let expected = Some("2,057 files/s, 1.500 GiB/s".to_string());
        for phase in [Phase::Scanning, Phase::Revalidating, Phase::Indexing, Phase::Summarizing] {
            assert_eq!(
                walk_rates(&FrameFacts { phase, ..facts }, Duration::from_secs(6)),
                expected
            );
        }
        for phase in [Phase::Loading, Phase::Saving, Phase::Analyzing] {
            assert_eq!(walk_rates(&FrameFacts { phase, ..facts }, Duration::from_secs(6)), None);
        }
        assert_eq!(
            walk_rates(&FrameFacts { directories: 0, ..facts }, Duration::from_secs(6)),
            None
        );
    }

    #[test]
    fn optional_rates_are_gray_and_drop_before_walk_facts_on_narrow_terminals() {
        let facts = FrameFacts {
            directories: 1,
            files: 12_345,
            bytes: 9 * (1 << 30),
            ..walk(Phase::Scanning)
        };
        let wide = render_frame(ROOT, &facts, Duration::from_secs(6), 0, 200, true);
        assert!(wide.contains("\x1b[90m · 6.0 s (2,057 files/s, 1.500 GiB/s)\x1b[0m"), "{wide:?}");
        let narrow = render_frame(ROOT, &facts, Duration::from_secs(6), 0, 80, false);
        assert!(!narrow.contains("files/s"), "{narrow}");
        assert!(narrow.contains("12,345 files"), "{narrow}");
        assert!(narrow.contains("9.0 GiB · 6.0 s"), "{narrow}");
        assert!(narrow.contains(ROOT), "{narrow}");
    }

    #[test]
    fn non_ascii_root_characters_count_as_two_columns() {
        let root = "~/Документы/проекты";
        let facts = walk(Phase::Saving);
        let frame = |width| render_frame(root, &facts, ms(8_100), 9, width, false);
        let full = "⠏ ~/Документы/проекты  Saving        8.1 s";
        // 42 characters, of which 16 in the root are wide: 58 columns.
        assert_eq!(full.chars().count(), 42);
        assert_eq!(path_columns(root), 35);
        assert_eq!(frame(59), full);
        assert_eq!(frame(58), "⠏ ~/Документы/проекты  Saving  8.1 s");
        // The elision keeps whole characters: a head budget of 6 columns holds `~/` and
        // two wide letters, a tail budget of 5 holds two wide letters, 11 columns in all.
        assert_eq!(frame(29), "⠏ ~/До…ты  Saving  8.1 s");
        assert_eq!(frame(28), "⠏ Saving");
        assert_eq!(frame(27), "⠏ Saving");
    }

    #[test]
    fn the_spinner_advances_one_cell_per_step_and_wraps() {
        let facts = walk(Phase::Saving);
        let spinner = |step| {
            render_frame(ROOT, &facts, ms(0), step, 100, false).chars().next().expect("a frame")
        };
        assert_eq!((0..10).map(spinner).collect::<String>(), "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏");
        assert_eq!(spinner(10), '⠋');
        assert_eq!(spinner(23), '⠸');
        assert_eq!(spinner(usize::MAX), '⠴');
    }

    #[test]
    fn an_analyzing_frame_without_analysis_facts_shows_none() {
        let facts = FrameFacts { analysis: None, ..analyzing(0, 0) };
        assert_eq!(
            render_frame(ROOT, &facts, ms(600), 2, 100, false),
            "⠹ ~/wrk/github  Analyzing     0.6 s"
        );
    }

    #[test]
    fn detect_reads_the_process_without_panicking() {
        let facts = TerminalFacts::detect();
        assert_eq!(facts.stderr_is_terminal, io::stderr().is_terminal());
        assert_eq!(facts.term, env::var_os("TERM"));
        assert_eq!(facts.ci, env::var_os("CI"));
        if !cfg!(windows) {
            assert!(facts.vt_enabled);
        }
    }
}