eza 0.23.5

A modern replacement for ls
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
1146
1147
1148
1149
// SPDX-FileCopyrightText: 2024 Christina Sørensen
// SPDX-License-Identifier: EUPL-1.2
//
// SPDX-FileCopyrightText: 2023-2024 Christina Sørensen, eza contributors
// SPDX-FileCopyrightText: 2014 Benjamin Sago
// SPDX-License-Identifier: MIT
use clap::{ArgMatches, ValueEnum};

use crate::output::TerminalWidth::Automatic;

use crate::fs::feature::xattr;
use crate::options::parser::{CodeContent, ColorScaleModeArgs};
use crate::options::{NumberSource, OptionsError, Vars, vars};
use crate::output::TerminalWidth::Set;
use crate::output::color_scale::{ColorScaleMode, ColorScaleOptions};
use crate::output::file_name::Options as FileStyle;
use crate::output::grid_details::{self, RowThreshold};
use crate::output::table::{
    Columns, FlagsFormat, GroupFormat, Options as TableOptions, SizeFormat, TimeTypes, UserFormat,
};
use crate::output::time::TimeFormat;
use crate::output::{Mode, TerminalWidth, View, code, details, grid};

use super::parser::{ColorScaleArgs, TimeArgs};

impl View {
    pub fn deduce<V: Vars>(
        matches: &ArgMatches,
        vars: &V,
        strict: bool,
    ) -> Result<Self, OptionsError> {
        let width = TerminalWidth::deduce(matches, vars)?;
        let is_tty = width.actual_terminal_width().is_some();
        let mode = Mode::deduce(matches, vars, is_tty, strict)?;
        let deref_links = matches.get_flag("dereference");
        let follow_links = matches.get_flag("follow-symlinks");
        let total_size = matches.get_flag("total-size");
        let file_style = FileStyle::deduce(matches, vars, is_tty)?;
        Ok(Self {
            mode,
            width,
            file_style,
            deref_links,
            follow_links,
            total_size,
        })
    }
}

impl Mode {
    /// Determine which viewing mode to use based on the user’s options.
    ///
    /// As with the other options, arguments are scanned right-to-left and the
    /// first flag found is matched, so `exa --oneline --long` will pick a
    /// details view, and `exa --long --oneline` will pick the lines view.
    ///
    /// This is complicated a little by the fact that `--grid` and `--tree`
    /// can also combine with `--long`, so care has to be taken to use the
    pub fn deduce<V: Vars>(
        matches: &ArgMatches,
        vars: &V,
        is_tty: bool,
        strict: bool,
    ) -> Result<Self, OptionsError> {
        // `--code` is its own standalone tool: it summarises languages rather
        // than listing files, so it takes precedence over the layout flags.
        if let Some(content) = matches.get_one::<CodeContent>("code").copied() {
            return Ok(Self::Code(code::Options { content }));
        }

        let long = matches.get_flag("long");
        let oneline = matches.get_flag("oneline");
        let grid = matches.get_flag("grid");
        let tree = matches.get_flag("tree");

        if !long && strict {
            Self::strict_check_long_flags(matches)?;
        }

        if !(long || oneline || grid || tree) {
            if is_tty {
                let grid = grid::Options::deduce(matches);
                return Ok(Self::Grid(grid));
            }
            return Ok(Self::Lines);
        }

        if long {
            let details = details::Options::deduce_long(matches, vars, strict)?;

            if grid {
                let row_threshold = RowThreshold::deduce(vars)?;
                let grid_details = grid_details::Options {
                    details,
                    row_threshold,
                };
                return Ok(Self::GridDetails(grid_details));
            }

            // the --tree case is handled by the DirAction parser later
            return Ok(Self::Details(details));
        }

        if tree {
            let details = details::Options::deduce_tree(matches, vars);
            return Ok(Self::Details(details));
        }

        if oneline {
            return Ok(Self::Lines);
        }

        let grid = grid::Options::deduce(matches);
        Ok(Self::Grid(grid))
    }

    // TODO: handle that with Clap
    fn strict_check_long_flags(matches: &ArgMatches) -> Result<(), OptionsError> {
        // If --long hasn’t been passed, then check if we need to warn the
        // user about flags that won’t have any effect.
        for flag in &[
            "binary",
            "bytes",
            "inode",
            "links",
            "header",
            "blocksize",
            "time",
            "group",
            "numeric",
            "mounts",
            "loc",
        ] {
            if matches.contains_id(flag) {
                return Err(OptionsError::Useless(flag, false, "long"));
            }
        }

        if matches.get_flag("git") && !matches.get_flag("no-git") {
            return Err(OptionsError::Useless("git", false, "long"));
        } else if matches.contains_id("level")
            && !matches.get_flag("recurse")
            && !matches.get_flag("tree")
        {
            return Err(OptionsError::Useless2("level", "recurse", "tree"));
        }

        Ok(())
    }
}

impl grid::Options {
    fn deduce(matches: &ArgMatches) -> Self {
        grid::Options {
            across: matches.get_flag("across"),
        }
    }
}

impl details::Options {
    fn deduce_tree<V: Vars>(matches: &ArgMatches, vars: &V) -> Self {
        details::Options {
            table: None,
            header: false,
            xattr: xattr::ENABLED && matches.get_flag("extended"),
            secattr: xattr::ENABLED && matches.get_flag("security-context"),
            mounts: matches.get_flag("mounts"),
            color_scale: ColorScaleOptions::deduce(matches, vars),
            follow_links: matches.get_flag("follow-symlinks"),
        }
    }

    fn deduce_long<V: Vars>(
        matches: &ArgMatches,
        vars: &V,
        strict: bool,
    ) -> Result<Self, OptionsError> {
        if strict {
            if matches.get_flag("across") && !matches.get_flag("grid") {
                return Err(OptionsError::Useless("across", true, "long"));
            } else if matches.get_flag("oneline") {
                return Err(OptionsError::Useless("one-line", true, "long"));
            }
        }

        Ok(details::Options {
            table: Some(TableOptions::deduce(matches, vars)?),
            header: matches.get_flag("header"),
            xattr: xattr::ENABLED && matches.get_flag("extended"),
            secattr: xattr::ENABLED && matches.get_flag("security-context"),
            mounts: matches.get_flag("mounts"),
            color_scale: ColorScaleOptions::deduce(matches, vars),
            follow_links: matches.get_flag("follow-symlinks"),
        })
    }
}

impl TerminalWidth {
    fn deduce<V: Vars>(matches: &ArgMatches, vars: &V) -> Result<Self, OptionsError> {
        if let Some(&width) = matches.get_one("width") {
            if width >= 1 {
                Ok(Set(width))
            } else {
                Ok(Automatic)
            }
        } else if let Some(columns) = vars.get(vars::COLUMNS).and_then(|s| s.into_string().ok()) {
            match columns.parse() {
                Ok(width) => Ok(Set(width)),
                Err(e) => {
                    let source = NumberSource::Env(vars::COLUMNS);
                    Err(OptionsError::FailedParse(columns, source, e))
                }
            }
        } else {
            Ok(Automatic)
        }
    }
}

impl RowThreshold {
    fn deduce<V: Vars>(vars: &V) -> Result<Self, OptionsError> {
        if let Some(columns) = vars
            .get_with_fallback(vars::EZA_GRID_ROWS, vars::EXA_GRID_ROWS)
            .and_then(|s| s.into_string().ok())
        {
            match columns.parse() {
                Ok(rows) => Ok(Self::MinimumRows(rows)),
                Err(e) => {
                    let source = NumberSource::Env(
                        vars.source(vars::EZA_GRID_ROWS, vars::EXA_GRID_ROWS)
                            .unwrap(),
                    );
                    Err(OptionsError::FailedParse(columns, source, e))
                }
            }
        } else {
            Ok(Self::AlwaysGrid)
        }
    }
}

impl TableOptions {
    fn deduce<V: Vars>(matches: &ArgMatches, vars: &V) -> Result<Self, OptionsError> {
        let time_format = TimeFormat::deduce(matches, vars);
        let flags_format = FlagsFormat::deduce(vars);
        let size_format = SizeFormat::deduce(matches);
        let user_format = UserFormat::deduce(matches);
        let group_format = GroupFormat::deduce(matches);
        let columns = Columns::deduce(matches, vars)?;
        Ok(Self {
            size_format,
            time_format,
            user_format,
            group_format,
            flags_format,
            columns,
        })
    }
}

impl Columns {
    fn deduce<V: Vars>(matches: &ArgMatches, vars: &V) -> Result<Self, OptionsError> {
        let time_types = TimeTypes::deduce(matches)?;

        let no_git_env = vars
            .get_with_fallback(vars::EXA_OVERRIDE_GIT, vars::EZA_OVERRIDE_GIT)
            .is_some();

        let git = matches.get_flag("git") && !matches.get_flag("no-git") && !no_git_env;
        let subdir_git_repos =
            matches.get_flag("git-repos") && !matches.get_flag("no-git") && !no_git_env;
        let subdir_git_repos_no_stat = !subdir_git_repos
            && matches.get_flag("git-repos-no-status")
            && !matches.get_flag("no-git")
            && !no_git_env;

        let file_flags = matches.get_flag("file-flags");
        let blocksize = matches.get_flag("blocksize");
        let group = matches.get_flag("group");
        let inode = matches.get_flag("inode");
        let links = matches.get_flag("links");
        let octal = matches.get_flag("octal-permissions");
        let security_context = xattr::ENABLED && matches.get_flag("security-context");

        let permissions = !matches.get_flag("no-permissions");
        let filesize = !matches.get_flag("no-filesize");
        let user = !matches.get_flag("no-user");

        let loc = matches.get_one::<CodeContent>("loc").copied();

        Ok(Self {
            time_types,
            inode,
            links,
            blocksize,
            group,
            git,
            subdir_git_repos,
            subdir_git_repos_no_stat,
            octal,
            security_context,
            file_flags,
            permissions,
            filesize,
            user,
            loc,
        })
    }
}

impl SizeFormat {
    /// Determine which file size to use in the file size column based on
    /// the user’s options.
    ///
    /// The default mode is to use the decimal prefixes, as they are the
    /// most commonly-understood, and don’t involve trying to parse large
    /// strings of digits in your head. Changing the format to anything else
    /// involves the `--binary` or `--bytes` flags, and these conflict with
    /// each other.
    fn deduce(matches: &ArgMatches) -> Self {
        use SizeFormat::*;
        if matches.get_flag("binary") {
            BinaryBytes
        } else if matches.get_flag("bytes") {
            JustBytes
        } else {
            DecimalBytes
        }
    }
}

const FORMAT_STYLE_FIELDS: [&str; 6] = [
    "default",
    "iso",
    "long-iso",
    "full-iso",
    "relative",
    "+<CUSTOM_FORMAT>",
];

impl TimeFormat {
    /// Determine how time should be formatted in timestamp columns.
    pub fn try_from_str(value: &str) -> Result<Self, String> {
        use nu_ansi_term::Color::*;

        let error_header = format!(
            "invalid value '{}' for '{}'\n  [possible values: {}]\n\n",
            Yellow.paint(value),
            White.paint("--time-style <STYLE>"),
            FORMAT_STYLE_FIELDS
                .map(|s| Green.paint(s).to_string())
                .join(", ")
        );
        let error_footer = format!(
            "\n\nFor more information, try '{}'.\n",
            White.paint("--help"),
        );

        let fmt = match value {
            "default" => return Ok(TimeFormat::DefaultFormat),
            "iso" => return Ok(TimeFormat::ISOFormat),
            "long-iso" => return Ok(TimeFormat::LongISO),
            "full-iso" => return Ok(TimeFormat::FullISO),
            "relative" => return Ok(TimeFormat::Relative),
            s if !s.starts_with('+') => {
                let error_middle = format!(
                    "{}{}",
                    "Please start the format with a plus sign (+) to indicate a custom format.\n",
                    "For example: \"+%Y-%m-%d %H:%M:%S\"",
                );
                return Err(format!("{error_header}{error_middle}{error_footer}"));
            }
            s => s,
        };

        let mut lines = fmt.strip_prefix('+').unwrap().lines();

        // line 1 is None when there is nothing after `+`
        // line 1 is empty when `+` is followed immediately by `\n`
        let non_recent = match lines.next() {
            None | Some("") => {
                let error_middle = format!(
                    "{}{}",
                    "Custom timestamp format is empty, ",
                    "please supply a chrono format string after the +."
                );
                return Err(format!("{error_header}{error_middle}{error_footer}"));
            }
            Some(non_recent) => non_recent,
        };

        // line 2 is None when there is not a single `\n`, or nothing after the first `\n`
        // line 2 is empty when there are at least 2 `\n`, and nothing between the 1st and 2nd `\n`
        let recent = match lines.next() {
            Some("") => {
                let error_middle = format!(
                    "{}{}",
                    "Custom timestamp format for recent files is empty, ",
                    "please supply a chrono format string at the second line."
                );
                return Err(format!("{error_header}{error_middle}{error_footer}"));
            }
            recent => recent.map(std::string::ToString::to_string),
        };

        Ok(TimeFormat::Custom {
            non_recent: String::from(non_recent),
            recent,
        })
    }
}

impl TimeFormat {
    /// Determine how time should be formatted in timestamp columns.
    fn deduce<V: Vars>(matches: &ArgMatches, vars: &V) -> Self {
        if let Some(arg) = matches.get_one::<TimeFormat>("time-style") {
            arg.clone()
        } else {
            match vars.get(vars::TIME_STYLE) {
                Some(t) if !t.is_empty() => TimeFormat::try_from_str(t.to_str().unwrap_or(""))
                    .unwrap_or(TimeFormat::DefaultFormat),
                _ => Self::DefaultFormat,
            }
        }
    }
}

impl UserFormat {
    fn deduce(matches: &ArgMatches) -> Self {
        if matches.get_flag("numeric") {
            Self::Numeric
        } else {
            Self::Name
        }
    }
}

impl GroupFormat {
    fn deduce(matches: &ArgMatches) -> Self {
        if matches.get_flag("smart-group") {
            Self::Smart
        } else {
            Self::Regular
        }
    }
}

impl TimeTypes {
    /// Determine which of a file’s time fields should be displayed for it
    /// based on the user’s options.
    ///
    /// There are two separate ways to pick which fields to show: with a
    /// flag (such as `--modified`) or with a parameter (such as
    /// `--time=modified`). An error is signaled if both ways are used.
    ///
    /// It’s valid to show more than one column by passing in more than one
    /// option, but passing *no* options means that the user just wants to
    /// see the default set.
    fn deduce(matches: &ArgMatches) -> Result<Self, OptionsError> {
        let possible_word = matches.get_one::<TimeArgs>("time");
        let modified = matches.get_flag("modified");
        let changed = matches.get_flag("changed");
        let accessed = matches.get_flag("accessed");
        let created = matches.get_flag("created");

        let no_time = matches.get_flag("no-time");

        #[rustfmt::skip]
        let time_types = if no_time {
            Self {
                modified: false,
                changed: false,
                accessed: false,
                created: false,
            }
        } else if let Some(word) = possible_word {
            if modified {
                return Err(OptionsError::Useless("modified", true, "time"));
            } else if changed {
                return Err(OptionsError::Useless("changed", true, "time"));
            } else if accessed {
                return Err(OptionsError::Useless("accessed", true, "time"));
            } else if created {
                return Err(OptionsError::Useless("created", true, "time"));
            } else if *word == TimeArgs::Modified  {
                Self { modified: true,  changed: false, accessed: false, created: false }
            } else if *word == TimeArgs::Changed {
                Self { modified: false, changed: true,  accessed: false, created: false }
            } else if *word == TimeArgs::Accessed {
                Self { modified: false, changed: false, accessed: true,  created: false }
            } else if *word == TimeArgs::Created {
                Self { modified: false, changed: false, accessed: false, created: true  }
            } else {
                return Err(OptionsError::BadArgument("time", word.to_possible_value().unwrap().get_name().into()));
            }
        } else if modified || changed || accessed || created {
            Self {
                modified,
                changed,
                accessed,
                created,
            }
        } else {
            Self::default()
        };

        Ok(time_types)
    }
}

impl ColorScaleOptions {
    pub fn deduce<V: Vars>(matches: &ArgMatches, vars: &V) -> Self {
        let min_luminance =
            match vars.get_with_fallback(vars::EZA_MIN_LUMINANCE, vars::EXA_MIN_LUMINANCE) {
                Some(var) => match var.to_string_lossy().parse() {
                    Ok(luminance) if (-100..=100).contains(&luminance) => luminance,
                    _ => 40,
                },
                None => 40,
            };

        let mode = match matches.get_one("color-scale-mode").unwrap() {
            ColorScaleModeArgs::Fixed => ColorScaleMode::Fixed,
            ColorScaleModeArgs::Gradient => ColorScaleMode::Gradient,
        };

        let mut options = ColorScaleOptions {
            mode,
            min_luminance,
            size: false,
            age: false,
        };

        let Some(words) = matches.get_many("color-scale") else {
            return options;
        };

        for word in words {
            match word {
                ColorScaleArgs::All => {
                    options.size = true;
                    options.age = true;
                }
                ColorScaleArgs::Age => {
                    options.age = true;
                }
                ColorScaleArgs::Size => {
                    options.size = true;
                }
            }
        }

        options
    }
}

#[cfg(test)]
mod tests {
    use crate::options::parser::test::mock_cli;
    use crate::options::vars::test::MockVars;
    use std::ffi::OsString;
    use std::num::ParseIntError;

    use super::*;

    #[test]
    fn deduce_time_types_no_time() {
        assert_eq!(
            TimeTypes::deduce(&mock_cli(vec!["--no-time"])),
            Ok(TimeTypes {
                modified: false,
                ..TimeTypes::default()
            })
        );
    }

    #[test]
    fn deduce_time_types_default() {
        assert_eq!(
            TimeTypes::deduce(&mock_cli(vec![""])),
            Ok(TimeTypes::default())
        );
    }

    #[test]
    fn deduce_time_types_modified_word() {
        assert_eq!(
            TimeTypes::deduce(&mock_cli(vec!["--time", "modified"])),
            Ok(TimeTypes {
                modified: true,
                ..TimeTypes::default()
            })
        );
    }

    #[test]
    fn deduce_time_types_accessed_word() {
        assert_eq!(
            TimeTypes::deduce(&mock_cli(vec!["--time", "accessed"])),
            Ok(TimeTypes {
                accessed: true,
                modified: false,
                ..TimeTypes::default()
            })
        );
    }

    #[test]
    fn deduce_time_types_changed_word() {
        assert_eq!(
            TimeTypes::deduce(&mock_cli(vec!["--time", "changed"])),
            Ok(TimeTypes {
                modified: false,
                changed: true,
                ..TimeTypes::default()
            })
        );
    }

    #[test]
    fn deduce_time_types_created_word() {
        assert_eq!(
            TimeTypes::deduce(&mock_cli(vec!["--time", "created"])),
            Ok(TimeTypes {
                modified: false,
                created: true,
                ..TimeTypes::default()
            })
        );
    }

    #[test]
    fn deduce_time_types_modified() {
        assert_eq!(
            TimeTypes::deduce(&mock_cli(vec!["--modified"])),
            Ok(TimeTypes {
                modified: true,
                ..TimeTypes::default()
            })
        );
    }

    #[test]
    fn deduce_time_types_accessed() {
        assert_eq!(
            TimeTypes::deduce(&mock_cli(vec!["--accessed"])),
            Ok(TimeTypes {
                accessed: true,
                modified: false,
                ..TimeTypes::default()
            })
        );
    }

    #[test]
    fn deduce_time_types_changed() {
        assert_eq!(
            TimeTypes::deduce(&mock_cli(vec!["--changed"])),
            Ok(TimeTypes {
                modified: false,
                changed: true,
                ..TimeTypes::default()
            })
        );
    }

    #[test]
    fn deduce_time_types_created() {
        assert_eq!(
            TimeTypes::deduce(&mock_cli(vec!["--created"])),
            Ok(TimeTypes {
                modified: false,
                created: true,
                ..TimeTypes::default()
            })
        );
    }

    #[test]
    fn deduce_group_format_on() {
        assert_eq!(
            GroupFormat::deduce(&mock_cli(vec!["--smart-group"])),
            GroupFormat::Smart
        );
    }

    #[test]
    fn deduce_group_format_off() {
        assert_eq!(
            GroupFormat::deduce(&mock_cli(vec![""])),
            GroupFormat::Regular
        );
    }

    #[test]
    fn deduce_user_format_on() {
        assert_eq!(
            UserFormat::deduce(&mock_cli(vec!["--numeric"])),
            UserFormat::Numeric
        );
    }

    #[test]
    fn deduce_user_format_off() {
        assert_eq!(UserFormat::deduce(&mock_cli(vec![""])), UserFormat::Name);
    }

    #[test]
    fn deduce_size_format_off() {
        assert_eq!(
            SizeFormat::deduce(&mock_cli(vec![""])),
            SizeFormat::DecimalBytes
        );
    }

    #[test]
    fn deduce_user_format_bytes() {
        assert_eq!(
            SizeFormat::deduce(&mock_cli(vec!["--bytes"])),
            SizeFormat::JustBytes
        );
    }

    #[test]
    fn deduce_user_format_binary() {
        assert_eq!(
            SizeFormat::deduce(&mock_cli(vec!["--binary"])),
            SizeFormat::BinaryBytes
        );
    }

    #[test]
    fn deduce_grid_options() {
        assert_eq!(
            grid::Options::deduce(&mock_cli(vec!["--across"])),
            grid::Options { across: true }
        );
    }

    #[test]
    fn deduce_time_style_iso_env() {
        let mut vars = MockVars::default();
        vars.set(vars::TIME_STYLE, &OsString::from("iso"));
        assert_eq!(
            TimeFormat::deduce(&mock_cli(vec![""]), &vars),
            TimeFormat::ISOFormat
        );
    }

    #[test]
    fn deduce_time_style_iso_arg() {
        let vars = MockVars::default();
        assert_eq!(
            TimeFormat::deduce(&mock_cli(vec!["--time-style", "iso"]), &vars),
            TimeFormat::ISOFormat
        );
    }

    #[test]
    fn deduce_time_style_long_iso_env() {
        let mut vars = MockVars::default();
        vars.set(vars::TIME_STYLE, &OsString::from("long-iso"));
        assert_eq!(
            TimeFormat::deduce(&mock_cli(vec![""]), &vars),
            TimeFormat::LongISO
        );
    }

    #[test]
    fn deduce_time_style_long_iso_arg() {
        let vars = MockVars::default();
        assert_eq!(
            TimeFormat::deduce(&mock_cli(vec!["--time-style", "long-iso"]), &vars),
            TimeFormat::LongISO
        );
    }

    #[test]
    fn deduce_time_style_full_iso_env() {
        let mut vars = MockVars::default();
        vars.set(vars::TIME_STYLE, &OsString::from("full-iso"));
        assert_eq!(
            TimeFormat::deduce(&mock_cli(vec![""]), &vars),
            TimeFormat::FullISO
        );
    }

    #[test]
    fn deduce_time_style_full_iso_arg() {
        let vars = MockVars::default();
        assert_eq!(
            TimeFormat::deduce(&mock_cli(vec!["--time-style", "full-iso"]), &vars),
            TimeFormat::FullISO
        );
    }

    #[test]
    fn deduce_time_style_relative_env() {
        let mut vars = MockVars::default();
        vars.set(vars::TIME_STYLE, &OsString::from("relative"));
        assert_eq!(
            TimeFormat::deduce(&mock_cli(vec![""]), &vars),
            TimeFormat::Relative
        );
    }

    #[test]
    fn deduce_time_style_relative_arg() {
        let vars = MockVars::default();
        assert_eq!(
            TimeFormat::deduce(&mock_cli(vec!["--time-style", "relative"]), &vars),
            TimeFormat::Relative
        );
    }

    #[test]
    fn deduce_time_style_custom_env() {
        let mut vars = MockVars::default();
        vars.set(vars::TIME_STYLE, &OsString::from("+%Y-%b-%d"));
        assert_eq!(
            TimeFormat::deduce(&mock_cli(vec![""]), &vars),
            TimeFormat::Custom {
                non_recent: String::from("%Y-%b-%d"),
                recent: None
            }
        );
    }

    #[test]
    fn deduce_time_style_custom_arg() {
        assert_eq!(
            TimeFormat::deduce(
                &mock_cli(vec!["--time-style", "+%Y-%b-%d"]),
                &MockVars::default()
            ),
            TimeFormat::Custom {
                non_recent: String::from("%Y-%b-%d"),
                recent: None
            }
        );
    }

    #[test]
    fn deduce_time_style_non_recent_and_recent() {
        assert_eq!(
            TimeFormat::deduce(
                &mock_cli(vec!["--time-style", "+%Y-%m-%d %H\n--%m-%d %H:%M"]),
                &MockVars::default()
            ),
            TimeFormat::Custom {
                non_recent: String::from("%Y-%m-%d %H"),
                recent: Some(String::from("--%m-%d %H:%M"))
            }
        );
    }

    #[test]
    fn deduce_color_scale_size_age_luminance_40_gradient() {
        assert_eq!(
            ColorScaleOptions::deduce(
                &mock_cli(vec!["--color-scale", "size,age"]),
                &MockVars::default()
            ),
            ColorScaleOptions {
                mode: ColorScaleMode::Gradient,
                min_luminance: 40,
                size: true,
                age: true,
            }
        );
    }

    #[test]
    fn deduce_color_scale_size_luminance_60_gradient() {
        let mut vars = MockVars::default();
        vars.set(vars::EZA_MIN_LUMINANCE, &OsString::from("60"));
        assert_eq!(
            ColorScaleOptions::deduce(&mock_cli(vec!["--color-scale", "size"]), &vars),
            ColorScaleOptions {
                mode: ColorScaleMode::Gradient,
                min_luminance: 60,
                size: true,
                age: false,
            }
        );
    }

    #[test]
    fn deduce_color_scale_age_luminance_60_fixed() {
        let mut vars = MockVars::default();
        vars.set(vars::EZA_MIN_LUMINANCE, &OsString::from("60"));
        assert_eq!(
            ColorScaleOptions::deduce(
                &mock_cli(vec!["--color-scale", "age", "--color-scale-mode", "fixed"]),
                &vars
            ),
            ColorScaleOptions {
                mode: ColorScaleMode::Fixed,
                min_luminance: 60,
                size: false,
                age: true,
            }
        );
    }

    #[test]
    fn deduce_color_scale_size_age_luminance_99_fixed() {
        let mut vars = MockVars::default();
        vars.set(vars::EZA_MIN_LUMINANCE, &OsString::from("99"));
        assert_eq!(
            ColorScaleOptions::deduce(
                &mock_cli(vec![
                    "--color-scale",
                    "size,age",
                    "--color-scale-mode",
                    "fixed"
                ]),
                &vars
            ),
            ColorScaleOptions {
                mode: ColorScaleMode::Fixed,
                min_luminance: 99,
                size: true,
                age: true,
            }
        );
    }

    #[test]
    fn deduce_mode_grid() {
        assert_eq!(
            Mode::deduce(
                &mock_cli(vec!["--grid"]),
                &MockVars::default(),
                false,
                false
            ),
            Ok(Mode::Grid(grid::Options { across: false }))
        );
    }

    #[test]
    fn deduce_mode_grid_across() {
        assert_eq!(
            Mode::deduce(
                &mock_cli(vec!["--grid", "--across"]),
                &MockVars::default(),
                false,
                false
            ),
            Ok(Mode::Grid(grid::Options { across: true }))
        );
    }
    #[test]
    fn deduce_details_options_tree() {
        let cli = mock_cli(vec!["--tree"]);
        assert_eq!(
            details::Options::deduce_tree(&cli, &MockVars::default()),
            details::Options {
                table: None,
                header: false,
                xattr: false,
                secattr: false,
                mounts: false,
                color_scale: ColorScaleOptions::deduce(&cli, &MockVars::default()),
                follow_links: false,
            }
        );
    }

    #[test]
    fn deduce_details_options_tree_mounts() {
        let cli = mock_cli(vec!["--tree", "--mounts"]);
        assert_eq!(
            details::Options::deduce_tree(&cli, &MockVars::default()),
            details::Options {
                table: None,
                header: false,
                xattr: false,
                secattr: false,
                mounts: true,
                color_scale: ColorScaleOptions::deduce(&cli, &MockVars::default()),
                follow_links: false,
            }
        );
    }

    #[test]
    fn deduce_details_options_tree_xattr() {
        let cli = mock_cli(vec!["--tree", "--extended"]);
        assert_eq!(
            details::Options::deduce_tree(&cli, &MockVars::default()),
            details::Options {
                table: None,
                header: false,
                xattr: xattr::ENABLED,
                secattr: false,
                mounts: false,
                color_scale: ColorScaleOptions::deduce(&cli, &MockVars::default()),
                follow_links: false,
            }
        );
    }

    #[test]
    fn deduce_details_options_tree_secattr() {
        let cli = mock_cli(vec!["--tree", "--context"]);
        assert_eq!(
            details::Options::deduce_tree(&cli, &MockVars::default()),
            details::Options {
                table: None,
                header: false,
                xattr: false,
                secattr: xattr::ENABLED,
                mounts: false,
                color_scale: ColorScaleOptions::deduce(&cli, &MockVars::default()),
                follow_links: false,
            }
        );
    }

    #[test]
    fn deduce_details_long_strict_across() {
        assert_eq!(
            details::Options::deduce_long(
                &mock_cli(vec!["--long", "--across"]),
                &MockVars::default(),
                true
            ),
            Err(OptionsError::Useless("across", true, "long"))
        );
    }

    #[test]
    fn deduce_details_long_strict_one_line() {
        assert_eq!(
            details::Options::deduce_long(
                &mock_cli(vec!["--long", "--oneline"]),
                &MockVars::default(),
                true
            ),
            Err(OptionsError::Useless("one-line", true, "long"))
        );
    }

    #[test]
    fn deduce_terminal_width_automatic() {
        assert_eq!(
            TerminalWidth::deduce(&mock_cli(vec![""]), &MockVars::default()),
            Ok(Automatic)
        );
    }

    #[test]
    fn deduce_terminal_width_set_arg() {
        assert_eq!(
            TerminalWidth::deduce(&mock_cli(vec!["--width", "80"]), &MockVars::default()),
            Ok(Set(80))
        );
    }

    #[test]
    fn deduce_terminal_width_set_env() {
        let mut vars = MockVars::default();
        vars.set(vars::COLUMNS, &OsString::from("80"));
        assert_eq!(
            TerminalWidth::deduce(&mock_cli(vec![""]), &vars),
            Ok(Set(80))
        );
    }

    #[test]
    fn deduce_terminal_width_set_env_bad() {
        let mut vars = MockVars::default();
        vars.set(vars::COLUMNS, &OsString::from("bad"));

        let e: Result<i64, ParseIntError> =
            vars.get(vars::COLUMNS).unwrap().to_string_lossy().parse();

        assert_eq!(
            TerminalWidth::deduce(&mock_cli(vec![""]), &vars),
            Err(OptionsError::FailedParse(
                String::from("bad"),
                NumberSource::Env(vars::COLUMNS),
                e.unwrap_err()
            ))
        );
    }

    #[test]
    fn deduce_mode_code_default_is_both() {
        assert_eq!(
            Mode::deduce(
                &mock_cli(vec!["--code"]),
                &MockVars::default(),
                false,
                false
            ),
            Ok(Mode::Code(code::Options {
                content: CodeContent::Both
            }))
        );
    }

    #[test]
    fn deduce_mode_code_lines() {
        assert_eq!(
            Mode::deduce(
                &mock_cli(vec!["--code=lines"]),
                &MockVars::default(),
                false,
                false
            ),
            Ok(Mode::Code(code::Options {
                content: CodeContent::Lines
            }))
        );
    }

    #[test]
    fn deduce_columns_loc_percent() {
        assert_eq!(
            Columns::deduce(&mock_cli(vec!["--loc=percent"]), &MockVars::default())
                .unwrap()
                .loc,
            Some(CodeContent::Percent)
        );
    }

    #[test]
    fn deduce_columns_loc_bare_is_both() {
        assert_eq!(
            Columns::deduce(&mock_cli(vec!["--loc"]), &MockVars::default())
                .unwrap()
                .loc,
            Some(CodeContent::Both)
        );
    }

    #[test]
    fn deduce_columns_loc_absent() {
        assert_eq!(
            Columns::deduce(&mock_cli(vec![""]), &MockVars::default())
                .unwrap()
                .loc,
            None
        );
    }
}