1use std::collections::BTreeSet;
22use std::fs;
23use std::path::{Path, PathBuf};
24
25use serde::Deserialize;
26
27use crate::error::IndexError;
28
29pub const CONFIG_FILE: &str = ".malt.toml";
31
32#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
34#[serde(default, deny_unknown_fields)]
35pub struct PathConfig {
36 pub enabled: bool,
39 pub paths: Vec<String>,
42}
43
44#[derive(Deserialize, Default)]
46struct ConfigFile {
47 #[serde(default)]
48 index: PathConfig,
49}
50
51fn parse(content: &str) -> Result<PathConfig, toml::de::Error> {
52 Ok(toml::from_str::<ConfigFile>(content)?.index)
53}
54
55impl PathConfig {
56 pub fn from_toml(content: &str) -> Result<Self, IndexError> {
58 parse(content).map_err(|err| IndexError::Config(err.to_string()))
59 }
60
61 pub fn load(dir: &Path) -> Result<Self, IndexError> {
63 let path = dir.join(CONFIG_FILE);
64 match fs::read_to_string(&path) {
65 Ok(content) => parse(&content)
66 .map_err(|err| IndexError::Config(format!("{}: {err}", path.display()))),
67 Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
68 Err(err) => Err(IndexError::io(&path, &err)),
69 }
70 }
71}
72
73pub fn resolve_paths(
77 config: &PathConfig,
78 cwd: &Path,
79 file: Option<&Path>,
80 extra_dirs: &[PathBuf],
81) -> (Vec<PathBuf>, Vec<String>) {
82 let mut found = Found::default();
83 let mut warnings = Vec::new();
84
85 if let Some(parent) = file.and_then(Path::parent) {
86 let folder = cwd.join(parent);
87 if folder.is_dir() {
88 found.push(&folder);
89 } else {
90 warnings.push(format!(
91 "{}: folder of the linted file not found",
92 folder.display()
93 ));
94 }
95 }
96 for dir in extra_dirs {
97 let folder = cwd.join(dir);
98 if folder.is_dir() {
99 found.push(&folder);
100 } else {
101 warnings.push(format!("{}: extra folder not found", folder.display()));
102 }
103 }
104
105 if config.paths.is_empty() {
106 if cwd.is_dir() {
107 found.push(cwd);
108 } else {
109 warnings.push(format!("{}: working directory not found", cwd.display()));
110 }
111 } else {
112 let mut configured = BTreeSet::new();
113 for pattern in &config.paths {
114 expand(pattern, cwd, &mut configured, &mut warnings);
115 }
116 for dir in &configured {
117 found.push(dir);
118 }
119 }
120
121 (found.dirs, warnings)
122}
123
124#[derive(Default)]
126struct Found {
127 seen: BTreeSet<PathBuf>,
128 dirs: Vec<PathBuf>,
129}
130
131impl Found {
132 fn push(&mut self, dir: &Path) {
133 let canon = canonical(dir);
134 if self.seen.insert(canon.clone()) {
135 self.dirs.push(canon);
136 }
137 }
138}
139
140fn expand(pattern: &str, cwd: &Path, out: &mut BTreeSet<PathBuf>, warnings: &mut Vec<String>) {
142 let raw = pattern.trim();
143 if raw.is_empty() {
144 warnings.push("empty entry in [index] paths ignored".to_string());
145 return;
146 }
147 let (recursive, base) = if raw == "**" {
148 (true, "")
149 } else if let Some(base) = raw.strip_suffix("/**") {
150 (true, base)
151 } else {
152 (false, raw)
153 };
154
155 let start = if Path::new(base).has_root() {
156 PathBuf::from("/")
157 } else {
158 cwd.to_path_buf()
159 };
160 let segments: Vec<&str> = base
161 .split('/')
162 .filter(|s| !s.is_empty() && *s != ".")
163 .collect();
164 let is_glob = base.contains(['*', '?', '[']);
165
166 let mut matches = Vec::new();
167 match_segments(&start, &segments, &mut matches);
168 if matches.is_empty() {
169 warnings.push(format!("{raw}: matches no folder"));
170 return;
171 }
172 for dir in matches {
173 let plain = segments.is_empty() || is_plain_name(&name_of(&dir));
174 if !plain {
175 if !is_glob {
176 warnings.push(format!(
177 "{raw}: package, class and private folders are not on the path"
178 ));
179 }
180 continue;
181 }
182 if recursive {
183 genpath(&dir, out);
184 } else {
185 out.insert(canonical(&dir));
186 }
187 }
188}
189
190fn match_segments(dir: &Path, segments: &[&str], out: &mut Vec<PathBuf>) {
194 let Some((first, rest)) = segments.split_first() else {
195 out.push(dir.to_path_buf());
196 return;
197 };
198 if *first == "**" {
199 match_segments(dir, rest, out);
200 for sub in plain_subdirs(dir) {
201 match_segments(&sub, segments, out);
202 }
203 } else if is_glob(first) {
204 let Ok(entries) = fs::read_dir(dir) else {
205 return;
206 };
207 for entry in entries.flatten() {
208 let name = entry.file_name().to_string_lossy().into_owned();
209 if name.starts_with('.') && !first.starts_with('.') {
210 continue;
211 }
212 let pattern: Vec<char> = first.chars().collect();
213 let name_chars: Vec<char> = name.chars().collect();
214 if glob_match(&pattern, &name_chars) && entry.path().is_dir() {
215 match_segments(&entry.path(), rest, out);
216 }
217 }
218 } else {
219 let next = dir.join(first);
220 if next.is_dir() {
221 match_segments(&next, rest, out);
222 }
223 }
224}
225
226fn genpath(dir: &Path, out: &mut BTreeSet<PathBuf>) {
228 out.insert(canonical(dir));
229 for sub in plain_subdirs(dir) {
230 genpath(&sub, out);
231 }
232}
233
234fn plain_subdirs(dir: &Path) -> Vec<PathBuf> {
237 let Ok(entries) = fs::read_dir(dir) else {
238 return Vec::new();
239 };
240 let mut subs: Vec<PathBuf> = entries
241 .flatten()
242 .filter(|entry| entry.file_type().is_ok_and(|t| t.is_dir()))
243 .map(|entry| entry.path())
244 .filter(|path| is_plain_name(&name_of(path)))
245 .collect();
246 subs.sort();
247 subs
248}
249
250fn is_plain_name(name: &str) -> bool {
253 !(name.starts_with(['.', '+', '@']) || name == "private")
254}
255
256fn is_glob(segment: &str) -> bool {
257 segment.contains(['*', '?', '['])
258}
259
260fn name_of(path: &Path) -> String {
261 path.file_name()
262 .map(|name| name.to_string_lossy().into_owned())
263 .unwrap_or_default()
264}
265
266fn canonical(path: &Path) -> PathBuf {
267 crate::fsutil::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
268}
269
270fn glob_match(pattern: &[char], name: &[char]) -> bool {
273 match pattern.split_first() {
274 None => name.is_empty(),
275 Some((&'*', rest)) => (0..=name.len()).any(|skip| glob_match(rest, &name[skip..])),
276 Some((&'?', rest)) => name
277 .split_first()
278 .is_some_and(|(_, tail)| glob_match(rest, tail)),
279 Some((&'[', rest)) => {
280 let Some((&c, tail)) = name.split_first() else {
281 return false;
282 };
283 match rest.iter().position(|&p| p == ']') {
284 Some(end) => class_matches(&rest[..end], c) && glob_match(&rest[end + 1..], tail),
285 None => c == '[' && glob_match(rest, tail),
286 }
287 }
288 Some((&literal, rest)) => name
289 .split_first()
290 .is_some_and(|(&c, tail)| c == literal && glob_match(rest, tail)),
291 }
292}
293
294fn class_matches(set: &[char], c: char) -> bool {
296 let (negated, set) = match set.first() {
297 Some('!' | '^') => (true, &set[1..]),
298 _ => (false, set),
299 };
300 let mut hit = false;
301 let mut i = 0;
302 while i < set.len() {
303 if i + 2 < set.len() && set[i + 1] == '-' {
304 hit |= (set[i]..=set[i + 2]).contains(&c);
305 i += 3;
306 } else {
307 hit |= set[i] == c;
308 i += 1;
309 }
310 }
311 hit != negated
312}