filter.rs 13 KB

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