Skip to main content

mago_database/
matcher.rs

1//! Path exclusion matching with mixed glob + prefix semantics.
2//!
3//! This module provides two reusable helpers used by the rest of the workspace:
4//!
5//! - [`build_glob_set`] compiles a list of glob-pattern strings into a
6//!   [`globset::GlobSet`] using the project's [`GlobSettings`]. The file
7//!   loader ([`crate::loader`]) uses this for `source.excludes` entries that
8//!   are pure glob patterns.
9//! - [`ExclusionMatcher`] layers on top of `build_glob_set`, splitting an
10//!   input list into glob patterns and plain prefixes.
11//!
12//! # Pattern semantics used by [`ExclusionMatcher`]
13//!
14//! Each pattern in the input list is classified as either a **glob pattern**
15//! or a **plain prefix** based on whether it contains any glob metacharacters
16//! (`*`, `?`, `[`, `{`):
17//!
18//! - Glob patterns (e.g. `src/**/*.php`, `tests/fixtures/*`) are compiled via
19//!   the [`globset`] crate using the supplied [`GlobSettings`] and matched
20//!   against the full file path.
21//! - Plain prefixes (e.g. `src`, `tests/fixtures/`) use the pre-existing
22//!   directory-prefix semantics: a pattern `X` matches `X`, `X/anything`, or
23//!   (if the pattern already ends with `/`) any path starting with `X/`.
24//!
25//! This split keeps existing `exclude = ["src/foo"]` configurations working
26//! exactly as before while adding full glob support for anyone who needs it.
27
28use globset::GlobBuilder;
29use globset::GlobSet;
30use globset::GlobSetBuilder;
31
32use crate::GlobSettings;
33use crate::error::DatabaseError;
34
35/// Returns `true` if the string contains any character that would make it a
36/// glob pattern rather than a literal path.
37#[inline]
38#[must_use]
39pub fn contains_glob_metacharacters<T>(pattern: T) -> bool
40where
41    T: AsRef<str>,
42{
43    pattern.as_ref().chars().any(|c| matches!(c, '*' | '?' | '[' | '{'))
44}
45
46/// Compiles a list of glob patterns into a [`GlobSet`] using the given
47/// [`GlobSettings`].
48///
49/// This is the single place in the workspace that applies `GlobSettings` to
50/// `GlobBuilder`; callers should prefer this over rebuilding the same
51/// configuration ad-hoc.
52///
53/// Returns an error if any individual pattern fails to compile.
54pub(crate) fn build_glob_set<I, S>(patterns: I, glob_settings: GlobSettings) -> Result<GlobSet, DatabaseError>
55where
56    I: IntoIterator<Item = S>,
57    S: AsRef<str>,
58{
59    let mut builder = GlobSetBuilder::new();
60    for pattern in patterns {
61        let glob = GlobBuilder::new(pattern.as_ref())
62            .case_insensitive(glob_settings.case_insensitive)
63            .literal_separator(glob_settings.literal_separator)
64            .backslash_escape(glob_settings.backslash_escape)
65            .empty_alternates(glob_settings.empty_alternates)
66            .build()?;
67
68        builder.add(glob);
69    }
70
71    Ok(builder.build()?)
72}
73
74/// The directories that exclusion globs ending in `/*`, `/**`, or `/**/*` prune with
75/// everything below them.
76pub(crate) fn directory_patterns<'pattern>(
77    patterns: impl IntoIterator<Item = &'pattern str>,
78) -> impl Iterator<Item = &'pattern str> {
79    patterns.into_iter().filter_map(|pattern| {
80        let stripped = pattern
81            .strip_suffix("/**/*")
82            .or_else(|| pattern.strip_suffix("/**"))
83            .or_else(|| pattern.strip_suffix("/*"))?;
84        (!stripped.is_empty() && stripped != "*" && stripped != "**").then_some(stripped)
85    })
86}
87
88/// Compiled matcher for a list of exclusion patterns.
89///
90/// Split patterns are stored once at construction time so that per-file
91/// matching is cheap. See the module-level documentation for the exact
92/// semantics.
93#[derive(Debug, Clone)]
94pub struct ExclusionMatcher<S: Clone + AsRef<str>> {
95    globs: GlobSet,
96    prefixes: Vec<S>,
97}
98
99impl<S: Clone + AsRef<str>> ExclusionMatcher<S> {
100    /// Builds a matcher from a list of patterns and the project's glob
101    /// settings.
102    ///
103    /// # Errors
104    ///
105    /// Returns a [`DatabaseError::InvalidGlobSet`] if any glob pattern fails to compile.
106    #[inline]
107    pub fn compile<I>(patterns: I, glob_settings: GlobSettings) -> Result<Self, DatabaseError>
108    where
109        I: IntoIterator<Item = S>,
110    {
111        let mut globs = Vec::new();
112        let mut prefixes = Vec::new();
113
114        for pattern in patterns {
115            if contains_glob_metacharacters(&pattern) {
116                globs.push(pattern);
117            } else {
118                prefixes.push(pattern);
119            }
120        }
121
122        Ok(Self { globs: build_glob_set(&globs, glob_settings)?, prefixes })
123    }
124
125    /// Returns `true` if there are no patterns at all.
126    #[inline]
127    #[must_use]
128    pub fn is_empty(&self) -> bool {
129        self.globs.is_empty() && self.prefixes.is_empty()
130    }
131
132    /// Returns `true` if `file` matches any of the configured patterns.
133    ///
134    /// `file` is expected to be a forward-slash-separated path string
135    /// relative to whatever root the caller considers meaningful (typically
136    /// the workspace root for source excludes, or the logical
137    /// `File::name` for per-rule excludes).
138    #[inline]
139    #[must_use]
140    pub fn is_match(&self, file: &str) -> bool {
141        if !self.globs.is_empty() && self.globs.is_match(file) {
142            return true;
143        }
144
145        self.prefixes.iter().any(|pattern| prefix_matches(file, pattern.as_ref()))
146    }
147}
148
149/// Checks whether `file` is covered by the plain-prefix pattern `pattern`.
150///
151/// - A pattern ending in `/` must be a path prefix of `file`.
152/// - Otherwise the pattern must equal `file` or be a proper directory prefix
153///   of it (i.e. `file` starts with `pattern` followed by `/`).
154fn prefix_matches(file: &str, pattern: &str) -> bool {
155    if pattern.ends_with('/') {
156        return file.starts_with(pattern);
157    }
158
159    if file == pattern {
160        return true;
161    }
162
163    let rest = file.strip_prefix(pattern);
164    matches!(rest, Some(rest) if rest.starts_with('/'))
165}
166
167#[cfg(test)]
168#[allow(clippy::expect_used)]
169mod tests {
170    use super::*;
171
172    fn matcher<'pat>(patterns: &[&'pat str]) -> ExclusionMatcher<&'pat str> {
173        ExclusionMatcher::compile(patterns.iter().copied(), GlobSettings::default()).expect("compile")
174    }
175
176    #[test]
177    fn empty_matcher_matches_nothing() {
178        let m = matcher(&[]);
179        assert!(m.is_empty());
180        assert!(!m.is_match("any/path.php"));
181    }
182
183    #[test]
184    fn plain_directory_prefix_matches_descendants() {
185        let m = matcher(&["src/vendor"]);
186        assert!(m.is_match("src/vendor"));
187        assert!(m.is_match("src/vendor/foo.php"));
188        assert!(m.is_match("src/vendor/deep/nested.php"));
189        assert!(!m.is_match("src/vendored.php"));
190        assert!(!m.is_match("src/other.php"));
191    }
192
193    #[test]
194    fn plain_trailing_slash_prefix_is_respected() {
195        let m = matcher(&["src/tests/"]);
196        assert!(m.is_match("src/tests/foo.php"));
197        assert!(!m.is_match("src/tests"));
198    }
199
200    #[test]
201    fn plain_file_matches_exactly() {
202        let m = matcher(&["src/skip.php"]);
203        assert!(m.is_match("src/skip.php"));
204        assert!(!m.is_match("src/skipped.php"));
205    }
206
207    #[test]
208    fn glob_double_star_matches_nested() {
209        let m = matcher(&["src/**/*.php"]);
210        assert!(m.is_match("src/a.php"));
211        assert!(m.is_match("src/dir/a.php"));
212        assert!(m.is_match("src/a/b/c.php"));
213        assert!(!m.is_match("tests/a.php"));
214    }
215
216    #[test]
217    fn glob_star_matches_flat_and_nested() {
218        let m = matcher(&["tests/fixtures/*"]);
219        assert!(m.is_match("tests/fixtures/a.php"));
220        assert!(m.is_match("tests/fixtures/dir/a.php"));
221    }
222
223    #[test]
224    fn mixed_patterns_combine_correctly() {
225        let m = matcher(&["src/legacy", "tests/**/*Test.php"]);
226        assert!(m.is_match("src/legacy/foo.php"));
227        assert!(m.is_match("tests/Unit/FooTest.php"));
228        assert!(!m.is_match("src/modern/foo.php"));
229        assert!(!m.is_match("tests/Unit/Helper.php"));
230    }
231
232    #[test]
233    fn contains_glob_metacharacters_detects_patterns() {
234        assert!(contains_glob_metacharacters("src/**/*.php"));
235        assert!(contains_glob_metacharacters("a?.php"));
236        assert!(contains_glob_metacharacters("[abc]"));
237        assert!(contains_glob_metacharacters("{a,b}"));
238        assert!(!contains_glob_metacharacters("src"));
239        assert!(!contains_glob_metacharacters("src/foo.php"));
240        assert!(!contains_glob_metacharacters("vendor/"));
241    }
242}