drep/files/mod.rs
1//! The only file-target policy.
2//!
3//! Every code path in drep that decides which files to look at goes through
4//! these predicates, so a Python file is a file is a file regardless of whether
5//! it was discovered by a full scan, the staged-files index, or a
6//! `--diff <ref>` query. Markdown has its own predicate and its own command:
7//! see `is_scan_target` for why the two file classes are disjoint.
8//!
9//! Walking is the `ignore` crate rather than `std::fs::read_dir` so a project's
10//! gitignore is honoured without a second pass, and vendored directories are
11//! pruned during the walk (rather than collected-then-filtered, which would
12//! `stat` every entry under `node_modules/` before discarding them).
13//!
14//! Discovery of explicit filenames (`drep check a.rs .`) deliberately ignores
15//! gitignore: the user naming a path is a stronger signal than a repo-wide
16//! pattern. `expand_paths` enforces that; `walk_targets` enforces the inverse.
17
18use std::collections::{BTreeMap, BTreeSet};
19use std::path::{Path, PathBuf};
20
21use ignore::{DirEntry, WalkBuilder};
22
23use crate::languages;
24
25/// Any registered language's source file - the file class `drep check` reads.
26///
27/// Markdown is **not** here, and that is the point. Each command owns one file
28/// class: `check` reads code through this predicate, while `lint-docs` reads
29/// markdown through [`is_markdown`]. A path the user names that falls outside
30/// the running command's class is a
31/// [`crate::analysis::result::FailureReason::Unsupported`] pointing at the
32/// other command - never a silent skip.
33pub fn is_scan_target(path: &Path) -> bool {
34 languages::detect(path).is_some()
35}
36
37/// Markdown document.
38pub fn is_markdown(path: &Path) -> bool {
39 path.extension()
40 .is_some_and(|extension| extension.eq_ignore_ascii_case("md"))
41}
42
43/// Hardcoded ignored dirs that belong to no single language: VCS metadata,
44/// build output, caches.
45const SHARED_IGNORED_DIRS: &[&str] = &[".git", "build", "dist", ".cache"];
46
47/// A directory that should never be descended into.
48///
49/// Case-insensitive on purpose: a directory called `VENV` and one called `venv`
50/// are the same on a case-insensitive filesystem, and matching only one of
51/// them would walk it anyway — defeating the whole point of having the list.
52pub fn is_ignored_dir(name: &str) -> bool {
53 let folded = name.to_ascii_lowercase();
54 if folded.ends_with(".egg-info") {
55 return true;
56 }
57 if SHARED_IGNORED_DIRS.iter().any(|d| *d == folded) {
58 return true;
59 }
60 crate::languages::vendored_dirs()
61 .iter()
62 .any(|d| d.eq_ignore_ascii_case(name))
63}
64
65/// Walk `root` and collect every regular file matching `predicate`.
66///
67/// Pruning happens **during** the walk via `ignore`'s `filter_entry`, so
68/// ignoring `node_modules/` does not mean stat-ing every entry under it first
69/// — the failure mode that `rglob` falls into on a real repo. Honors
70/// per-directory `.gitignore`, which is the difference between a walk that
71/// respects a project's policy and one that simply skips a directory named
72/// `build`.
73pub fn walk_targets(root: &Path, predicate: fn(&Path) -> bool) -> Vec<PathBuf> {
74 let walker = WalkBuilder::new(root)
75 .hidden(false)
76 .git_ignore(true)
77 .git_global(false)
78 .git_exclude(true)
79 .require_git(false)
80 .sort_by_file_name(|a, b| a.cmp(b))
81 .filter_entry(|entry: &DirEntry| {
82 if entry.depth() == 0 {
83 return true;
84 }
85 if entry.file_type().is_some_and(|ft| ft.is_dir())
86 && is_ignored_dir(&entry.file_name().to_string_lossy())
87 {
88 return false;
89 }
90 true
91 })
92 .build();
93
94 let mut found = Vec::new();
95 for result in walker {
96 let Ok(entry) = result else { continue };
97 if entry.file_type().is_some_and(|ft| ft.is_file()) {
98 let path = entry.path();
99 if predicate(path) {
100 found.push(path.to_path_buf());
101 }
102 }
103 }
104 found
105}
106
107/// Expand a list of explicit paths (files and/or directories) into a sorted,
108/// deduplicated set of files matching `predicate`.
109///
110/// Explicit files bypass gitignore. Missing and unsupported paths are skipped;
111/// callers needing those rejections use [`expand_named`]. Empty input is empty.
112pub fn expand_paths(paths: &[PathBuf], predicate: fn(&Path) -> bool) -> Vec<PathBuf> {
113 expand(paths, predicate).targets
114}
115
116/// Why an explicitly named path produced no target.
117///
118/// Only *named* paths are ever rejected. A directory walk that yields nothing
119/// is legitimately empty: `drep check .` in a documentation repository has
120/// correctly found no code. A path the user typed is the opposite case, and
121/// reporting "No issues found." for it is the single failure this codebase is
122/// built to prevent.
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub enum Rejected {
125 /// Nothing exists at that path.
126 Missing,
127 /// Something exists there, but this command cannot analyze it: the
128 /// predicate declined the file type, or the path is neither a regular file
129 /// nor a directory (a fifo, a socket, `/dev/stdin`).
130 Unanalyzable,
131}
132
133/// The result of resolving a command's path arguments.
134pub struct Expansion {
135 /// Files to analyze, sorted and deduplicated.
136 pub targets: Vec<PathBuf>,
137 /// Named paths that produced nothing, and why.
138 pub rejected: BTreeMap<PathBuf, Rejected>,
139}
140
141/// Resolve a command's path arguments against `root`.
142///
143/// Classify each explicit path once, collecting both targets and rejections.
144/// No arguments expands `root` without treating it as an explicitly named path.
145pub fn expand_named(paths: &[PathBuf], root: &Path, predicate: fn(&Path) -> bool) -> Expansion {
146 if paths.is_empty() {
147 return Expansion {
148 targets: expand_paths(&[root.to_path_buf()], predicate),
149 rejected: BTreeMap::new(),
150 };
151 }
152 expand(paths, predicate)
153}
154
155fn expand(paths: &[PathBuf], predicate: fn(&Path) -> bool) -> Expansion {
156 let mut targets = BTreeSet::new();
157 let mut rejected = BTreeMap::new();
158 for named in paths {
159 let verdict = match std::fs::metadata(named) {
160 Err(_) => Some(Rejected::Missing),
161 Ok(meta) if meta.is_dir() => {
162 targets.extend(walk_targets(named, predicate));
163 None
164 }
165 Ok(meta) if meta.is_file() && predicate(named) => {
166 targets.insert(named.clone());
167 None
168 }
169 Ok(_) => Some(Rejected::Unanalyzable),
170 };
171 if let Some(verdict) = verdict {
172 rejected.insert(named.clone(), verdict);
173 }
174 }
175 Expansion {
176 targets: targets.into_iter().collect(),
177 rejected,
178 }
179}
180
181/// The subcommand that does analyze `path`, if any.
182///
183/// One table, consulted from both directions. Each command previously
184/// hardcoded a pointer at the other - `check` asked `is_markdown`, `lint-docs`
185/// asked `languages::detect` - which is two definitions of one question and an
186/// edit in every existing command each time a file class is added.
187pub fn owning_command(path: &Path) -> Option<&'static str> {
188 if is_scan_target(path) {
189 Some("check")
190 } else if is_markdown(path) {
191 Some("lint-docs")
192 } else {
193 None
194 }
195}
196
197/// What to tell a user who named `path` at the wrong command.
198///
199/// `None` when no command claims the type, because drep genuinely has nothing
200/// to say about a `.png` and inventing a suggestion would be worse than
201/// admitting that.
202pub fn redirect_hint(path: &Path) -> Option<String> {
203 owning_command(path).map(|command| format!("run `drep {command}` instead"))
204}
205
206#[cfg(test)]
207mod tests;