filter.rs 7.0 KB
Newer Older
1
use fs::DotFilter;
2
use fs::filter::{FileFilter, SortField, SortCase, IgnorePatterns};
B
Benjamin Sago 已提交
3 4

use options::{flags, Misfire};
5
use options::parser::MatchedFlags;
B
Benjamin Sago 已提交
6 7 8 9 10 11


impl FileFilter {

    /// Determines the set of file filter options to use, based on the user’s
    /// command-line arguments.
12
    pub fn deduce(matches: &MatchedFlags) -> Result<FileFilter, Misfire> {
B
Benjamin Sago 已提交
13
        Ok(FileFilter {
B
Benjamin Sago 已提交
14 15
            list_dirs_first: matches.has(&flags::DIRS_FIRST),
            reverse:         matches.has(&flags::REVERSE),
16
            sort_field:      SortField::deduce(matches)?,
B
Benjamin Sago 已提交
17
            dot_filter:      DotFilter::deduce(matches)?,
18
            ignore_patterns: IgnorePatterns::deduce(matches)?,
B
Benjamin Sago 已提交
19 20 21 22 23 24 25 26 27 28 29 30
        })
    }
}



impl Default for SortField {
    fn default() -> SortField {
        SortField::Name(SortCase::Sensitive)
    }
}

B
Benjamin Sago 已提交
31 32 33 34
const SORTS: &[&str] = &[ "name", "Name", "size", "extension",
                          "Extension", "modified", "accessed",
                          "created", "inode", "type", "none" ];

B
Benjamin Sago 已提交
35 36 37 38 39
impl SortField {

    /// Determine the sort field to use, based on the presence of a “sort”
    /// argument. This will return `Err` if the option is there, but does not
    /// correspond to a valid field.
40
    fn deduce(matches: &MatchedFlags) -> Result<SortField, Misfire> {
B
Benjamin Sago 已提交
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
        let word = match matches.get(&flags::SORT) {
            Some(w)  => w,
            None     => return Ok(SortField::default()),
        };

        if word == "name" || word == "filename" {
            Ok(SortField::Name(SortCase::Sensitive))
        }
        else if word == "Name" || word == "Filename" {
            Ok(SortField::Name(SortCase::Insensitive))
        }
        else if word == "size" || word == "filesize" {
            Ok(SortField::Size)
        }
        else if word == "ext" || word == "extension" {
            Ok(SortField::Extension(SortCase::Sensitive))
        }
        else if word == "Ext" || word == "Extension" {
            Ok(SortField::Extension(SortCase::Insensitive))
        }
        else if word == "mod" || word == "modified" {
            Ok(SortField::ModifiedDate)
        }
        else if word == "acc" || word == "accessed" {
            Ok(SortField::AccessedDate)
        }
        else if word == "cr" || word == "created" {
            Ok(SortField::CreatedDate)
        }
        else if word == "inode" {
            Ok(SortField::FileInode)
        }
        else if word == "type" {
            Ok(SortField::FileType)
        }
        else if word == "none" {
            Ok(SortField::Unsorted)
B
Benjamin Sago 已提交
78 79
        }
        else {
B
Benjamin Sago 已提交
80
            Err(Misfire::bad_argument(&flags::SORT, word, SORTS))
B
Benjamin Sago 已提交
81 82 83
        }
    }
}
B
Ben S 已提交
84 85


86
impl DotFilter {
87
    pub fn deduce(matches: &MatchedFlags) -> Result<DotFilter, Misfire> {
B
Benjamin Sago 已提交
88 89 90 91 92
        match matches.count(&flags::ALL) {
            0 => Ok(DotFilter::JustFiles),
            1 => Ok(DotFilter::Dotfiles),
            _ => if matches.has(&flags::TREE) { Err(Misfire::TreeAllAll) }
                                         else { Ok(DotFilter::DotfilesAndDots) }
93
        }
94 95 96 97
    }
}


B
Ben S 已提交
98
impl IgnorePatterns {
99

B
Ben S 已提交
100 101
    /// Determines the set of file filter options to use, based on the user’s
    /// command-line arguments.
102
    pub fn deduce(matches: &MatchedFlags) -> Result<IgnorePatterns, Misfire> {
B
Ben S 已提交
103

104 105 106 107 108 109
        let inputs = match matches.get(&flags::IGNORE_GLOB) {
            None => return Ok(IgnorePatterns::empty()),
            Some(is) => is,
        };

        let (patterns, mut errors) = IgnorePatterns::parse_from_iter(inputs.to_string_lossy().split('|'));
B
Benjamin Sago 已提交
110

111 112 113 114 115 116 117 118
        // It can actually return more than one glob error,
        // but we only use one.
        if let Some(error) = errors.pop() {
            return Err(error.into())
        }
        else {
            Ok(patterns)
        }
B
Ben S 已提交
119 120
    }
}
B
Benjamin Sago 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139



#[cfg(test)]
mod test {
    use super::*;
    use std::ffi::OsString;
    use options::flags;

    pub fn os(input: &'static str) -> OsString {
        let mut os = OsString::new();
        os.push(input);
        os
    }

    macro_rules! test {
        ($name:ident: $type:ident <- $inputs:expr => $result:expr) => {
            #[test]
            fn $name() {
140
                use options::parser::{Args, Arg};
B
Benjamin Sago 已提交
141 142
                use std::ffi::OsString;

B
Benjamin Sago 已提交
143
                static TEST_ARGS: &[&Arg] = &[ &flags::SORT, &flags::ALL, &flags::TREE, &flags::IGNORE_GLOB ];
B
Benjamin Sago 已提交
144 145

                let bits = $inputs.as_ref().into_iter().map(|&o| os(o)).collect::<Vec<OsString>>();
146
                let results = Args(TEST_ARGS).parse(bits.iter());
147
                assert_eq!($type::deduce(&results.unwrap().flags), $result);
B
Benjamin Sago 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
            }
        };
    }

    mod sort_fields {
        use super::*;

        // Default behaviour
        test!(empty:         SortField <- []                  => Ok(SortField::default()));

        // Sort field arguments
        test!(one_arg:       SortField <- ["--sort=cr"]       => Ok(SortField::CreatedDate));
        test!(one_long:      SortField <- ["--sort=size"]     => Ok(SortField::Size));
        test!(one_short:     SortField <- ["-saccessed"]      => Ok(SortField::AccessedDate));
        test!(lowercase:     SortField <- ["--sort", "name"]  => Ok(SortField::Name(SortCase::Sensitive)));
        test!(uppercase:     SortField <- ["--sort", "Name"]  => Ok(SortField::Name(SortCase::Insensitive)));

        // Errors
        test!(error:         SortField <- ["--sort=colour"]   => Err(Misfire::bad_argument(&flags::SORT, &os("colour"), super::SORTS)));

        // Overriding
        test!(overridden:    SortField <- ["--sort=cr",       "--sort", "mod"]     => Ok(SortField::ModifiedDate));
        test!(overridden_2:  SortField <- ["--sort", "none",  "--sort=Extension"]  => Ok(SortField::Extension(SortCase::Insensitive)));
    }
B
Benjamin Sago 已提交
172 173 174 175 176 177 178 179 180 181 182 183 184 185


    mod dot_filters {
        use super::*;

        // Default behaviour
        test!(empty:      DotFilter <- []               => Ok(DotFilter::JustFiles));

        // --all
        test!(all:        DotFilter <- ["--all"]        => Ok(DotFilter::Dotfiles));
        test!(all_all:    DotFilter <- ["--all", "-a"]  => Ok(DotFilter::DotfilesAndDots));
        test!(all_all_2:  DotFilter <- ["-aa"]          => Ok(DotFilter::DotfilesAndDots));

        // --all and --tree
B
Benjamin Sago 已提交
186 187
        test!(tree_a:     DotFilter <- ["-Ta"]          => Ok(DotFilter::Dotfiles));
        test!(tree_aa:    DotFilter <- ["-Taa"]         => Err(Misfire::TreeAllAll));
B
Benjamin Sago 已提交
188
    }
B
Benjamin Sago 已提交
189 190 191 192


    mod ignore_patternses {
        use super::*;
193
        use std::iter::FromIterator;
B
Benjamin Sago 已提交
194 195 196 197 198 199 200
        use glob;

        fn pat(string: &'static str) -> glob::Pattern {
            glob::Pattern::new(string).unwrap()
        }

        // Various numbers of globs
201 202 203 204
        test!(none:   IgnorePatterns <- []                             => Ok(IgnorePatterns::empty()));
        test!(one:    IgnorePatterns <- ["--ignore-glob", "*.ogg"]     => Ok(IgnorePatterns::from_iter(vec![ pat("*.ogg") ])));
        test!(two:    IgnorePatterns <- ["--ignore-glob=*.ogg|*.MP3"]  => Ok(IgnorePatterns::from_iter(vec![ pat("*.ogg"), pat("*.MP3") ])));
        test!(loads:  IgnorePatterns <- ["-I*|?|.|*"]                  => Ok(IgnorePatterns::from_iter(vec![ pat("*"), pat("?"), pat("."), pat("*") ])));
B
Benjamin Sago 已提交
205
    }
B
Benjamin Sago 已提交
206
}