1use std::path::{Path, PathBuf};
11
12use walkdir::{DirEntry, WalkDir};
13
14use crate::filter::{extension_of, FilterConfig};
15
16#[derive(Debug, Default)]
18pub struct WalkResult {
19 pub files: Vec<PathBuf>,
21 pub warnings: Vec<String>,
23}
24
25pub fn collect_files(root: &Path, cfg: &FilterConfig) -> WalkResult {
27 let mut result = WalkResult::default();
28
29 for entry in WalkDir::new(root)
30 .follow_links(false)
31 .into_iter()
32 .filter_entry(|e| keep_entry(e, cfg, root))
33 {
34 match entry {
35 Ok(e) => {
36 if !e.file_type().is_file() {
37 continue;
38 }
39 let path = e.path();
40 let Some(ext) = extension_of(path) else {
41 continue;
42 };
43 if !cfg.extensions.contains(&ext) {
44 continue;
45 }
46 if is_glob_excluded(path, root, cfg) {
47 continue;
48 }
49 result.files.push(path.to_path_buf());
50 }
51 Err(err) => {
52 result
53 .warnings
54 .push(format!("walk warning at {}: {err}", err.path().unwrap_or(root).display()));
55 }
56 }
57 }
58
59 result.files.sort();
60 result
61}
62
63fn keep_entry(e: &DirEntry, cfg: &FilterConfig, root: &Path) -> bool {
66 if e.depth() == 0 {
68 return true;
69 }
70 if cfg.is_excluded_dir_name(e.file_name()) {
71 return false;
72 }
73 if cfg.is_hidden_name(e.file_name()) {
74 return false;
75 }
76 !is_glob_excluded(e.path(), root, cfg)
77}
78
79fn is_glob_excluded(path: &Path, root: &Path, cfg: &FilterConfig) -> bool {
82 if cfg.exclude_globs.is_empty() {
83 return false;
84 }
85 let rel = path.strip_prefix(root).unwrap_or(path);
86 let components: Vec<String> = rel
87 .components()
88 .map(|c| c.as_os_str().to_string_lossy().into_owned())
89 .collect();
90 let refs: Vec<&str> = components.iter().map(String::as_str).collect();
91 cfg.is_excluded_by_glob(&refs)
92}