filter.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. //! Filtering and sorting the list of files before displaying them.
  2. use std::cmp::Ordering;
  3. use std::iter::FromIterator;
  4. use std::os::unix::fs::MetadataExt;
  5. use crate::fs::DotFilter;
  6. use crate::fs::File;
  7. /// The **file filter** processes a list of files before displaying them to
  8. /// the user, by removing files they don’t want to see, and putting the list
  9. /// in the desired order.
  10. ///
  11. /// Usually a user does not want to see *every* file in the list. The most
  12. /// common case is to remove files starting with `.`, which are designated
  13. /// as ‘hidden’ files.
  14. ///
  15. /// The special files `.` and `..` files are not actually filtered out, but
  16. /// need to be inserted into the list, in a special case.
  17. ///
  18. /// The filter also governs sorting the list. After being filtered, pairs of
  19. /// files are compared and sorted based on the result, with the sort field
  20. /// performing the comparison.
  21. #[derive(PartialEq, Debug, Clone)]
  22. pub struct FileFilter {
  23. /// Whether directories should be listed first, and other types of file
  24. /// second. Some users prefer it like this.
  25. pub list_dirs_first: bool,
  26. /// The metadata field to sort by.
  27. pub sort_field: SortField,
  28. /// Whether to reverse the sorting order. This would sort the largest
  29. /// files first, or files starting with Z, or the most-recently-changed
  30. /// ones, depending on the sort field.
  31. pub reverse: bool,
  32. /// Whether to only show directories.
  33. pub only_dirs: bool,
  34. /// Which invisible “dot” files to include when listing a directory.
  35. ///
  36. /// Files starting with a single “.” are used to determine “system” or
  37. /// “configuration” files that should not be displayed in a regular
  38. /// directory listing, and the directory entries “.” and “..” are
  39. /// considered extra-special.
  40. ///
  41. /// This came about more or less by a complete historical accident,
  42. /// when the original `ls` tried to hide `.` and `..`:
  43. ///
  44. /// [Linux History: How Dot Files Became Hidden Files](https://linux-audit.com/linux-history-how-dot-files-became-hidden-files/)
  45. pub dot_filter: DotFilter,
  46. /// Glob patterns to ignore. Any file name that matches *any* of these
  47. /// patterns won’t be displayed in the list.
  48. pub ignore_patterns: IgnorePatterns,
  49. /// Whether to ignore Git-ignored patterns.
  50. pub git_ignore: GitIgnore,
  51. }
  52. impl FileFilter {
  53. /// Remove every file in the given vector that does *not* pass the
  54. /// filter predicate for files found inside a directory.
  55. pub fn filter_child_files(&self, files: &mut Vec<File<'_>>) {
  56. files.retain(|f| ! self.ignore_patterns.is_ignored(&f.name));
  57. if self.only_dirs {
  58. files.retain(File::is_directory);
  59. }
  60. }
  61. /// Remove every file in the given vector that does *not* pass the
  62. /// filter predicate for file names specified on the command-line.
  63. ///
  64. /// The rules are different for these types of files than the other
  65. /// type because the ignore rules can be used with globbing. For
  66. /// example, running `exa -I='*.tmp' .vimrc` shouldn’t filter out the
  67. /// dotfile, because it’s been directly specified. But running
  68. /// `exa -I='*.ogg' music/*` should filter out the ogg files obtained
  69. /// from the glob, even though the globbing is done by the shell!
  70. pub fn filter_argument_files(&self, files: &mut Vec<File<'_>>) {
  71. files.retain(|f| {
  72. ! self.ignore_patterns.is_ignored(&f.name)
  73. });
  74. }
  75. /// Sort the files in the given vector based on the sort field option.
  76. pub fn sort_files<'a, F>(&self, files: &mut Vec<F>)
  77. where F: AsRef<File<'a>>
  78. {
  79. files.sort_by(|a, b| {
  80. self.sort_field.compare_files(a.as_ref(), b.as_ref())
  81. });
  82. if self.reverse {
  83. files.reverse();
  84. }
  85. if self.list_dirs_first {
  86. // This relies on the fact that `sort_by` is *stable*: it will keep
  87. // adjacent elements next to each other.
  88. files.sort_by(|a, b| {
  89. b.as_ref().points_to_directory()
  90. .cmp(&a.as_ref().points_to_directory())
  91. });
  92. }
  93. }
  94. }
  95. /// User-supplied field to sort by.
  96. #[derive(PartialEq, Debug, Copy, Clone)]
  97. pub enum SortField {
  98. /// Don’t apply any sorting. This is usually used as an optimisation in
  99. /// scripts, where the order doesn’t matter.
  100. Unsorted,
  101. /// The file name. This is the default sorting.
  102. Name(SortCase),
  103. /// The file’s extension, with extensionless files being listed first.
  104. Extension(SortCase),
  105. /// The file’s size, in bytes.
  106. Size,
  107. /// The file’s inode, which usually corresponds to the order in which
  108. /// files were created on the filesystem, more or less.
  109. FileInode,
  110. /// The time the file was modified (the “mtime”).
  111. ///
  112. /// As this is stored as a Unix timestamp, rather than a local time
  113. /// instance, the time zone does not matter and will only be used to
  114. /// display the timestamps, not compare them.
  115. ModifiedDate,
  116. /// The time the file was accessed (the “atime”).
  117. ///
  118. /// Oddly enough, this field rarely holds the *actual* accessed time.
  119. /// Recording a read time means writing to the file each time it’s read
  120. /// slows the whole operation down, so many systems will only update the
  121. /// timestamp in certain circumstances. This has become common enough that
  122. /// it’s now expected behaviour!
  123. /// <http://unix.stackexchange.com/a/8842>
  124. AccessedDate,
  125. /// The time the file was changed (the “ctime”).
  126. ///
  127. /// This field is used to mark the time when a file’s metadata
  128. /// changed — its permissions, owners, or link count.
  129. ///
  130. /// In original Unix, this was, however, meant as creation time.
  131. /// <https://www.bell-labs.com/usr/dmr/www/cacm.html>
  132. ChangedDate,
  133. /// The time the file was created (the “btime” or “birthtime”).
  134. CreatedDate,
  135. /// The type of the file: directories, links, pipes, regular, files, etc.
  136. ///
  137. /// Files are ordered according to the `PartialOrd` implementation of
  138. /// `fs::fields::Type`, so changing that will change this.
  139. FileType,
  140. /// The “age” of the file, which is the time it was modified sorted
  141. /// backwards. The reverse of the `ModifiedDate` ordering!
  142. ///
  143. /// It turns out that listing the most-recently-modified files first is a
  144. /// common-enough use case that it deserves its own variant. This would be
  145. /// implemented by just using the modified date and setting the reverse
  146. /// flag, but this would make reversing *that* output not work, which is
  147. /// bad, even though that’s kind of nonsensical. So it’s its own variant
  148. /// that can be reversed like usual.
  149. ModifiedAge,
  150. /// The file's name, however if the name of the file begins with `.`
  151. /// ignore the leading `.` and then sort as Name
  152. NameMixHidden(SortCase),
  153. }
  154. /// Whether a field should be sorted case-sensitively or case-insensitively.
  155. /// This determines which of the `natord` functions to use.
  156. ///
  157. /// I kept on forgetting which one was sensitive and which one was
  158. /// insensitive. Would a case-sensitive sort put capital letters first because
  159. /// it takes the case of the letters into account, or intermingle them with
  160. /// lowercase letters because it takes the difference between the two cases
  161. /// into account? I gave up and just named these two variants after the
  162. /// effects they have.
  163. #[derive(PartialEq, Debug, Copy, Clone)]
  164. pub enum SortCase {
  165. /// Sort files case-sensitively with uppercase first, with ‘A’ coming
  166. /// before ‘a’.
  167. ABCabc,
  168. /// Sort files case-insensitively, with ‘A’ being equal to ‘a’.
  169. AaBbCc,
  170. }
  171. impl SortField {
  172. /// Compares two files to determine the order they should be listed in,
  173. /// depending on the search field.
  174. ///
  175. /// The `natord` crate is used here to provide a more *natural* sorting
  176. /// order than just sorting character-by-character. This splits filenames
  177. /// into groups between letters and numbers, and then sorts those blocks
  178. /// together, so `file10` will sort after `file9`, instead of before it
  179. /// because of the `1`.
  180. pub fn compare_files(self, a: &File<'_>, b: &File<'_>) -> Ordering {
  181. use self::SortCase::{ABCabc, AaBbCc};
  182. match self {
  183. Self::Unsorted => Ordering::Equal,
  184. Self::Name(ABCabc) => natord::compare(&a.name, &b.name),
  185. Self::Name(AaBbCc) => natord::compare_ignore_case(&a.name, &b.name),
  186. Self::Size => a.metadata.len().cmp(&b.metadata.len()),
  187. Self::FileInode => a.metadata.ino().cmp(&b.metadata.ino()),
  188. Self::ModifiedDate => a.modified_time().cmp(&b.modified_time()),
  189. Self::AccessedDate => a.accessed_time().cmp(&b.accessed_time()),
  190. Self::ChangedDate => a.changed_time().cmp(&b.changed_time()),
  191. Self::CreatedDate => a.created_time().cmp(&b.created_time()),
  192. Self::ModifiedAge => b.modified_time().cmp(&a.modified_time()), // flip b and a
  193. Self::FileType => match a.type_char().cmp(&b.type_char()) { // todo: this recomputes
  194. Ordering::Equal => natord::compare(&*a.name, &*b.name),
  195. order => order,
  196. },
  197. Self::Extension(ABCabc) => match a.ext.cmp(&b.ext) {
  198. Ordering::Equal => natord::compare(&*a.name, &*b.name),
  199. order => order,
  200. },
  201. Self::Extension(AaBbCc) => match a.ext.cmp(&b.ext) {
  202. Ordering::Equal => natord::compare_ignore_case(&*a.name, &*b.name),
  203. order => order,
  204. },
  205. Self::NameMixHidden(ABCabc) => natord::compare(
  206. Self::strip_dot(&a.name),
  207. Self::strip_dot(&b.name)
  208. ),
  209. Self::NameMixHidden(AaBbCc) => natord::compare_ignore_case(
  210. Self::strip_dot(&a.name),
  211. Self::strip_dot(&b.name)
  212. )
  213. }
  214. }
  215. fn strip_dot(n: &str) -> &str {
  216. match n.strip_prefix('.') {
  217. Some(s) => s,
  218. None => n,
  219. }
  220. }
  221. }
  222. /// The **ignore patterns** are a list of globs that are tested against
  223. /// each filename, and if any of them match, that file isn’t displayed.
  224. /// This lets a user hide, say, text files by ignoring `*.txt`.
  225. #[derive(PartialEq, Default, Debug, Clone)]
  226. pub struct IgnorePatterns {
  227. patterns: Vec<glob::Pattern>,
  228. }
  229. impl FromIterator<glob::Pattern> for IgnorePatterns {
  230. fn from_iter<I>(iter: I) -> Self
  231. where I: IntoIterator<Item = glob::Pattern>
  232. {
  233. let patterns = iter.into_iter().collect();
  234. Self { patterns }
  235. }
  236. }
  237. impl IgnorePatterns {
  238. /// Create a new list from the input glob strings, turning the inputs that
  239. /// are valid glob patterns into an `IgnorePatterns`. The inputs that
  240. /// don’t parse correctly are returned separately.
  241. pub fn parse_from_iter<'a, I: IntoIterator<Item = &'a str>>(iter: I) -> (Self, Vec<glob::PatternError>) {
  242. let iter = iter.into_iter();
  243. // Almost all glob patterns are valid, so it’s worth pre-allocating
  244. // the vector with enough space for all of them.
  245. let mut patterns = match iter.size_hint() {
  246. (_, Some(count)) => Vec::with_capacity(count),
  247. _ => Vec::new(),
  248. };
  249. // Similarly, assume there won’t be any errors.
  250. let mut errors = Vec::new();
  251. for input in iter {
  252. match glob::Pattern::new(input) {
  253. Ok(pat) => patterns.push(pat),
  254. Err(e) => errors.push(e),
  255. }
  256. }
  257. (Self { patterns }, errors)
  258. }
  259. /// Create a new empty set of patterns that matches nothing.
  260. pub fn empty() -> Self {
  261. Self { patterns: Vec::new() }
  262. }
  263. /// Test whether the given file should be hidden from the results.
  264. fn is_ignored(&self, file: &str) -> bool {
  265. self.patterns.iter().any(|p| p.matches(file))
  266. }
  267. }
  268. /// Whether to ignore or display files that Git would ignore.
  269. #[derive(PartialEq, Debug, Copy, Clone)]
  270. pub enum GitIgnore {
  271. /// Ignore files that Git would ignore.
  272. CheckAndIgnore,
  273. /// Display files, even if Git would ignore them.
  274. Off,
  275. }
  276. #[cfg(test)]
  277. mod test_ignores {
  278. use super::*;
  279. #[test]
  280. fn empty_matches_nothing() {
  281. let pats = IgnorePatterns::empty();
  282. assert_eq!(false, pats.is_ignored("nothing"));
  283. assert_eq!(false, pats.is_ignored("test.mp3"));
  284. }
  285. #[test]
  286. fn ignores_a_glob() {
  287. let (pats, fails) = IgnorePatterns::parse_from_iter(vec![ "*.mp3" ]);
  288. assert!(fails.is_empty());
  289. assert_eq!(false, pats.is_ignored("nothing"));
  290. assert_eq!(true, pats.is_ignored("test.mp3"));
  291. }
  292. #[test]
  293. fn ignores_an_exact_filename() {
  294. let (pats, fails) = IgnorePatterns::parse_from_iter(vec![ "nothing" ]);
  295. assert!(fails.is_empty());
  296. assert_eq!(true, pats.is_ignored("nothing"));
  297. assert_eq!(false, pats.is_ignored("test.mp3"));
  298. }
  299. #[test]
  300. fn ignores_both() {
  301. let (pats, fails) = IgnorePatterns::parse_from_iter(vec![ "nothing", "*.mp3" ]);
  302. assert!(fails.is_empty());
  303. assert_eq!(true, pats.is_ignored("nothing"));
  304. assert_eq!(true, pats.is_ignored("test.mp3"));
  305. }
  306. }