use std::path::{Path, PathBuf};
use walkdir::{DirEntry, WalkDir};
use crate::filter::{FilterConfig, extension_of};
use crate::ignorefile::IgnoreFile;
#[derive(Debug, Default)]
pub struct WalkResult {
pub files: Vec<PathBuf>,
pub warnings: Vec<String>,
}
pub fn collect_files(
root: &Path,
cfg: &FilterConfig,
skip: &[PathBuf],
ignore: Option<&IgnoreFile>,
) -> WalkResult {
let mut result = WalkResult::default();
let skip_set = canonical_skip_set(skip);
let root_canonical = fs_canonicalize_or(root, root);
let use_skip = !skip_set.is_empty();
for entry in WalkDir::new(root)
.follow_links(false)
.into_iter()
.filter_entry(|e| keep_entry(e, cfg, root, ignore))
{
match entry {
Ok(e) => {
if !e.file_type().is_file() {
continue;
}
let path = e.path();
if use_skip && is_skipped(path, root, &root_canonical, &skip_set) {
continue;
}
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 canonical_skip_set(skip: &[PathBuf]) -> Vec<PathBuf> {
skip.iter()
.filter_map(|p| {
if let Ok(c) = std::fs::canonicalize(p) {
return Some(c);
}
let parent = p.parent()?;
let parent_c = std::fs::canonicalize(parent).ok()?;
let name = p.file_name()?;
Some(parent_c.join(name))
})
.collect()
}
fn is_skipped(path: &Path, root: &Path, root_canonical: &Path, skip_set: &[PathBuf]) -> bool {
let Ok(rel) = path.strip_prefix(root) else {
return false;
};
let candidate = root_canonical.join(rel);
skip_set.iter().any(|s| s == &candidate)
}
fn keep_entry(e: &DirEntry, cfg: &FilterConfig, root: &Path, ignore: Option<&IgnoreFile>) -> bool {
if e.depth() == 0 {
return true;
}
if e.file_type().is_dir() && cfg.is_excluded_dir_name(e.file_name()) {
return false;
}
if cfg.is_hidden_name(e.file_name()) {
return false;
}
if let Some(rules) = ignore {
let rel = match e.path().strip_prefix(root) {
Ok(r) => r,
Err(_) => return true,
};
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();
if rules.ignores(&refs, e.file_type().is_dir()) {
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)
}
fn fs_canonicalize_or(path: &Path, fallback: &Path) -> PathBuf {
std::fs::canonicalize(path).unwrap_or_else(|_| fallback.to_path_buf())
}