use std::path::{Path, PathBuf};
use walkdir::{DirEntry, WalkDir};
use crate::filter::{extension_of, FilterConfig};
#[derive(Debug, Default)]
pub struct WalkResult {
pub files: Vec<PathBuf>,
pub warnings: Vec<String>,
}
pub fn collect_files(root: &Path, cfg: &FilterConfig) -> WalkResult {
let mut result = WalkResult::default();
for entry in WalkDir::new(root)
.follow_links(false)
.into_iter()
.filter_entry(|e| keep_entry(e, cfg, root))
{
match entry {
Ok(e) => {
if !e.file_type().is_file() {
continue;
}
let path = e.path();
let Some(ext) = extension_of(path) else {
continue;
};
if !cfg.extensions.contains(&ext) {
continue;
}
if is_glob_excluded(path, root, cfg) {
continue;
}
result.files.push(path.to_path_buf());
}
Err(err) => {
result
.warnings
.push(format!("walk warning at {}: {err}", err.path().unwrap_or(root).display()));
}
}
}
result.files.sort();
result
}
fn keep_entry(e: &DirEntry, cfg: &FilterConfig, root: &Path) -> bool {
if e.depth() == 0 {
return true;
}
if cfg.is_excluded_dir_name(e.file_name()) {
return false;
}
if cfg.is_hidden_name(e.file_name()) {
return false;
}
!is_glob_excluded(e.path(), root, cfg)
}
fn is_glob_excluded(path: &Path, root: &Path, cfg: &FilterConfig) -> bool {
if cfg.exclude_globs.is_empty() {
return false;
}
let rel = path.strip_prefix(root).unwrap_or(path);
let components: Vec<String> = rel
.components()
.map(|c| c.as_os_str().to_string_lossy().into_owned())
.collect();
let refs: Vec<&str> = components.iter().map(String::as_str).collect();
cfg.is_excluded_by_glob(&refs)
}