Skip to main content

ex_cli/
finder.rs

1use crate::cli::file::FileKind;
2use crate::config::Config;
3use crate::error::{MyError, MyResult};
4use crate::fs::entry::Entry;
5use crate::fs::file::File;
6use crate::fs::flags::FileFlags;
7use crate::fs::system::System;
8use crate::fs::total::Total;
9use crate::git::cache::GitCache;
10use crate::regex;
11use crate::zip::wrapper::ZipKind;
12use chrono::{DateTime, TimeZone, Utc};
13use glob::{MatchOptions, Pattern};
14use multimap::MultiMap;
15use path_clean::PathClean;
16use std::cell::RefCell;
17use std::collections::{BTreeMap, BTreeSet};
18use std::ffi::OsStr;
19#[cfg(windows)]
20use std::path::MAIN_SEPARATOR_STR;
21use std::path::{Component, Path, PathBuf};
22use std::rc::Rc;
23use std::time::SystemTime;
24
25#[allow(dead_code)]
26pub struct Finder<'a, S: System> {
27    config: &'a Config,
28    system: &'a S,
29    current: PathBuf,
30    options: MatchOptions,
31    start_time: Option<DateTime<Utc>>,
32    git_cache: Option<Rc<GitCache>>,
33    git_bash: bool,
34}
35
36// noinspection RsLift
37impl<'a, S: System> Finder<'a, S> {
38    pub fn new<Tz: TimeZone>(
39        config: &'a Config,
40        system: &'a S,
41        zone: &Tz,
42        current: PathBuf,
43        git_bash: bool,
44    ) -> Self {
45        let options = Self::match_options(config);
46        let start_time = config.start_time(zone);
47        let git_cache = config.filter_git().map(GitCache::new).map(Rc::new);
48        Self {
49            config,
50            system,
51            current,
52            options,
53            start_time,
54            git_cache,
55            git_bash,
56        }
57    }
58
59    #[cfg(windows)]
60    fn match_options(config: &Config) -> MatchOptions {
61        let mut options = MatchOptions::new();
62        options.case_sensitive = config.case_sensitive().unwrap_or(false);
63        options
64    }
65
66    #[cfg(not(windows))]
67    fn match_options(config: &Config) -> MatchOptions {
68        let mut options = MatchOptions::new();
69        options.case_sensitive = config.case_sensitive().unwrap_or(true);
70        options
71    }
72
73    pub fn find_files(&self) -> MyResult<Vec<File>> {
74        let files = RefCell::new(BTreeSet::new());
75        let tasks = self.group_tasks()?;
76        for ((abs_root, rel_root), patterns) in tasks.iter_all() {
77            self.find_entries(&files, abs_root, rel_root, patterns)?;
78            self.find_parents(&files, abs_root, rel_root)?;
79        }
80        let files = files.into_inner().into_iter().collect();
81        Ok(files)
82    }
83
84    pub fn create_total(&self, files: &Vec<File>) -> Total {
85        Total::from_files(self.start_time, self.config, files)
86    }
87
88    fn group_tasks(&self) -> MyResult<MultiMap<(PathBuf, PathBuf), Pattern>> {
89        let mut tasks = MultiMap::new();
90        for pattern in self.config.patterns() {
91            if let Some((abs_root, rel_root, filename)) = self.parse_pattern(pattern) {
92                let pattern = Pattern::new(&filename).map_err(|e| (e, &filename))?;
93                tasks.insert((abs_root, rel_root), pattern);
94            }
95        }
96        Ok(tasks)
97    }
98
99    #[cfg(windows)]
100    fn parse_pattern(&self, pattern: &str) -> Option<(PathBuf, PathBuf, String)> {
101        if self.git_bash {
102            let drive_regex = regex!(r#"^/([A-Za-z])/(.+)$"#);
103            if let Some(captures) = drive_regex.captures(pattern) {
104                let drive = captures.get(1).unwrap().as_str().to_uppercase();
105                let path = captures.get(2).unwrap().as_str().replace("/", MAIN_SEPARATOR_STR);
106                let pattern = format!("{}:{}{}", drive, MAIN_SEPARATOR_STR, path);
107                self.split_pattern(&pattern)
108            } else {
109                let pattern = pattern.replace("/", MAIN_SEPARATOR_STR);
110                self.split_pattern(&pattern)
111            }
112        } else {
113            self.split_pattern(pattern)
114        }
115    }
116
117    #[cfg(not(windows))]
118    fn parse_pattern(&self, pattern: &str) -> Option<(PathBuf, PathBuf, String)> {
119        self.split_pattern(pattern)
120    }
121
122    fn split_pattern(&self, pattern: &str) -> Option<(PathBuf, PathBuf, String)> {
123        let rel_root = PathBuf::from(pattern);
124        let abs_root = self.current.join(&rel_root).clean();
125        if requires_wildcard(&rel_root, self.config.zip_expand()) {
126            let name = String::from("*");
127            return Some((abs_root, rel_root, name));
128        }
129        if let Some(mut name) = find_name(&abs_root) {
130            if let Some(abs_root) = find_parent(&abs_root) {
131                if let Some(rel_root) = find_parent(&rel_root) {
132                    if name.starts_with(".") {
133                        name = format!("*{name}");
134                    }
135                    return Some((abs_root, rel_root, name));
136                }
137            }
138        }
139        None
140    }
141
142    fn find_entries(
143        &self,
144        files: &RefCell<BTreeSet<File>>,
145        abs_root: &Path,
146        rel_root: &Path,
147        patterns: &Vec<Pattern>,
148    ) -> MyResult<()> {
149        let rel_depth = count_components(rel_root);
150        let git_cache = self.git_cache.as_ref().map(Rc::clone);
151        self.system.walk_entries(abs_root, rel_root, git_cache, &|entry| {
152            match entry {
153                Ok(entry) => {
154                    self.insert_file(
155                        files,
156                        entry,
157                        abs_root,
158                        rel_root,
159                        rel_depth,
160                        patterns,
161                    );
162                }
163                Err(error) => if !self.config.quiet() {
164                    error.print_error();
165                }
166            }
167        })
168    }
169
170    fn insert_file(
171        &self,
172        files: &RefCell<BTreeSet<File>>,
173        entry: &dyn Entry,
174        abs_root: &Path,
175        rel_root: &Path,
176        rel_depth: usize,
177        patterns: &Vec<Pattern>,
178    ) {
179        match self.create_file(entry, abs_root, rel_root, rel_depth, patterns) {
180            Ok(file) => if let Some(file) = file {
181                if !self.config.sort_name() || self.config.show_indent() || (file.file_type != FileKind::Dir) {
182                    files.borrow_mut().insert(file);
183                }
184            }
185            Err(error) => if !self.config.quiet() {
186                error.print_error();
187            }
188        }
189    }
190
191    fn create_file(
192        &self,
193        entry: &dyn Entry,
194        abs_root: &Path,
195        rel_root: &Path,
196        rel_depth: usize,
197        patterns: &Vec<Pattern>,
198    ) -> MyResult<Option<File>> {
199        if let Some(name) = entry.file_name().to_str() {
200            if !patterns.iter().any(|p| p.matches_with(name, self.options)) {
201                return Ok(None);
202            }
203            if let Some(depth) = self.config.min_depth() {
204                if entry.file_depth() < depth {
205                    return Ok(None);
206                }
207            }
208            let file_type = FileKind::from_entry(self.system, entry);
209            if let Some(filter_types) = self.config.filter_types() {
210                if !filter_types.contains(&file_type) {
211                    return Ok(None);
212                }
213            }
214            if let FileKind::Link(_) = file_type {
215                let link_path = self.system.read_link(entry)?;
216                if let Some(link_path) = link_path {
217                    return if let Some(link_entry) = self.follow_link(entry.file_path(), &link_path) {
218                        entry.copy_metadata(link_entry.as_ref().as_ref());
219                        let link_path = link_entry.file_path().to_path_buf();
220                        let link_type = FileKind::from_entry(self.system, link_entry.as_ref().as_ref());
221                        self.create_inner(
222                            entry,
223                            abs_root,
224                            rel_root,
225                            rel_depth,
226                            file_type,
227                            Some((link_path, link_type)),
228                        )
229                    } else {
230                        entry.reset_metadata();
231                        self.create_inner(
232                            entry,
233                            abs_root,
234                            rel_root,
235                            rel_depth,
236                            FileKind::Link(false),
237                            Some((link_path, FileKind::Link(false))),
238                        )
239                    }
240                }
241            }
242            return self.create_inner(
243                entry,
244                abs_root,
245                rel_root,
246                rel_depth,
247                file_type,
248                None,
249            );
250        }
251        Ok(None)
252    }
253
254    fn follow_link(&self, file_path: &Path, link_path: &Path) -> Option<Rc<Box<dyn Entry>>> {
255        if let Some(file_parent) = file_path.parent() {
256            let link_path = file_parent.join(link_path);
257            return self.system.get_entry(&link_path).ok();
258        }
259        None
260    }
261
262    fn create_inner(
263        &self,
264        entry: &dyn Entry,
265        abs_root: &Path,
266        rel_root: &Path,
267        rel_depth: usize,
268        file_type: FileKind,
269        link_data: Option<(PathBuf, FileKind)>,
270    ) -> MyResult<Option<File>> {
271        let file_time = DateTime::<Utc>::from(entry.file_time());
272        if let Some(start_time) = self.start_time {
273            if file_time < start_time {
274                return Ok(None);
275            }
276        }
277        let abs_path = entry.file_path();
278        let git_flags = if let Some(git_cache) = &self.git_cache {
279            if entry.file_flags() != FileFlags::File {
280                return Ok(None);
281            }
282            let flags = git_cache.test_allowed(abs_path)?;
283            if flags.is_none() {
284                return Ok(None);
285            }
286            flags
287        } else {
288            None
289        };
290        if let Some(rel_path) = create_relative(abs_root, rel_root, abs_path) {
291            if let Some(abs_dir) = select_parent(abs_path, file_type) {
292                if let Some(rel_dir) = select_parent_from_owned(rel_path, file_type) {
293                    let file_depth = entry.file_depth() + rel_depth;
294                    let inner_depth = entry.inner_depth();
295                    let file_name = select_name(abs_path, file_type).unwrap_or_default();
296                    let file_ext = find_extension(abs_path, file_type);
297                    let file_size = select_size(entry, &link_data, file_type);
298                    let mut file = File::new(abs_dir, rel_dir, file_depth, inner_depth, file_name, file_ext, file_type)
299                        .with_mode(entry.file_mode())
300                        .with_size(file_size)
301                        .with_time(file_time)
302                        .with_git(git_flags);
303                    #[cfg(unix)]
304                    if self.config.show_owner() {
305                        let user = self.system.find_user(entry.owner_uid());
306                        let group = self.system.find_group(entry.owner_gid());
307                        file = file.with_owner(user, group);
308                    }
309                    if self.config.show_sig() {
310                        if let FileKind::File(_) | FileKind::Link(_) = file_type {
311                            let file_sig = self.system.read_sig(entry);
312                            file = file.with_sig(file_sig);
313                        }
314                    }
315                    #[cfg(windows)]
316                    if self.config.win_ver() {
317                        if let Some(file_ver) = self.system.read_version(entry) {
318                            file = file.with_version(file_ver);
319                        }
320                    }
321                    if let Some((link_path, link_type)) = link_data {
322                        file = file.with_link(link_path, link_type);
323                    }
324                    return Ok(Some(file));
325                }
326            }
327        }
328        Ok(None)
329    }
330
331    fn find_parents(
332        &self,
333        files: &RefCell<BTreeSet<File>>,
334        abs_root: &Path,
335        rel_root: &Path,
336    ) -> MyResult<()> {
337        if self.config.show_indent() {
338            let parents = find_parents(files)?;
339            for (abs_path, file_depth) in parents.into_iter() {
340                self.insert_parent(files, abs_root, rel_root, abs_path, file_depth);
341            }
342        }
343        Ok(())
344    }
345
346    #[allow(unused_mut)]
347    fn insert_parent(
348        &self,
349        files: &RefCell<BTreeSet<File>>,
350        abs_root: &Path,
351        rel_root: &Path,
352        abs_path: PathBuf,
353        file_depth: usize,
354    ) {
355        if let Some(rel_path) = create_relative(abs_root, rel_root, &abs_path) {
356            if let Some(abs_dir) = select_parent(&abs_path, FileKind::Dir) {
357                if let Some(rel_dir) = select_parent_from_owned(rel_path, FileKind::Dir) {
358                    let sys_entry = self.system.get_entry(&abs_path).ok();
359                    let inner_depth = sys_entry.as_ref().and_then(|e| e.inner_depth());
360                    let file_mode = sys_entry.as_ref().map(|e| e.file_mode()).unwrap_or_default();
361                    let file_time = sys_entry.as_ref().map(|e| e.file_time()).unwrap_or(SystemTime::UNIX_EPOCH);
362                    let file_name = String::from("");
363                    let file_ext = String::from("");
364                    let mut file = File::new(abs_dir, rel_dir, file_depth, inner_depth, file_name, file_ext, FileKind::Dir)
365                        .with_mode(file_mode)
366                        .with_time(DateTime::<Utc>::from(file_time));
367                    #[cfg(unix)]
368                    if self.config.show_owner() {
369                        let uid = sys_entry.as_ref().map(|e| e.owner_uid()).unwrap_or_default();
370                        let gid = sys_entry.as_ref().map(|e| e.owner_gid()).unwrap_or_default();
371                        let user = self.system.find_user(uid);
372                        let group = self.system.find_group(gid);
373                        file = file.with_owner(user, group);
374                    }
375                    files.borrow_mut().insert(file);
376                }
377            }
378        }
379    }
380}
381
382fn requires_wildcard(root: &Path, zip_expand: bool) -> bool {
383    let wildcard_regex = regex!(r"(^\.+$|[\\/]\.*$)");
384    if let Some(root) = root.to_str() {
385        if wildcard_regex.is_match(root) {
386            return true;
387        }
388    }
389    ZipKind::from_path(root, zip_expand).is_some()
390}
391
392pub fn count_components(path: &Path) -> usize {
393    path
394        .components()
395        .filter(|c| matches!(c, Component::Normal(_)))
396        .count()
397}
398
399fn find_parents(files: &RefCell<BTreeSet<File>>) -> MyResult<BTreeMap<PathBuf, usize>> {
400    let mut parents = BTreeMap::new();
401    for file in files.borrow().iter() {
402        let file_depth = file.file_depth + file.file_type.dir_offset();
403        find_ancestors(&mut parents, &file.abs_dir, file_depth)?;
404    }
405    Ok(parents)
406}
407
408fn find_ancestors(
409    parents: &mut BTreeMap<PathBuf, usize>,
410    abs_path: &Path,
411    file_depth: usize,
412) -> MyResult<()> {
413    if let Some(file_depth) = file_depth.checked_sub(1) {
414        if file_depth > 0 {
415            if let Some(old_depth) = parents.insert(PathBuf::from(abs_path), file_depth) {
416                if old_depth != file_depth {
417                    let error = format!("Inconsistent depth: {}", abs_path.display());
418                    return Err(MyError::Text(error));
419                }
420            } else {
421                if let Some(abs_path) = abs_path.parent() {
422                    find_ancestors(parents, abs_path, file_depth)?;
423                }
424            }
425        }
426    }
427    Ok(())
428}
429
430fn create_relative(
431    abs_root: &Path,
432    rel_root: &Path,
433    abs_path: &Path,
434) -> Option<PathBuf> {
435    let mut abs_root = PathBuf::from(abs_root);
436    let mut rel_path = PathBuf::new();
437    loop {
438        if let Ok(path) = abs_path.strip_prefix(&abs_root) {
439            rel_path.push(path);
440            return Some(rel_root.join(rel_path).clean());
441        }
442        if !abs_root.pop() {
443            return None;
444        }
445        rel_path.push("..");
446    }
447}
448
449fn select_parent_from_owned(path: PathBuf, file_type: FileKind) -> Option<PathBuf> {
450    if file_type == FileKind::Dir {
451        Some(path)
452    } else {
453        find_parent(&path)
454    }
455}
456
457fn select_parent(path: &Path, file_type: FileKind) -> Option<PathBuf> {
458    if file_type == FileKind::Dir {
459        Some(PathBuf::from(path))
460    } else {
461        find_parent(path)
462    }
463}
464
465fn select_name(path: &Path, file_type: FileKind) -> Option<String> {
466    if file_type == FileKind::Dir {
467        Some(String::from(""))
468    } else {
469        find_name(path)
470    }
471}
472
473fn find_parent(path: &Path) -> Option<PathBuf> {
474    path.parent().map(PathBuf::from)
475}
476
477fn find_name(path: &Path) -> Option<String> {
478    path.file_name().and_then(OsStr::to_str).map(String::from)
479}
480
481fn find_extension(path: &Path, file_type: FileKind) -> String {
482    match file_type {
483        FileKind::File(_) | FileKind::Link(_) => path.extension()
484            .and_then(OsStr::to_str)
485            .map(str::to_ascii_lowercase)
486            .map(|ext| format!(".{ext}"))
487            .unwrap_or_default(),
488        _ => String::default(),
489    }
490}
491
492fn select_size(
493    entry: &dyn Entry,
494    link_data: &Option<(PathBuf, FileKind)>,
495    file_type: FileKind,
496) -> u64 {
497    if file_type == FileKind::Dir {
498        return 0;
499    }
500    if let Some((_, link_type)) = link_data {
501        if *link_type == FileKind::Dir {
502            return 0;
503        }
504    }
505    entry.file_size()
506}
507
508#[cfg(test)]
509mod tests {
510    use crate::cli::file::{ExecKind, FileKind};
511    use crate::cli::recent::RecentKind;
512    use crate::config::Config;
513    use crate::finder::{create_relative, requires_wildcard, Finder};
514    use crate::fs::file::File;
515    use crate::fs::system::tests::MockSystem;
516    use chrono::{DateTime, TimeZone, Utc};
517    use pretty_assertions::assert_eq;
518    use std::path::PathBuf;
519
520    #[test]
521    fn test_dir_requires_wildcard() {
522        assert_eq!(true, test_wildcard(".", false));
523        assert_eq!(true, test_wildcard("..", false));
524        assert_eq!(true, test_wildcard("/", false));
525        assert_eq!(true, test_wildcard("/path/to/dir/", false));
526        assert_eq!(true, test_wildcard("/path/to/dir/.", false));
527        assert_eq!(true, test_wildcard("/path/to/dir/..", false));
528        assert_eq!(true, test_wildcard(r"\", false));
529        assert_eq!(true, test_wildcard(r"\path\to\dir\", false));
530        assert_eq!(true, test_wildcard(r"\path\to\dir\.", false));
531        assert_eq!(true, test_wildcard(r"\path\to\dir\..", false));
532    }
533
534    #[test]
535    fn test_file_requires_wildcard() {
536        assert_eq!(false, test_wildcard("lower", false));
537        assert_eq!(false, test_wildcard("lower.zip", false));
538        assert_eq!(false, test_wildcard("lower.7z", false));
539        assert_eq!(false, test_wildcard("lower.tar", false));
540        assert_eq!(false, test_wildcard("UPPER", false));
541        assert_eq!(false, test_wildcard("UPPER.ZIP", false));
542        assert_eq!(false, test_wildcard("UPPER.7Z", false));
543        assert_eq!(false, test_wildcard("UPPER.TAR", false));
544        assert_eq!(false, test_wildcard("/path/to/dir/lower", false));
545        assert_eq!(false, test_wildcard("/path/to/dir/lower.zip", false));
546        assert_eq!(false, test_wildcard("/path/to/dir/lower.7z", false));
547        assert_eq!(false, test_wildcard("/path/to/dir/lower.tar", false));
548        assert_eq!(false, test_wildcard("/path/to/dir/UPPER", false));
549        assert_eq!(false, test_wildcard("/path/to/dir/UPPER.ZIP", false));
550        assert_eq!(false, test_wildcard("/path/to/dir/UPPER.7Z", false));
551        assert_eq!(false, test_wildcard("/path/to/dir/UPPER.TAR", false));
552        assert_eq!(false, test_wildcard(r"\path\to\dir\lower", false));
553        assert_eq!(false, test_wildcard(r"\path\to\dir\lower.zip", false));
554        assert_eq!(false, test_wildcard(r"\path\to\dir\lower.7z", false));
555        assert_eq!(false, test_wildcard(r"\path\to\dir\lower.tar", false));
556        assert_eq!(false, test_wildcard(r"\path\to\dir\UPPER", false));
557        assert_eq!(false, test_wildcard(r"\path\to\dir\UPPER.ZIP", false));
558        assert_eq!(false, test_wildcard(r"\path\to\dir\UPPER.7Z", false));
559        assert_eq!(false, test_wildcard(r"\path\to\dir\UPPER.TAR", false));
560    }
561
562    #[test]
563    fn test_archive_requires_wildcard() {
564        assert_eq!(false, test_wildcard("lower", true));
565        assert_eq!(true, test_wildcard("lower.zip", true));
566        assert_eq!(true, test_wildcard("lower.7z", true));
567        assert_eq!(true, test_wildcard("lower.tar", true));
568        assert_eq!(false, test_wildcard("UPPER", true));
569        assert_eq!(true, test_wildcard("UPPER.ZIP", true));
570        assert_eq!(true, test_wildcard("UPPER.7Z", true));
571        assert_eq!(true, test_wildcard("UPPER.TAR", true));
572        assert_eq!(false, test_wildcard("/path/to/dir/lower", true));
573        assert_eq!(true, test_wildcard("/path/to/dir/lower.zip", true));
574        assert_eq!(true, test_wildcard("/path/to/dir/lower.7z", true));
575        assert_eq!(true, test_wildcard("/path/to/dir/lower.tar", true));
576        assert_eq!(false, test_wildcard("/path/to/dir/UPPER", true));
577        assert_eq!(true, test_wildcard("/path/to/dir/UPPER.ZIP", true));
578        assert_eq!(true, test_wildcard("/path/to/dir/UPPER.7Z", true));
579        assert_eq!(true, test_wildcard("/path/to/dir/UPPER.TAR", true));
580        assert_eq!(false, test_wildcard(r"\path\to\dir\lower", true));
581        assert_eq!(true, test_wildcard(r"\path\to\dir\lower.zip", true));
582        assert_eq!(true, test_wildcard(r"\path\to\dir\lower.7z", true));
583        assert_eq!(true, test_wildcard(r"\path\to\dir\lower.tar", true));
584        assert_eq!(false, test_wildcard(r"\path\to\dir\UPPER", true));
585        assert_eq!(true, test_wildcard(r"\path\to\dir\UPPER.ZIP", true));
586        assert_eq!(true, test_wildcard(r"\path\to\dir\UPPER.7Z", true));
587        assert_eq!(true, test_wildcard(r"\path\to\dir\UPPER.TAR", true));
588    }
589
590    fn test_wildcard(root: &str, zip_expand: bool) -> bool {
591        let root = PathBuf::from(root);
592        requires_wildcard(&root, zip_expand)
593    }
594
595    #[test]
596    #[cfg(all(windows, any()))]
597    fn test_counts_components() {
598        use crate::finder::count_components;
599        assert_eq!(0, count_components(&PathBuf::from(r"")));
600        assert_eq!(0, count_components(&PathBuf::from(r"..")));
601        assert_eq!(1, count_components(&PathBuf::from(r"..\dir")));
602        assert_eq!(2, count_components(&PathBuf::from(r"..\dir\subdir")));
603        assert_eq!(0, count_components(&PathBuf::from(r".")));
604        assert_eq!(1, count_components(&PathBuf::from(r".\dir")));
605        assert_eq!(2, count_components(&PathBuf::from(r".\dir\subdir")));
606        assert_eq!(1, count_components(&PathBuf::from(r"dir")));
607        assert_eq!(2, count_components(&PathBuf::from(r"dir\subdir")));
608        assert_eq!(1, count_components(&PathBuf::from(r"\dir")));
609        assert_eq!(2, count_components(&PathBuf::from(r"\dir\subdir")));
610        assert_eq!(1, count_components(&PathBuf::from(r"D:\dir")));
611        assert_eq!(2, count_components(&PathBuf::from(r"D:\dir\subdir")));
612        assert_eq!(1, count_components(&PathBuf::from(r"\\unc\dir")));
613        assert_eq!(2, count_components(&PathBuf::from(r"\\unc\dir\subdir")));
614    }
615
616    #[test]
617    #[cfg(not(windows))]
618    fn test_counts_components() {
619        use crate::finder::count_components;
620        assert_eq!(0, count_components(&PathBuf::from("")));
621        assert_eq!(0, count_components(&PathBuf::from("..")));
622        assert_eq!(1, count_components(&PathBuf::from("../dir")));
623        assert_eq!(2, count_components(&PathBuf::from("../dir/subdir")));
624        assert_eq!(0, count_components(&PathBuf::from(".")));
625        assert_eq!(1, count_components(&PathBuf::from("./dir")));
626        assert_eq!(2, count_components(&PathBuf::from("./dir/subdir")));
627        assert_eq!(1, count_components(&PathBuf::from("dir")));
628        assert_eq!(2, count_components(&PathBuf::from("dir/subdir")));
629        assert_eq!(1, count_components(&PathBuf::from("/dir")));
630        assert_eq!(2, count_components(&PathBuf::from("/dir/subdir")));
631    }
632
633    #[test]
634    fn test_creates_relative_paths() {
635        assert_eq!(Some(PathBuf::from("..")), test_relative("/root"));
636        assert_eq!(Some(PathBuf::from("../dir")), test_relative("/root/dir"));
637        assert_eq!(Some(PathBuf::from("../dir/subdir")), test_relative("/root/dir/subdir"));
638        assert_eq!(Some(PathBuf::from("../dir2")), test_relative("/root/dir2"));
639        assert_eq!(Some(PathBuf::from("../dir2/subdir")), test_relative("/root/dir2/subdir"));
640        assert_eq!(Some(PathBuf::from("../..")), test_relative("/"));
641        assert_eq!(Some(PathBuf::from("../../root2/dir")), test_relative("/root2/dir"));
642        assert_eq!(Some(PathBuf::from("../../root2/dir/subdir")), test_relative("/root2/dir/subdir"));
643    }
644
645    fn test_relative(abs_path: &str) -> Option<PathBuf> {
646        let abs_root = PathBuf::from("/root/dir");
647        let rel_root = PathBuf::from("../dir");
648        let abs_path = PathBuf::from(abs_path);
649        create_relative(&abs_root, &rel_root, &abs_path)
650    }
651
652    #[test]
653    fn test_parses_file_attributes_no_indent_in_root_directory() {
654        let config = Config::default()
655            .with_patterns(vec!["*"])
656            .with_recurse_all(true);
657        let system = create_system(&config, create_entries);
658        let finder = create_finder(&config, &system);
659        let files = find_files(&finder);
660        assert_eq!(10, files.len());
661        assert_data(files.get(0), 1, FileKind::File(ExecKind::User), 0o744, 100, 2023, 1, 1);
662        assert_data(files.get(1), 1, FileKind::Dir, 0o755, 0, 2023, 2, 2);
663        assert_data(files.get(2), 2, FileKind::Link(true), 0o755, 0, 2023, 3, 3);
664        assert_data(files.get(3), 2, FileKind::Link(true), 0o644, 500, 2023, 5, 5);
665        assert_data(files.get(4), 2, FileKind::Link(false), 0o644, 0, 1970, 1, 1);
666        assert_data(files.get(5), 2, FileKind::Dir, 0o755, 0, 2023, 3, 3);
667        assert_data(files.get(6), 3, FileKind::File(ExecKind::None), 0o644, 400, 2023, 4, 4);
668        assert_data(files.get(7), 3, FileKind::File(ExecKind::None), 0o644, 500, 2023, 5, 5);
669        assert_data(files.get(8), 3, FileKind::File(ExecKind::None), 0o644, 600, 2023, 6, 6);
670        assert_data(files.get(9), 3, FileKind::File(ExecKind::None), 0o644, 700, 2023, 7, 7);
671        assert_path(files.get(0), "/root", "", "archive.sh", ".sh");
672        assert_path(files.get(1), "/root/dir", "dir", "", "");
673        assert_path(files.get(2), "/root/dir", "dir", "link1", "");
674        assert_path(files.get(3), "/root/dir", "dir", "link2", "");
675        assert_path(files.get(4), "/root/dir", "dir", "link3", "");
676        assert_path(files.get(5), "/root/dir/subdir", "dir/subdir", "", "");
677        assert_path(files.get(6), "/root/dir/subdir", "dir/subdir", "alpha.csv", ".csv");
678        assert_path(files.get(7), "/root/dir/subdir", "dir/subdir", "alpha.txt", ".txt");
679        assert_path(files.get(8), "/root/dir/subdir", "dir/subdir", "beta.csv", ".csv");
680        assert_path(files.get(9), "/root/dir/subdir", "dir/subdir", "beta.txt", ".txt");
681        assert_link(files.get(0), None);
682        assert_link(files.get(1), None);
683        assert_link(files.get(2), Some(("/root/dir/subdir", FileKind::Dir)));
684        assert_link(files.get(3), Some(("/root/dir/subdir/alpha.txt", FileKind::File(ExecKind::None))));
685        assert_link(files.get(4), Some(("/etc/missing.txt", FileKind::Link(false))));
686        assert_link(files.get(5), None);
687        assert_link(files.get(6), None);
688        assert_link(files.get(7), None);
689        assert_link(files.get(8), None);
690        assert_link(files.get(9), None);
691    }
692
693    #[test]
694    fn test_parses_file_attributes_no_indent_in_branch_directory() {
695        let config = Config::default()
696            .with_patterns(vec!["dir/*"])
697            .with_recurse_all(true);
698        let system = create_system(&config, create_entries);
699        let finder = create_finder(&config, &system);
700        let files = find_files(&finder);
701        assert_eq!(8, files.len());
702        assert_data(files.get(0), 2, FileKind::Link(true), 0o755, 0, 2023, 3, 3);
703        assert_data(files.get(1), 2, FileKind::Link(true), 0o644, 500, 2023, 5, 5);
704        assert_data(files.get(2), 2, FileKind::Link(false), 0o644, 0, 1970, 1, 1);
705        assert_data(files.get(3), 2, FileKind::Dir, 0o755, 0, 2023, 3, 3);
706        assert_data(files.get(4), 3, FileKind::File(ExecKind::None), 0o644, 400, 2023, 4, 4);
707        assert_data(files.get(5), 3, FileKind::File(ExecKind::None), 0o644, 500, 2023, 5, 5);
708        assert_data(files.get(6), 3, FileKind::File(ExecKind::None), 0o644, 600, 2023, 6, 6);
709        assert_data(files.get(7), 3, FileKind::File(ExecKind::None), 0o644, 700, 2023, 7, 7);
710        assert_path(files.get(0), "/root/dir", "dir", "link1", "");
711        assert_path(files.get(1), "/root/dir", "dir", "link2", "");
712        assert_path(files.get(2), "/root/dir", "dir", "link3", "");
713        assert_path(files.get(3), "/root/dir/subdir", "dir/subdir", "", "");
714        assert_path(files.get(4), "/root/dir/subdir", "dir/subdir", "alpha.csv", ".csv");
715        assert_path(files.get(5), "/root/dir/subdir", "dir/subdir", "alpha.txt", ".txt");
716        assert_path(files.get(6), "/root/dir/subdir", "dir/subdir", "beta.csv", ".csv");
717        assert_path(files.get(7), "/root/dir/subdir", "dir/subdir", "beta.txt", ".txt");
718        assert_link(files.get(0), Some(("/root/dir/subdir", FileKind::Dir)));
719        assert_link(files.get(1), Some(("/root/dir/subdir/alpha.txt", FileKind::File(ExecKind::None))));
720        assert_link(files.get(2), Some(("/etc/missing.txt", FileKind::Link(false))));
721        assert_link(files.get(3), None);
722        assert_link(files.get(4), None);
723        assert_link(files.get(5), None);
724        assert_link(files.get(6), None);
725        assert_link(files.get(7), None);
726    }
727
728    #[test]
729    fn test_parses_file_attributes_with_indent_in_root_directory() {
730        let config = Config::default()
731            .with_patterns(vec!["*"])
732            .with_recurse_all(true)
733            .with_show_indent(true)
734            .with_filter_types(vec![
735                FileKind::File(ExecKind::None),
736                FileKind::File(ExecKind::User),
737                FileKind::File(ExecKind::Other),
738                FileKind::Link(false),
739                FileKind::Link(true),
740            ]);
741        let system = create_system(&config, create_entries);
742        let finder = create_finder(&config, &system);
743        let files = find_files(&finder);
744        assert_eq!(10, files.len());
745        assert_data(files.get(0), 1, FileKind::File(ExecKind::User), 0o744, 100, 2023, 1, 1);
746        assert_data(files.get(1), 1, FileKind::Dir, 0o755, 0, 2023, 2, 2);
747        assert_data(files.get(2), 2, FileKind::Link(true), 0o755, 0, 2023, 3, 3);
748        assert_data(files.get(3), 2, FileKind::Link(true), 0o644, 500, 2023, 5, 5);
749        assert_data(files.get(4), 2, FileKind::Link(false), 0o644, 0, 1970, 1, 1);
750        assert_data(files.get(5), 2, FileKind::Dir, 0o755, 0, 2023, 3, 3);
751        assert_data(files.get(6), 3, FileKind::File(ExecKind::None), 0o644, 400, 2023, 4, 4);
752        assert_data(files.get(7), 3, FileKind::File(ExecKind::None), 0o644, 500, 2023, 5, 5);
753        assert_data(files.get(8), 3, FileKind::File(ExecKind::None), 0o644, 600, 2023, 6, 6);
754        assert_data(files.get(9), 3, FileKind::File(ExecKind::None), 0o644, 700, 2023, 7, 7);
755        assert_path(files.get(0), "/root", "", "archive.sh", ".sh");
756        assert_path(files.get(1), "/root/dir", "dir", "", "");
757        assert_path(files.get(2), "/root/dir", "dir", "link1", "");
758        assert_path(files.get(3), "/root/dir", "dir", "link2", "");
759        assert_path(files.get(4), "/root/dir", "dir", "link3", "");
760        assert_path(files.get(5), "/root/dir/subdir", "dir/subdir", "", "");
761        assert_path(files.get(6), "/root/dir/subdir", "dir/subdir", "alpha.csv", ".csv");
762        assert_path(files.get(7), "/root/dir/subdir", "dir/subdir", "alpha.txt", ".txt");
763        assert_path(files.get(8), "/root/dir/subdir", "dir/subdir", "beta.csv", ".csv");
764        assert_path(files.get(9), "/root/dir/subdir", "dir/subdir", "beta.txt", ".txt");
765        assert_link(files.get(0), None);
766        assert_link(files.get(1), None);
767        assert_link(files.get(2), Some(("/root/dir/subdir", FileKind::Dir)));
768        assert_link(files.get(3), Some(("/root/dir/subdir/alpha.txt", FileKind::File(ExecKind::None))));
769        assert_link(files.get(4), Some(("/etc/missing.txt", FileKind::Link(false))));
770        assert_link(files.get(5), None);
771        assert_link(files.get(6), None);
772        assert_link(files.get(7), None);
773        assert_link(files.get(8), None);
774        assert_link(files.get(9), None);
775    }
776
777    #[test]
778    fn test_finds_multiple_patterns_in_same_directory() {
779        let expected = vec![
780            "/root/dir/subdir/alpha.csv",
781            "/root/dir/subdir/alpha.txt",
782            "/root/dir/subdir/beta.txt",
783        ];
784        let config = Config::default()
785            .with_patterns(vec!["dir/subdir/alpha.*", "dir/subdir/*.txt"])
786            .with_recurse_all(true);
787        let system = create_system(&config, create_entries);
788        let finder = create_finder(&config, &system);
789        let files = find_files(&finder);
790        let paths = convert_paths(files);
791        assert_eq!(expected, paths);
792    }
793
794    #[test]
795    fn test_finds_multiple_patterns_in_diff_directories() {
796        let expected = vec![
797            "/root/dir/subdir/alpha.csv",
798            "/root/dir/subdir/alpha.txt",
799            "/root/dir/subdir/beta.txt",
800        ];
801        let config = Config::default()
802            .with_patterns(vec!["dir/alpha.*", "dir/subdir/*.txt"])
803            .with_recurse_all(true);
804        let system = create_system(&config, create_entries);
805        let finder = create_finder(&config, &system);
806        let files = find_files(&finder);
807        let paths = convert_paths(files);
808        assert_eq!(expected, paths);
809    }
810
811    #[test]
812    fn test_finds_files_if_recurse_no_indent_in_root_directory() {
813        let expected = vec![
814            "/root/dir/subdir/alpha.txt",
815            "/root/dir/subdir/beta.txt",
816        ];
817        let config = Config::default()
818            .with_patterns(vec!["*.txt"])
819            .with_recurse_all(true);
820        let system = create_system(&config, create_entries);
821        let finder = create_finder(&config, &system);
822        let files = find_files(&finder);
823        let paths = convert_paths(files);
824        assert_eq!(expected, paths);
825    }
826
827    #[test]
828    fn test_finds_parents_if_recurse_with_indent_in_root_directory() {
829        let expected = vec![
830            "/root/dir/",
831            "/root/dir/subdir/",
832            "/root/dir/subdir/alpha.txt",
833            "/root/dir/subdir/beta.txt",
834        ];
835        let config = Config::default()
836            .with_patterns(vec!["*.txt"])
837            .with_recurse_all(true)
838            .with_show_indent(true);
839        let system = create_system(&config, create_entries);
840        let finder = create_finder(&config, &system);
841        let files = find_files(&finder);
842        let paths = convert_paths(files);
843        assert_eq!(expected, paths);
844    }
845
846    #[test]
847    fn test_finds_parents_if_recurse_with_indent_in_branch_directory() {
848        let expected = vec![
849            "/root/dir/",
850            "/root/dir/subdir/",
851            "/root/dir/subdir/alpha.txt",
852            "/root/dir/subdir/beta.txt",
853        ];
854        let config = Config::default()
855            .with_patterns(vec!["dir/*.txt"])
856            .with_recurse_all(true)
857            .with_show_indent(true);
858        let system = create_system(&config, create_entries);
859        let finder = create_finder(&config, &system);
860        let files = find_files(&finder);
861        let paths = convert_paths(files);
862        assert_eq!(expected, paths);
863    }
864
865    #[test]
866    fn test_finds_parents_if_recurse_with_indent_in_leaf_directory() {
867        let expected = vec![
868            "/root/dir/",
869            "/root/dir/subdir/",
870            "/root/dir/subdir/alpha.txt",
871            "/root/dir/subdir/beta.txt",
872        ];
873        let config = Config::default()
874            .with_patterns(vec!["dir/subdir/*.txt"])
875            .with_recurse_all(true)
876            .with_show_indent(true);
877        let system = create_system(&config, create_entries);
878        let finder = create_finder(&config, &system);
879        let files = find_files(&finder);
880        let paths = convert_paths(files);
881        assert_eq!(expected, paths);
882    }
883
884    #[test]
885    fn test_hides_directories_if_order_by_name() {
886        let expected = vec![
887            "/root/archive.sh",
888            "/root/dir/link1",
889            "/root/dir/link2",
890            "/root/dir/link3",
891            "/root/dir/subdir/alpha.csv",
892            "/root/dir/subdir/alpha.txt",
893            "/root/dir/subdir/beta.csv",
894            "/root/dir/subdir/beta.txt",
895        ];
896        let config = Config::default()
897            .with_patterns(vec!["*"])
898            .with_recurse_all(true)
899            .with_sort_name(true);
900        let system = create_system(&config, create_entries);
901        let finder = create_finder(&config, &system);
902        let files = find_files(&finder);
903        let paths = convert_paths(files);
904        assert_eq!(expected, paths);
905    }
906
907    #[test]
908    fn test_finds_files_with_bare_filename() {
909        let expected = vec![
910            "/root/dir/subdir/beta.csv",
911        ];
912        let config = Config::default()
913            .with_patterns(vec!["beta.csv"])
914            .with_recurse_all(true);
915        let system = create_system(&config, create_entries);
916        let finder = create_finder(&config, &system);
917        let files = find_files(&finder);
918        let paths = convert_paths(files);
919        assert_eq!(expected, paths);
920    }
921
922    #[test]
923    fn test_finds_files_with_bare_extension() {
924        let expected = vec![
925            "/root/dir/subdir/alpha.csv",
926            "/root/dir/subdir/beta.csv",
927        ];
928        let config = Config::default()
929            .with_patterns(vec![".csv"])
930            .with_recurse_all(true);
931        let system = create_system(&config, create_entries);
932        let finder = create_finder(&config, &system);
933        let files = find_files(&finder);
934        let paths = convert_paths(files);
935        assert_eq!(expected, paths);
936    }
937
938    #[test]
939    fn test_filters_files_by_minimum_depth() {
940        let expected = vec![
941            "/root/dir/link1",
942            "/root/dir/link2",
943            "/root/dir/link3",
944            "/root/dir/subdir/",
945            "/root/dir/subdir/alpha.csv",
946            "/root/dir/subdir/alpha.txt",
947            "/root/dir/subdir/beta.csv",
948            "/root/dir/subdir/beta.txt",
949        ];
950        let config = Config::default()
951            .with_patterns(vec!["*"])
952            .with_min_depth(2);
953        let system = create_system(&config, create_entries);
954        let finder = create_finder(&config, &system);
955        let files = find_files(&finder);
956        let paths = convert_paths(files);
957        assert_eq!(expected, paths);
958    }
959
960    #[test]
961    fn test_filters_files_by_maximum_depth() {
962        let expected = vec![
963            "/root/archive.sh",
964            "/root/dir/",
965            "/root/dir/link1",
966            "/root/dir/link2",
967            "/root/dir/link3",
968            "/root/dir/subdir/",
969        ];
970        let config = Config::default()
971            .with_patterns(vec!["*"])
972            .with_max_depth(2);
973        let system = create_system(&config, create_entries);
974        let finder = create_finder(&config, &system);
975        let files = find_files(&finder);
976        let paths = convert_paths(files);
977        assert_eq!(expected, paths);
978    }
979
980    #[test]
981    fn test_filters_files_by_file_type() {
982        let expected = vec![
983            "/root/archive.sh",
984            "/root/dir/subdir/alpha.csv",
985            "/root/dir/subdir/alpha.txt",
986            "/root/dir/subdir/beta.csv",
987            "/root/dir/subdir/beta.txt",
988        ];
989        let config = Config::default()
990            .with_patterns(vec!["*"])
991            .with_recurse_all(true)
992            .with_filter_types(vec![
993                FileKind::File(ExecKind::None),
994                FileKind::File(ExecKind::User),
995                FileKind::File(ExecKind::Other),
996            ]);
997        let system = create_system(&config, create_entries);
998        let finder = create_finder(&config, &system);
999        let files = find_files(&finder);
1000        let paths = convert_paths(files);
1001        assert_eq!(expected, paths);
1002    }
1003
1004    #[test]
1005    fn test_filters_files_by_recent_time() {
1006        let expected = vec![
1007            "/root/dir/link2",
1008            "/root/dir/subdir/alpha.txt",
1009            "/root/dir/subdir/beta.csv",
1010            "/root/dir/subdir/beta.txt",
1011        ];
1012        let config = Config::default()
1013            .with_patterns(vec!["*"])
1014            .with_recurse_all(true)
1015            .with_curr_time(2024, 1, 1, 0, 0, 0)
1016            .with_filter_recent(RecentKind::Month(8));
1017        let system = create_system(&config, create_entries);
1018        let finder = create_finder(&config, &system);
1019        let files = find_files(&finder);
1020        let paths = convert_paths(files);
1021        assert_eq!(expected, paths);
1022    }
1023
1024    #[test]
1025    fn test_calculates_total_from_files() {
1026        let config = Config::default()
1027            .with_patterns(vec!["*"])
1028            .with_recurse_all(true);
1029        let system = create_system(&config, create_entries);
1030        let finder = create_finder(&config, &system);
1031        let files = find_files(&finder);
1032        let total = finder.create_total(&files);
1033        assert_eq!(700, total.max_size);
1034        assert_eq!(2800, total.total_size);
1035        #[cfg(unix)]
1036        assert_eq!(0, total.user_width);
1037        #[cfg(unix)]
1038        assert_eq!(0, total.group_width);
1039        #[cfg(windows)]
1040        assert_eq!(0, total.ver_width);
1041        assert_eq!(4, total.ext_width);
1042        assert_eq!(8, total.num_files);
1043        assert_eq!(2, total.num_dirs);
1044    }
1045
1046    #[test]
1047    #[cfg(unix)]
1048    fn test_calculates_total_from_files_with_no_owners() {
1049        let config = Config::default()
1050            .with_show_owner(true);
1051        let system = create_system(&config, create_entries);
1052        let finder = create_finder(&config, &system);
1053        let files = find_files(&finder);
1054        let total = finder.create_total(&files);
1055        assert_eq!(1, total.user_width);
1056        assert_eq!(1, total.group_width);
1057    }
1058
1059    #[test]
1060    #[cfg(unix)]
1061    fn test_calculates_total_from_files_with_some_owners() {
1062        let config = Config::default()
1063            .with_patterns(vec!["*"])
1064            .with_recurse_all(true)
1065            .with_show_owner(true);
1066        let system = create_system(&config, create_entries);
1067        let finder = create_finder(&config, &system);
1068        let files = find_files(&finder);
1069        let total = finder.create_total(&files);
1070        assert_eq!(5, total.user_width);
1071        assert_eq!(6, total.group_width);
1072    }
1073
1074    fn create_entries(system: &mut MockSystem) {
1075        system.insert_entry(1, 'f', 0o744, 0, 0, 100, 2023, 1, 1, "archive.sh", None);
1076        system.insert_entry(1, 'd', 0o755, 1000, 500, 4096, 2023, 2, 2, "dir", None);
1077        system.insert_entry(2, 'l', 0o644, 1000, 500, 99, 2023, 12, 31, "dir/link1", Some("subdir"));
1078        system.insert_entry(2, 'l', 0o644, 1000, 500, 99, 2023, 12, 31, "dir/link2", Some("subdir/alpha.txt"));
1079        system.insert_entry(2, 'l', 0o644, 1000, 500, 99, 2023, 12, 31, "dir/link3", Some("/etc/missing.txt"));
1080        system.insert_entry(2, 'd', 0o755, 1500, 500, 4096, 2023, 3, 3, "dir/subdir", None);
1081        system.insert_entry(3, 'f', 0o644, 1500, 500, 400, 2023, 4, 4, "dir/subdir/alpha.csv", None);
1082        system.insert_entry(3, 'f', 0o644, 1500, 500, 500, 2023, 5, 5, "dir/subdir/alpha.txt", None);
1083        system.insert_entry(3, 'f', 0o644, 1500, 500, 600, 2023, 6, 6, "dir/subdir/beta.csv", None);
1084        system.insert_entry(3, 'f', 0o644, 1500, 500, 700, 2023, 7, 7, "dir/subdir/beta.txt", None);
1085    }
1086
1087    #[test]
1088    fn test_performs_case_sensitive_search() {
1089        let expected = vec![
1090            "/root/A1.txt",
1091            "/root/A2.txt",
1092        ];
1093        let config = Config::default()
1094            .with_patterns(vec!["A*"])
1095            .with_recurse_all(true)
1096            .with_case_sensitive(true);
1097        let system = create_system(&config, create_cases);
1098        let finder = create_finder(&config, &system);
1099        let files = find_files(&finder);
1100        let paths = convert_paths(files);
1101        assert_eq!(expected, paths);
1102    }
1103
1104    #[test]
1105    fn test_performs_case_insensitive_search() {
1106        let expected = vec![
1107            "/root/A1.txt",
1108            "/root/A2.txt",
1109            "/root/a1.txt",
1110            "/root/a2.txt",
1111        ];
1112        let config = Config::default()
1113            .with_patterns(vec!["A*"])
1114            .with_recurse_all(true)
1115            .with_case_sensitive(false);
1116        let system = create_system(&config, create_cases);
1117        let finder = create_finder(&config, &system);
1118        let files = find_files(&finder);
1119        let paths = convert_paths(files);
1120        assert_eq!(expected, paths);
1121    }
1122
1123    fn create_cases(system: &mut MockSystem) {
1124        system.insert_entry(1, 'f', 0o000, 0, 0, 0, 1970, 1, 1, "A1.txt", None);
1125        system.insert_entry(1, 'f', 0o000, 0, 0, 0, 1970, 1, 1, "A2.txt", None);
1126        system.insert_entry(1, 'f', 0o000, 0, 0, 0, 1970, 1, 1, "B3.txt", None);
1127        system.insert_entry(1, 'f', 0o000, 0, 0, 0, 1970, 1, 1, "B4.txt", None);
1128        system.insert_entry(1, 'f', 0o000, 0, 0, 0, 1970, 1, 1, "a1.txt", None);
1129        system.insert_entry(1, 'f', 0o000, 0, 0, 0, 1970, 1, 1, "a2.txt", None);
1130        system.insert_entry(1, 'f', 0o000, 0, 0, 0, 1970, 1, 1, "b3.txt", None);
1131        system.insert_entry(1, 'f', 0o000, 0, 0, 0, 1970, 1, 1, "b4.txt", None);
1132    }
1133
1134    #[cfg(unix)]
1135    fn create_system<F>(config: &Config, mut setter: F) -> MockSystem<'_> where
1136        F: FnMut(&mut MockSystem),
1137    {
1138        use std::collections::BTreeMap;
1139        let current = PathBuf::from("/root");
1140        let user_names = BTreeMap::from([
1141            (0, String::from("root")),
1142            (1000, String::from("alice")),
1143            (1500, String::from("bob")),
1144        ]);
1145        let group_names = BTreeMap::from([
1146            (0, String::from("root")),
1147            (500, String::from("public")),
1148        ]);
1149        let mut system = MockSystem::new(config, current, user_names, group_names);
1150        setter(&mut system);
1151        system
1152    }
1153
1154    #[cfg(not(unix))]
1155    fn create_system<F>(config: &Config, mut setter: F) -> MockSystem<'_> where
1156        F: FnMut(&mut MockSystem),
1157    {
1158        let current = PathBuf::from("/root");
1159        let mut system = MockSystem::new(config, current);
1160        setter(&mut system);
1161        system
1162    }
1163
1164    fn create_finder<'a>(
1165        config: &'a Config,
1166        system: &'a MockSystem,
1167    ) -> Finder<'a, MockSystem<'a>> {
1168        let current = PathBuf::from("/root");
1169        Finder::new(config, system, &Utc, current, false)
1170    }
1171
1172    fn find_files(finder: &Finder<MockSystem>) -> Vec<File> {
1173        let mut files = finder.find_files().unwrap();
1174        files.sort_by_key(File::get_path);
1175        files
1176    }
1177
1178    fn assert_data(
1179        file: Option<&File>,
1180        file_depth: usize,
1181        file_type: FileKind,
1182        file_mode: u32,
1183        file_size: u64,
1184        time_year: i32,
1185        time_month: u32,
1186        time_day: u32,
1187    ) {
1188        let file = file.unwrap();
1189        let file_time = create_time(time_year, time_month, time_day);
1190        assert_eq!(file.file_depth, file_depth, "file depth");
1191        assert_eq!(file.file_type, file_type, "file type");
1192        assert_eq!(file.file_mode, file_mode, "file mode");
1193        assert_eq!(file.file_size, file_size, "file size");
1194        assert_eq!(file.file_time, file_time, "file time");
1195    }
1196
1197    fn assert_path(
1198        file: Option<&File>,
1199        abs_dir: &str,
1200        rel_dir: &str,
1201        file_name: &str,
1202        file_ext: &str,
1203    ) {
1204        let file = file.unwrap();
1205        assert_eq!(file.abs_dir, PathBuf::from(abs_dir), "absolute directory");
1206        assert_eq!(file.rel_dir, PathBuf::from(rel_dir), "relative directory");
1207        assert_eq!(file.file_name, file_name, "file name");
1208        assert_eq!(file.file_ext, file_ext, "file extension");
1209    }
1210
1211    fn assert_link(
1212        file: Option<&File>,
1213        link_data: Option<(&str, FileKind)>,
1214    ) {
1215        let file = file.unwrap();
1216        let link_data = link_data.map(|(p, f)| (PathBuf::from(p), f));
1217        assert_eq!(file.link_data, link_data, "link data");
1218    }
1219
1220    fn create_time(year: i32, month: u32, day: u32) -> DateTime<Utc> {
1221        Utc.with_ymd_and_hms(year, month, day, 0, 0, 0).unwrap()
1222    }
1223
1224    fn convert_paths(files: Vec<File>) -> Vec<String> {
1225        files.into_iter().flat_map(convert_path).collect()
1226    }
1227
1228    #[cfg(windows)]
1229    fn convert_path(file: File) -> Option<String> {
1230        use std::path::MAIN_SEPARATOR_STR;
1231        let path = file.abs_dir.join(file.file_name);
1232        path.to_str().map(|path| path.replace(MAIN_SEPARATOR_STR, "/"))
1233    }
1234
1235    #[cfg(not(windows))]
1236    fn convert_path(file: File) -> Option<String> {
1237        let path = file.abs_dir.join(file.file_name);
1238        path.to_str().map(str::to_string)
1239    }
1240}