filter.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. //! Parsing the options for `FileFilter`.
  2. use fs::DotFilter;
  3. use fs::filter::{FileFilter, SortField, SortCase, IgnorePatterns, GitIgnore};
  4. use options::{flags, Misfire};
  5. use options::parser::MatchedFlags;
  6. impl FileFilter {
  7. /// Determines which of all the file filter options to use.
  8. pub fn deduce(matches: &MatchedFlags) -> Result<FileFilter, Misfire> {
  9. Ok(FileFilter {
  10. list_dirs_first: matches.has(&flags::DIRS_FIRST)?,
  11. reverse: matches.has(&flags::REVERSE)?,
  12. only_dirs: matches.has(&flags::ONLY_DIRS)?,
  13. sort_field: SortField::deduce(matches)?,
  14. dot_filter: DotFilter::deduce(matches)?,
  15. ignore_patterns: IgnorePatterns::deduce(matches)?,
  16. git_ignore: GitIgnore::deduce(matches)?,
  17. })
  18. }
  19. }
  20. impl SortField {
  21. /// Determines which sort field to use based on the `--sort` argument.
  22. /// This argument’s value can be one of several flags, listed above.
  23. /// Returns the default sort field if none is given, or `Err` if the
  24. /// value doesn’t correspond to a sort field we know about.
  25. fn deduce(matches: &MatchedFlags) -> Result<SortField, Misfire> {
  26. let word = match matches.get(&flags::SORT)? {
  27. Some(w) => w,
  28. None => return Ok(SortField::default()),
  29. };
  30. // Get String because we can’t match an OsStr
  31. let word = match word.to_str() {
  32. Some(ref w) => *w,
  33. None => return Err(Misfire::BadArgument(&flags::SORT, word.into()))
  34. };
  35. let field = match word {
  36. "name" | "filename" => SortField::Name(SortCase::AaBbCc),
  37. "Name" | "Filename" => SortField::Name(SortCase::ABCabc),
  38. ".name" | ".filename" => SortField::NameMixHidden(SortCase::AaBbCc),
  39. ".Name" | ".Filename" => SortField::NameMixHidden(SortCase::ABCabc),
  40. "size" | "filesize" => SortField::Size,
  41. "ext" | "extension" => SortField::Extension(SortCase::AaBbCc),
  42. "Ext" | "Extension" => SortField::Extension(SortCase::ABCabc),
  43. // “new” sorts oldest at the top and newest at the bottom; “old”
  44. // sorts newest at the top and oldest at the bottom. I think this
  45. // is the right way round to do this: “size” puts the smallest at
  46. // the top and the largest at the bottom, doesn’t it?
  47. "date" | "time" | "mod" | "modified" | "new" | "newest" => SortField::ModifiedDate,
  48. // Similarly, “age” means that files with the least age (the
  49. // newest files) get sorted at the top, and files with the most
  50. // age (the oldest) at the bottom.
  51. "age" | "old" | "oldest" => SortField::ModifiedAge,
  52. "ch" | "changed" => SortField::ChangedDate,
  53. "acc" | "accessed" => SortField::AccessedDate,
  54. "cr" | "created" => SortField::CreatedDate,
  55. "inode" => SortField::FileInode,
  56. "type" => SortField::FileType,
  57. "none" => SortField::Unsorted,
  58. _ => return Err(Misfire::BadArgument(&flags::SORT, word.into()))
  59. };
  60. Ok(field)
  61. }
  62. }
  63. // I’ve gone back and forth between whether to sort case-sensitively or
  64. // insensitively by default. The default string sort in most programming
  65. // languages takes each character’s ASCII value into account, sorting
  66. // “Documents” before “apps”, but there’s usually an option to ignore
  67. // characters’ case, putting “apps” before “Documents”.
  68. //
  69. // The argument for following case is that it’s easy to forget whether an item
  70. // begins with an uppercase or lowercase letter and end up having to scan both
  71. // the uppercase and lowercase sub-lists to find the item you want. If you
  72. // happen to pick the sublist it’s not in, it looks like it’s missing, which
  73. // is worse than if you just take longer to find it.
  74. // (https://ux.stackexchange.com/a/79266)
  75. //
  76. // The argument for ignoring case is that it makes exa sort files differently
  77. // from shells. A user would expect a directory’s files to be in the same
  78. // order if they used “exa ~/directory” or “exa ~/directory/*”, but exa sorts
  79. // them in the first case, and the shell in the second case, so they wouldn’t
  80. // be exactly the same if exa does something non-conventional.
  81. //
  82. // However, exa already sorts files differently: it uses natural sorting from
  83. // the natord crate, sorting the string “2” before “10” because the number’s
  84. // smaller, because that’s usually what the user expects to happen. Users will
  85. // name their files with numbers expecting them to be treated like numbers,
  86. // rather than lists of numeric characters.
  87. //
  88. // In the same way, users will name their files with letters expecting the
  89. // order of the letters to matter, rather than each letter’s character’s ASCII
  90. // value. So exa breaks from tradition and ignores case while sorting:
  91. // “apps” first, then “Documents”.
  92. //
  93. // You can get the old behaviour back by sorting with `--sort=Name`.
  94. impl Default for SortField {
  95. fn default() -> SortField {
  96. SortField::Name(SortCase::AaBbCc)
  97. }
  98. }
  99. impl DotFilter {
  100. /// Determines the dot filter based on how many `--all` options were
  101. /// given: one will show dotfiles, but two will show `.` and `..` too.
  102. ///
  103. /// It also checks for the `--tree` option in strict mode, because of a
  104. /// special case where `--tree --all --all` won’t work: listing the
  105. /// parent directory in tree mode would loop onto itself!
  106. pub fn deduce(matches: &MatchedFlags) -> Result<DotFilter, Misfire> {
  107. let count = matches.count(&flags::ALL);
  108. if count == 0 {
  109. Ok(DotFilter::JustFiles)
  110. }
  111. else if count == 1 {
  112. Ok(DotFilter::Dotfiles)
  113. }
  114. else if matches.count(&flags::TREE) > 0 {
  115. Err(Misfire::TreeAllAll)
  116. }
  117. else if count >= 3 && matches.is_strict() {
  118. Err(Misfire::Conflict(&flags::ALL, &flags::ALL))
  119. }
  120. else {
  121. Ok(DotFilter::DotfilesAndDots)
  122. }
  123. }
  124. }
  125. impl IgnorePatterns {
  126. /// Determines the set of glob patterns to use based on the
  127. /// `--ignore-patterns` argument’s value. This is a list of strings
  128. /// separated by pipe (`|`) characters, given in any order.
  129. pub fn deduce(matches: &MatchedFlags) -> Result<IgnorePatterns, Misfire> {
  130. // If there are no inputs, we return a set of patterns that doesn’t
  131. // match anything, rather than, say, `None`.
  132. let inputs = match matches.get(&flags::IGNORE_GLOB)? {
  133. None => return Ok(IgnorePatterns::empty()),
  134. Some(is) => is,
  135. };
  136. // Awkwardly, though, a glob pattern can be invalid, and we need to
  137. // deal with invalid patterns somehow.
  138. let (patterns, mut errors) = IgnorePatterns::parse_from_iter(inputs.to_string_lossy().split('|'));
  139. // It can actually return more than one glob error,
  140. // but we only use one. (TODO)
  141. match errors.pop() {
  142. Some(e) => Err(e.into()),
  143. None => Ok(patterns),
  144. }
  145. }
  146. }
  147. impl GitIgnore {
  148. pub fn deduce(matches: &MatchedFlags) -> Result<Self, Misfire> {
  149. Ok(if matches.has(&flags::GIT_IGNORE)? { GitIgnore::CheckAndIgnore }
  150. else { GitIgnore::Off })
  151. }
  152. }
  153. #[cfg(test)]
  154. mod test {
  155. use super::*;
  156. use std::ffi::OsString;
  157. use options::flags;
  158. use options::parser::Flag;
  159. macro_rules! test {
  160. ($name:ident: $type:ident <- $inputs:expr; $stricts:expr => $result:expr) => {
  161. #[test]
  162. fn $name() {
  163. use options::parser::Arg;
  164. use options::test::parse_for_test;
  165. use options::test::Strictnesses::*;
  166. static TEST_ARGS: &[&Arg] = &[ &flags::SORT, &flags::ALL, &flags::TREE, &flags::IGNORE_GLOB, &flags::GIT_IGNORE ];
  167. for result in parse_for_test($inputs.as_ref(), TEST_ARGS, $stricts, |mf| $type::deduce(mf)) {
  168. assert_eq!(result, $result);
  169. }
  170. }
  171. };
  172. }
  173. mod sort_fields {
  174. use super::*;
  175. // Default behaviour
  176. test!(empty: SortField <- []; Both => Ok(SortField::default()));
  177. // Sort field arguments
  178. test!(one_arg: SortField <- ["--sort=mod"]; Both => Ok(SortField::ModifiedDate));
  179. test!(one_long: SortField <- ["--sort=size"]; Both => Ok(SortField::Size));
  180. test!(one_short: SortField <- ["-saccessed"]; Both => Ok(SortField::AccessedDate));
  181. test!(lowercase: SortField <- ["--sort", "name"]; Both => Ok(SortField::Name(SortCase::AaBbCc)));
  182. test!(uppercase: SortField <- ["--sort", "Name"]; Both => Ok(SortField::Name(SortCase::ABCabc)));
  183. test!(old: SortField <- ["--sort", "new"]; Both => Ok(SortField::ModifiedDate));
  184. test!(oldest: SortField <- ["--sort=newest"]; Both => Ok(SortField::ModifiedDate));
  185. test!(new: SortField <- ["--sort", "old"]; Both => Ok(SortField::ModifiedAge));
  186. test!(newest: SortField <- ["--sort=oldest"]; Both => Ok(SortField::ModifiedAge));
  187. test!(age: SortField <- ["-sage"]; Both => Ok(SortField::ModifiedAge));
  188. test!(mix_hidden_lowercase: SortField <- ["--sort", ".name"]; Both => Ok(SortField::NameMixHidden(SortCase::AaBbCc)));
  189. test!(mix_hidden_uppercase: SortField <- ["--sort", ".Name"]; Both => Ok(SortField::NameMixHidden(SortCase::ABCabc)));
  190. // Errors
  191. test!(error: SortField <- ["--sort=colour"]; Both => Err(Misfire::BadArgument(&flags::SORT, OsString::from("colour"))));
  192. // Overriding
  193. test!(overridden: SortField <- ["--sort=cr", "--sort", "mod"]; Last => Ok(SortField::ModifiedDate));
  194. test!(overridden_2: SortField <- ["--sort", "none", "--sort=Extension"]; Last => Ok(SortField::Extension(SortCase::ABCabc)));
  195. test!(overridden_3: SortField <- ["--sort=cr", "--sort", "mod"]; Complain => Err(Misfire::Duplicate(Flag::Long("sort"), Flag::Long("sort"))));
  196. test!(overridden_4: SortField <- ["--sort", "none", "--sort=Extension"]; Complain => Err(Misfire::Duplicate(Flag::Long("sort"), Flag::Long("sort"))));
  197. }
  198. mod dot_filters {
  199. use super::*;
  200. // Default behaviour
  201. test!(empty: DotFilter <- []; Both => Ok(DotFilter::JustFiles));
  202. // --all
  203. test!(all: DotFilter <- ["--all"]; Both => Ok(DotFilter::Dotfiles));
  204. test!(all_all: DotFilter <- ["--all", "-a"]; Both => Ok(DotFilter::DotfilesAndDots));
  205. test!(all_all_2: DotFilter <- ["-aa"]; Both => Ok(DotFilter::DotfilesAndDots));
  206. test!(all_all_3: DotFilter <- ["-aaa"]; Last => Ok(DotFilter::DotfilesAndDots));
  207. test!(all_all_4: DotFilter <- ["-aaa"]; Complain => Err(Misfire::Conflict(&flags::ALL, &flags::ALL)));
  208. // --all and --tree
  209. test!(tree_a: DotFilter <- ["-Ta"]; Both => Ok(DotFilter::Dotfiles));
  210. test!(tree_aa: DotFilter <- ["-Taa"]; Both => Err(Misfire::TreeAllAll));
  211. test!(tree_aaa: DotFilter <- ["-Taaa"]; Both => Err(Misfire::TreeAllAll));
  212. }
  213. mod ignore_patterns {
  214. use super::*;
  215. use std::iter::FromIterator;
  216. use glob;
  217. fn pat(string: &'static str) -> glob::Pattern {
  218. glob::Pattern::new(string).unwrap()
  219. }
  220. // Various numbers of globs
  221. test!(none: IgnorePatterns <- []; Both => Ok(IgnorePatterns::empty()));
  222. test!(one: IgnorePatterns <- ["--ignore-glob", "*.ogg"]; Both => Ok(IgnorePatterns::from_iter(vec![ pat("*.ogg") ])));
  223. test!(two: IgnorePatterns <- ["--ignore-glob=*.ogg|*.MP3"]; Both => Ok(IgnorePatterns::from_iter(vec![ pat("*.ogg"), pat("*.MP3") ])));
  224. test!(loads: IgnorePatterns <- ["-I*|?|.|*"]; Both => Ok(IgnorePatterns::from_iter(vec![ pat("*"), pat("?"), pat("."), pat("*") ])));
  225. // Overriding
  226. test!(overridden: IgnorePatterns <- ["-I=*.ogg", "-I", "*.mp3"]; Last => Ok(IgnorePatterns::from_iter(vec![ pat("*.mp3") ])));
  227. test!(overridden_2: IgnorePatterns <- ["-I", "*.OGG", "-I*.MP3"]; Last => Ok(IgnorePatterns::from_iter(vec![ pat("*.MP3") ])));
  228. test!(overridden_3: IgnorePatterns <- ["-I=*.ogg", "-I", "*.mp3"]; Complain => Err(Misfire::Duplicate(Flag::Short(b'I'), Flag::Short(b'I'))));
  229. test!(overridden_4: IgnorePatterns <- ["-I", "*.OGG", "-I*.MP3"]; Complain => Err(Misfire::Duplicate(Flag::Short(b'I'), Flag::Short(b'I'))));
  230. }
  231. mod git_ignores {
  232. use super::*;
  233. test!(off: GitIgnore <- []; Both => Ok(GitIgnore::Off));
  234. test!(on: GitIgnore <- ["--git-ignore"]; Both => Ok(GitIgnore::CheckAndIgnore));
  235. }
  236. }