Skip to main content

utf8_forge/
walker.rs

1// Copyright 2026 houseme
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Recursive candidate collection on top of `walkdir`.
16//!
17//! ```rust
18//! use utf8_forge::filter::{FilterConfig, FilterOptions};
19//! use utf8_forge::walker::collect_files;
20//!
21//! let cfg = FilterConfig::build(&FilterOptions::default(), "--ext").unwrap();
22//! let result = collect_files(std::path::Path::new("."), &cfg, &[], None);
23//! // `result.files` is the sorted whitelist; `result.warnings` carries
24//! // non-fatal traversal problems.
25//! ```
26//!
27//! - Symlinks are never followed, neither directories nor files: a symlinked
28//!   directory is not descended into and a symlinked file is skipped.
29//! - Directory-name / prefix exclusions prune directories during traversal
30//!   (never descended into); the same rule deliberately does **not** drop
31//!   files — a file named `outputfiles_config.md` is legitimate content, and
32//!   files are gated by the extension whitelist anyway.
33//! - The root entry itself is always kept: an explicitly given `--root` must
34//!   be honored even when its basename collides with an exclusion rule.
35//! - `skip` paths (e.g. the `--report` output) are excluded from collection so
36//!   a report written inside the tree never pollutes later runs.
37//! - Walk errors (permission, ...) are collected as warnings, never fatal.
38
39use std::path::{Path, PathBuf};
40
41use walkdir::{DirEntry, WalkDir};
42
43use crate::filter::{FilterConfig, extension_of};
44use crate::ignorefile::IgnoreFile;
45
46/// Collected candidates plus non-fatal traversal warnings.
47#[derive(Debug, Default)]
48pub struct WalkResult {
49    /// Whitelisted files, sorted by path for deterministic processing.
50    pub files: Vec<PathBuf>,
51    /// Human-readable traversal warnings (unreadable directories etc.).
52    pub warnings: Vec<String>,
53}
54
55/// Collect whitelisted files under `root`, sorted by path so every run
56/// processes and reports files in the same deterministic order.
57///
58/// `skip` holds absolute/canonical paths that must never be collected (the
59/// `--report` output; currently-existing paths are canonicalized, and paths
60/// whose parent exists are canonicalized through the parent so not-yet-written
61/// reports resolve correctly).
62pub fn collect_files(
63    root: &Path,
64    cfg: &FilterConfig,
65    skip: &[PathBuf],
66    ignore: Option<&IgnoreFile>,
67) -> WalkResult {
68    let mut result = WalkResult::default();
69    let skip_set = canonical_skip_set(skip);
70    let root_canonical = fs_canonicalize_or(root, root);
71    let use_skip = !skip_set.is_empty();
72
73    for entry in WalkDir::new(root)
74        .follow_links(false)
75        .into_iter()
76        .filter_entry(|e| keep_entry(e, cfg, root, ignore))
77    {
78        match entry {
79            Ok(e) => {
80                if !e.file_type().is_file() {
81                    continue;
82                }
83                let path = e.path();
84                if use_skip && is_skipped(path, root, &root_canonical, &skip_set) {
85                    continue;
86                }
87                let Some(ext) = extension_of(path) else {
88                    continue;
89                };
90                if !cfg.extensions.contains(&ext) {
91                    continue;
92                }
93                if is_glob_excluded(path, root, cfg) {
94                    continue;
95                }
96                result.files.push(path.to_path_buf());
97            }
98            Err(err) => {
99                result.warnings.push(format!(
100                    "walk warning at {}: {err}",
101                    err.path().unwrap_or(root).display()
102                ));
103            }
104        }
105    }
106
107    result.files.sort();
108    result
109}
110
111/// Canonicalize every existing skip path (best effort); skip paths whose
112/// parent exists resolve through the parent + file name.
113fn canonical_skip_set(skip: &[PathBuf]) -> Vec<PathBuf> {
114    skip.iter()
115        .filter_map(|p| {
116            if let Ok(c) = std::fs::canonicalize(p) {
117                return Some(c);
118            }
119            // A bare filename has no directory component; resolve it against
120            // the current directory so it still lands in the skip set.
121            let parent = match p.parent() {
122                Some(parent) if !parent.as_os_str().is_empty() => parent.to_path_buf(),
123                _ => std::path::PathBuf::from("."),
124            };
125            let parent_c = std::fs::canonicalize(parent).ok()?;
126            let name = p.file_name()?;
127            Some(parent_c.join(name))
128        })
129        .collect()
130}
131
132/// True when the walked entry resolves to a skipped path. Entry paths are
133/// rebuilt against the canonical root (no per-entry syscalls — traversal does
134/// not follow symlinks, so the entries are real).
135fn is_skipped(path: &Path, root: &Path, root_canonical: &Path, skip_set: &[PathBuf]) -> bool {
136    let Ok(rel) = path.strip_prefix(root) else {
137        return false;
138    };
139    let candidate = root_canonical.join(rel);
140    skip_set.iter().any(|s| s == &candidate)
141}
142
143/// Entry gate for traversal: keep the root, drop excluded/hidden dirs and
144/// dot-files, drop glob-excluded paths.
145fn keep_entry(e: &DirEntry, cfg: &FilterConfig, root: &Path, ignore: Option<&IgnoreFile>) -> bool {
146    // Always process the explicit root itself; ignore patterns never prune it.
147    if e.depth() == 0 {
148        return true;
149    }
150    // Directory-name / prefix exclusion applies to directories only; files
151    // with excluded-looking names are gated by the extension whitelist.
152    if e.file_type().is_dir() && cfg.is_excluded_dir_name(e.file_name()) {
153        return false;
154    }
155    if cfg.is_hidden_name(e.file_name()) {
156        return false;
157    }
158    if let Some(rules) = ignore {
159        let rel = match e.path().strip_prefix(root) {
160            Ok(r) => r,
161            Err(_) => return true,
162        };
163        let components: Vec<String> = rel
164            .components()
165            .map(|c| c.as_os_str().to_string_lossy().into_owned())
166            .collect();
167        let refs: Vec<&str> = components.iter().map(String::as_str).collect();
168        if rules.ignores(&refs, e.file_type().is_dir()) {
169            return false;
170        }
171    }
172    !is_glob_excluded(e.path(), root, cfg)
173}
174
175/// Glob check against the root-relative path (safety net on top of dir
176/// pruning, and the primary gate for file paths).
177fn is_glob_excluded(path: &Path, root: &Path, cfg: &FilterConfig) -> bool {
178    if cfg.exclude_globs.is_empty() {
179        return false;
180    }
181    let rel = path.strip_prefix(root).unwrap_or(path);
182    let components: Vec<String> = rel
183        .components()
184        .map(|c| c.as_os_str().to_string_lossy().into_owned())
185        .collect();
186    let refs: Vec<&str> = components.iter().map(String::as_str).collect();
187    cfg.is_excluded_by_glob(&refs)
188}
189
190/// `fs::canonicalize` with a fallback that keeps the input untouched.
191fn fs_canonicalize_or(path: &Path, fallback: &Path) -> PathBuf {
192    std::fs::canonicalize(path).unwrap_or_else(|_| fallback.to_path_buf())
193}