1 //! This module defines the [TotalSize] flag. To set it up from [ArgMatches], a [Config] and its
2 //! [Default] value, use the [configure_from](Configurable::configure_from) method.
3 
4 use super::Configurable;
5 
6 use crate::config_file::Config;
7 
8 use clap::ArgMatches;
9 
10 /// The flag showing whether to show the total size for directories.
11 #[derive(Clone, Debug, Copy, PartialEq, Eq, Default)]
12 pub struct TotalSize(pub bool);
13 
14 impl Configurable<Self> for TotalSize {
15     /// Get a potential `TotalSize` value from [ArgMatches].
16     ///
17     /// If the "total-size" argument is passed, this returns a `TotalSize` with value `true` in a
18     /// [Some]. Otherwise this returns [None].
from_arg_matches(matches: &ArgMatches) -> Option<Self>19     fn from_arg_matches(matches: &ArgMatches) -> Option<Self> {
20         if matches.is_present("total-size") {
21             Some(Self(true))
22         } else {
23             None
24         }
25     }
26 
27     /// Get a potential `TotalSize` value from a [Config].
28     ///
29     /// If the `Config::total-size` has value,
30     /// this returns it as the value of the `TotalSize`, in a [Some].
31     /// Otherwise this returns [None].
from_config(config: &Config) -> Option<Self>32     fn from_config(config: &Config) -> Option<Self> {
33         if let Some(total) = config.total_size {
34             Some(Self(total))
35         } else {
36             None
37         }
38     }
39 }
40 
41 #[cfg(test)]
42 mod test {
43     use super::TotalSize;
44 
45     use crate::app;
46     use crate::config_file::Config;
47     use crate::flags::Configurable;
48 
49     #[test]
test_from_arg_matches_none()50     fn test_from_arg_matches_none() {
51         let argv = vec!["lsd"];
52         let matches = app::build().get_matches_from_safe(argv).unwrap();
53         assert_eq!(None, TotalSize::from_arg_matches(&matches));
54     }
55 
56     #[test]
test_from_arg_matches_true()57     fn test_from_arg_matches_true() {
58         let argv = vec!["lsd", "--total-size"];
59         let matches = app::build().get_matches_from_safe(argv).unwrap();
60         assert_eq!(Some(TotalSize(true)), TotalSize::from_arg_matches(&matches));
61     }
62 
63     #[test]
test_from_config_none()64     fn test_from_config_none() {
65         assert_eq!(None, TotalSize::from_config(&Config::with_none()));
66     }
67 
68     #[test]
test_from_config_true()69     fn test_from_config_true() {
70         let mut c = Config::with_none();
71         c.total_size = Some(true);
72         assert_eq!(Some(TotalSize(true)), TotalSize::from_config(&c));
73     }
74 
75     #[test]
test_from_config_false()76     fn test_from_config_false() {
77         let mut c = Config::with_none();
78         c.total_size = Some(false);
79         assert_eq!(Some(TotalSize(false)), TotalSize::from_config(&c));
80     }
81 }
82