Skip to main content

malt_index/
paths.rs

1//! The folders on the search path: `[index] paths` in the working directory's
2//! `.malt.toml`, the folder of the linted file, and extra folders.
3//!
4//! Without `paths` the search path is the working directory. With `paths`, the listed
5//! folders replace the working directory (list `"."` to keep it as well). The folder of
6//! the linted file and the extra folders are always added, first, as MATLAB searches the
7//! current folder before the path.
8//!
9//! Pattern rules (genpath's, as MATLAB reads them):
10//! - `lib/**` adds `lib` and every plain subfolder of it, recursively. `+pkg`, `@cls`,
11//!   `private` and hidden folders are never added, and nothing below them is.
12//! - Any other pattern (`lib`, `src/*`, `lib?`, `[ab]x`) adds the matching folders only,
13//!   not recursively. `*`, `?` and `[...]` match within one path segment; `**` in the
14//!   middle of a pattern matches any number of folder levels.
15//! - Relative patterns resolve against the working directory. Recursion does not follow
16//!   symbolic links (it cannot loop); a link named by a pattern is followed.
17//!
18//! The result is deduplicated. Its order is the search order: the file's folder, the
19//! extra folders in the order given, then the configured folders sorted by path.
20
21use std::collections::BTreeSet;
22use std::fs;
23use std::path::{Path, PathBuf};
24
25use serde::Deserialize;
26
27use crate::error::IndexError;
28
29/// The configuration file read from the working directory.
30pub const CONFIG_FILE: &str = ".malt.toml";
31
32/// The `[index]` table of `.malt.toml`.
33#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
34#[serde(default, deny_unknown_fields)]
35pub struct PathConfig {
36    /// Whether the linter uses the index (default: no). The index only adds
37    /// findings that MATLAB's Code Analyzer does not make; this crate ignores it.
38    pub enabled: bool,
39    /// Folders to search: plain folders or glob patterns (see the module docs).
40    /// Empty means the working directory alone.
41    pub paths: Vec<String>,
42}
43
44/// The parts of `.malt.toml` that this module reads. Other tables are ignored.
45#[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    /// Parse the `[index]` table of a `.malt.toml`'s content. Other tables are ignored.
57    pub fn from_toml(content: &str) -> Result<Self, IndexError> {
58        parse(content).map_err(|err| IndexError::Config(err.to_string()))
59    }
60
61    /// Read `dir/.malt.toml`. A missing file is the empty configuration.
62    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
73/// The folders to search, in search order, and the warnings about what was skipped:
74/// missing folders, patterns that match nothing, and package, class and `private`
75/// folders named explicitly. Never panics; a folder that cannot be read is skipped.
76pub 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/// The folders found so far, deduplicated by their canonical path, in the order added.
125#[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
140/// Add the folders one `[index] paths` entry names to `out`.
141fn 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
190/// Every folder that the segments name under `dir`. `**` matches zero or more levels;
191/// a segment with `*`, `?` or `[` matches names within the folder (hidden names only
192/// when the segment starts with a dot).
193fn 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
226/// `dir` and every plain subfolder of it, recursively (genpath's rule).
227fn 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
234/// The subfolders of `dir` that can be on the path, sorted. Symbolic links are not
235/// followed, so recursion ends.
236fn 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
250/// Whether a folder of this name can be on the path: not a package (`+`), a class
251/// folder (`@`), `private` or hidden.
252fn 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
270/// Match one name against a segment pattern: `*` (any run), `?` (one character) and
271/// `[...]` (a set, with a range `a-z`, negated by a leading `!` or `^`).
272fn 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
294/// Whether `c` is in a `[...]` set (the characters between the brackets).
295fn 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}