Skip to main content

utf8_forge/
walker.rs

1//! Recursive candidate collection on top of `walkdir` (`DESIGN.md ยง6`).
2//!
3//! - Symlinks are never followed (invariant #9); symlinked files are also
4//!   skipped entirely.
5//! - Excluded directories are pruned during traversal (never descended into).
6//! - The root entry itself is always kept: an explicitly given `--root` must
7//!   be honored even when its basename collides with an exclusion rule.
8//! - Walk errors (permission, ...) are collected as warnings, never fatal.
9
10use std::path::{Path, PathBuf};
11
12use walkdir::{DirEntry, WalkDir};
13
14use crate::filter::{extension_of, FilterConfig};
15
16/// Collected candidates plus non-fatal traversal warnings.
17#[derive(Debug, Default)]
18pub struct WalkResult {
19    /// Whitelisted files, sorted by path for deterministic processing.
20    pub files: Vec<PathBuf>,
21    /// Human-readable traversal warnings (unreadable directories etc.).
22    pub warnings: Vec<String>,
23}
24
25/// Collect whitelisted files under `root`, sorted by path (invariant #8).
26pub 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
63/// Entry gate for traversal: keep the root, drop excluded/hidden dirs and
64/// dot-files, drop glob-excluded paths.
65fn keep_entry(e: &DirEntry, cfg: &FilterConfig, root: &Path) -> bool {
66    // Always process the explicit root itself.
67    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
79/// Glob check against the root-relative path (safety net on top of dir
80/// pruning, and the primary gate for file paths).
81fn 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}