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 let parent = p.parent()?;
110 let parent_c = std::fs::canonicalize(parent).ok()?;
111 let name = p.file_name()?;
112 Some(parent_c.join(name))
113 })
114 .collect()
115}
116
117/// True when the walked entry resolves to a skipped path. Entry paths are
118/// rebuilt against the canonical root (no per-entry syscalls — traversal does
119/// not follow symlinks, so the entries are real).
120fn is_skipped(path: &Path, root: &Path, root_canonical: &Path, skip_set: &[PathBuf]) -> bool {
121 let Ok(rel) = path.strip_prefix(root) else {
122 return false;
123 };
124 let candidate = root_canonical.join(rel);
125 skip_set.iter().any(|s| s == &candidate)
126}
127
128/// Entry gate for traversal: keep the root, drop excluded/hidden dirs and
129/// dot-files, drop glob-excluded paths.
130fn keep_entry(e: &DirEntry, cfg: &FilterConfig, root: &Path, ignore: Option<&IgnoreFile>) -> bool {
131 // Always process the explicit root itself; ignore patterns never prune it.
132 if e.depth() == 0 {
133 return true;
134 }
135 // Directory-name / prefix exclusion applies to directories only; files
136 // with excluded-looking names are gated by the extension whitelist.
137 if e.file_type().is_dir() && cfg.is_excluded_dir_name(e.file_name()) {
138 return false;
139 }
140 if cfg.is_hidden_name(e.file_name()) {
141 return false;
142 }
143 if let Some(rules) = ignore {
144 let rel = match e.path().strip_prefix(root) {
145 Ok(r) => r,
146 Err(_) => return true,
147 };
148 let components: Vec<String> = rel
149 .components()
150 .map(|c| c.as_os_str().to_string_lossy().into_owned())
151 .collect();
152 let refs: Vec<&str> = components.iter().map(String::as_str).collect();
153 if rules.ignores(&refs, e.file_type().is_dir()) {
154 return false;
155 }
156 }
157 !is_glob_excluded(e.path(), root, cfg)
158}
159
160/// Glob check against the root-relative path (safety net on top of dir
161/// pruning, and the primary gate for file paths).
162fn is_glob_excluded(path: &Path, root: &Path, cfg: &FilterConfig) -> bool {
163 if cfg.exclude_globs.is_empty() {
164 return false;
165 }
166 let rel = path.strip_prefix(root).unwrap_or(path);
167 let components: Vec<String> = rel
168 .components()
169 .map(|c| c.as_os_str().to_string_lossy().into_owned())
170 .collect();
171 let refs: Vec<&str> = components.iter().map(String::as_str).collect();
172 cfg.is_excluded_by_glob(&refs)
173}
174
175/// `fs::canonicalize` with a fallback that keeps the input untouched.
176fn fs_canonicalize_or(path: &Path, fallback: &Path) -> PathBuf {
177 std::fs::canonicalize(path).unwrap_or_else(|_| fallback.to_path_buf())
178}