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