Skip to main content

mago_database/
membership.rs

1//! Single-path membership test: would a given file be part of the database
2//! under a [`DatabaseConfiguration`]?
3//!
4//! Source directories, exact paths, and globs retain the loader's source types,
5//! extension rules, and exclusions. Watch roots remain separate from membership.
6
7use std::borrow::Cow;
8use std::ffi::OsStr;
9use std::ffi::OsString;
10use std::path::Path;
11use std::path::PathBuf;
12
13use foldhash::HashSet;
14use globset::GlobSet;
15
16use crate::DatabaseConfiguration;
17use crate::error::DatabaseError;
18use crate::exclusion::Exclusion;
19use crate::file::FileType;
20use crate::loader::resolve_file_type;
21use crate::matcher::build_glob_set;
22use crate::utils::bytes_to_os_str;
23
24mod source;
25
26use source::SourcePattern;
27use source::canonical_path;
28
29/// Resolves whether a single path belongs to the workspace database and, if so,
30/// as which [`FileType`]. Built once from a [`DatabaseConfiguration`]; cheap to
31/// query per path.
32#[derive(Debug, Clone)]
33pub struct WorkspaceMatcher {
34    workspace: PathBuf,
35    extensions: HashSet<OsString>,
36    glob_excludes: GlobSet,
37    path_excludes: Vec<PathBuf>,
38    host_sources: Vec<SourcePattern>,
39    include_sources: Vec<SourcePattern>,
40    patch_sources: Vec<SourcePattern>,
41}
42
43impl WorkspaceMatcher {
44    /// Builds a matcher from a database configuration.
45    ///
46    /// # Errors
47    ///
48    /// Returns a [`DatabaseError`] if a source or exclude glob fails to compile.
49    pub fn from_configuration(configuration: &DatabaseConfiguration<'_>) -> Result<Self, DatabaseError> {
50        let workspace = configuration.workspace.as_ref();
51        let workspace = canonical_path(workspace);
52
53        let extensions: HashSet<OsString> = if configuration.extensions.is_empty() {
54            std::iter::once(OsString::from("php")).collect()
55        } else {
56            configuration.extensions.iter().map(|s| bytes_to_os_str(s.as_ref()).into_owned()).collect()
57        };
58
59        let glob_patterns: Vec<&str> = configuration
60            .excludes
61            .iter()
62            .filter_map(|ex| match ex {
63                Exclusion::Pattern(pattern) => Some(pattern.as_ref()),
64                Exclusion::Path(_) => None,
65            })
66            .collect();
67
68        let glob_excludes = build_glob_set(glob_patterns.iter().copied(), configuration.glob)?;
69        let path_excludes: Vec<PathBuf> = configuration
70            .excludes
71            .iter()
72            .filter_map(|ex| match ex {
73                Exclusion::Path(path) => {
74                    let path =
75                        if path.is_absolute() { path.as_ref().to_path_buf() } else { workspace.join(path.as_ref()) };
76                    Some(canonical_path(&path))
77                }
78                Exclusion::Pattern(_) => None,
79            })
80            .collect();
81
82        let make_sources = |patterns: &[Cow<'_, [u8]>]| -> Result<Vec<SourcePattern>, DatabaseError> {
83            patterns.iter().map(|pattern| SourcePattern::new(&workspace, pattern)).collect()
84        };
85
86        let host_sources = if configuration.paths.is_empty() {
87            vec![SourcePattern::new(&workspace, workspace.to_string_lossy().as_bytes())?]
88        } else {
89            make_sources(&configuration.paths)?
90        };
91
92        let include_sources = make_sources(&configuration.includes)?;
93        let patch_sources = make_sources(&configuration.patches)?;
94
95        Ok(Self { workspace, extensions, glob_excludes, path_excludes, host_sources, include_sources, patch_sources })
96    }
97
98    /// Returns the [`FileType`] for `file` if it would be part of the database,
99    /// or `None` if the path lies outside every configured root or is excluded.
100    #[must_use]
101    pub fn classify(&self, file: &Path) -> Option<FileType> {
102        let canonical = canonical_path(file);
103
104        let specificity = |sources: &[SourcePattern]| {
105            let extension_ok = file.extension().is_some_and(|extension| self.extensions.contains(extension));
106            let canonical_extension_ok =
107                canonical.extension().is_some_and(|extension| self.extensions.contains(extension));
108
109            let lexical = (!file.components().any(|part| part == std::path::Component::ParentDir))
110                .then(|| max_specificity(sources, file, extension_ok))
111                .flatten();
112
113            lexical.max(max_specificity(sources, &canonical, canonical_extension_ok))
114        };
115
116        let host = specificity(&self.host_sources);
117        let include = specificity(&self.include_sources);
118        let patch = specificity(&self.patch_sources);
119        if host.is_none() && include.is_none() && patch.is_none() {
120            return None;
121        }
122
123        if self.is_excluded(file) || self.is_excluded(&canonical) {
124            return None;
125        }
126
127        Some(resolve_file_type(host, include, patch))
128    }
129
130    /// Returns `true` if `path` would be part of the database.
131    #[must_use]
132    pub fn contains(&self, path: &Path) -> bool {
133        self.classify(path).is_some()
134    }
135
136    /// Roots for filesystem watchers, filtered by exclusions rather than file membership.
137    pub fn watch_roots(&self) -> impl Iterator<Item = &Path> {
138        self.host_sources
139            .iter()
140            .chain(&self.include_sources)
141            .chain(&self.patch_sources)
142            .map(|source| source.root.as_path())
143            .filter(|root| !self.is_excluded(root))
144    }
145
146    /// Whether a directory can contain files from any configured source.
147    #[must_use]
148    pub fn can_contain_files(&self, directory: &Path) -> bool {
149        let canonical = canonical_path(directory);
150        !self.is_excluded(directory)
151            && !self.is_excluded(&canonical)
152            && self.watch_roots().any(|root| {
153                directory.starts_with(root)
154                    || root.starts_with(directory)
155                    || canonical.starts_with(root)
156                    || root.starts_with(&canonical)
157            })
158    }
159
160    /// File extensions accepted below the configured roots.
161    pub fn extensions(&self) -> impl Iterator<Item = &OsStr> {
162        self.extensions.iter().map(OsString::as_os_str)
163    }
164
165    /// Check an absolute source path against the configured exclusions.
166    #[must_use]
167    pub fn is_excluded(&self, canonical: &Path) -> bool {
168        if !self.glob_excludes.is_empty() {
169            if self.glob_excludes.is_match(canonical) {
170                return true;
171            }
172
173            if let Ok(relative) = canonical.strip_prefix(&self.workspace)
174                && self.glob_excludes.is_match(relative)
175            {
176                return true;
177            }
178        }
179
180        self.path_excludes.iter().any(|excluded| canonical.starts_with(excluded))
181    }
182}
183
184fn max_specificity(sources: &[SourcePattern], path: &Path, extension_ok: bool) -> Option<usize> {
185    sources.iter().filter(|source| source.matches(path, extension_ok)).map(|source| source.specificity).max()
186}
187
188#[cfg(test)]
189#[path = "membership/tests.rs"]
190mod parity_tests;
191
192#[cfg(test)]
193#[allow(clippy::unwrap_used)]
194mod tests {
195    use std::borrow::Cow;
196
197    use tempfile::TempDir;
198
199    use crate::GlobSettings;
200
201    use super::*;
202
203    fn touch(dir: &TempDir, relative: &str) {
204        let path = dir.path().join(relative);
205        if let Some(parent) = path.parent() {
206            std::fs::create_dir_all(parent).unwrap();
207        }
208        std::fs::write(path, "<?php\n").unwrap();
209    }
210
211    fn config(
212        dir: &TempDir,
213        paths: &[&str],
214        includes: &[&str],
215        excludes: Vec<Exclusion<'static>>,
216    ) -> DatabaseConfiguration<'static> {
217        DatabaseConfiguration {
218            workspace: Cow::Owned(dir.path().to_path_buf()),
219            paths: paths.iter().map(|s| Cow::Owned(s.as_bytes().to_vec())).collect(),
220            includes: includes.iter().map(|s| Cow::Owned(s.as_bytes().to_vec())).collect(),
221            patches: Vec::new(),
222            excludes,
223            extensions: vec![Cow::Borrowed(b"php")],
224            glob: GlobSettings::default(),
225        }
226    }
227
228    fn matcher(configuration: &DatabaseConfiguration<'_>) -> WorkspaceMatcher {
229        WorkspaceMatcher::from_configuration(configuration).unwrap()
230    }
231
232    #[test]
233    fn file_under_a_configured_path_is_tracked_as_host() {
234        let dir = TempDir::new().unwrap();
235        touch(&dir, "src/Foo.php");
236        let matcher = matcher(&config(&dir, &["src"], &[], vec![]));
237
238        assert_eq!(matcher.classify(&dir.path().join("src/Foo.php")), Some(FileType::Host));
239    }
240
241    #[test]
242    fn file_outside_every_configured_path_is_not_tracked() {
243        let dir = TempDir::new().unwrap();
244        touch(&dir, "src/Foo.php");
245        touch(&dir, "scripts/build.php");
246        let matcher = matcher(&config(&dir, &["src"], &[], vec![]));
247
248        assert_eq!(matcher.classify(&dir.path().join("scripts/build.php")), None);
249    }
250
251    #[test]
252    fn glob_excluded_file_is_not_tracked() {
253        let dir = TempDir::new().unwrap();
254        touch(&dir, "src/Foo.php");
255        touch(&dir, "src/generated/Bar.php");
256        let excludes = vec![Exclusion::Pattern(Cow::Borrowed("src/generated/**"))];
257        let matcher = matcher(&config(&dir, &["src"], &[], excludes));
258
259        assert_eq!(matcher.classify(&dir.path().join("src/Foo.php")), Some(FileType::Host));
260        assert_eq!(matcher.classify(&dir.path().join("src/generated/Bar.php")), None);
261    }
262
263    #[test]
264    fn path_excluded_directory_is_not_tracked() {
265        let dir = TempDir::new().unwrap();
266        touch(&dir, "app/Foo.php");
267        touch(&dir, "app/cache/Bar.php");
268        let excludes = vec![Exclusion::Path(Cow::Owned(dir.path().join("app/cache")))];
269        let matcher = matcher(&config(&dir, &["app"], &[], excludes));
270
271        assert_eq!(matcher.classify(&dir.path().join("app/cache/Bar.php")), None);
272    }
273
274    #[test]
275    fn included_path_is_tracked_as_vendored() {
276        let dir = TempDir::new().unwrap();
277        touch(&dir, "vendor/foo/Lib.php");
278        let matcher = matcher(&config(&dir, &["src"], &["vendor/foo"], vec![]));
279
280        assert_eq!(matcher.classify(&dir.path().join("vendor/foo/Lib.php")), Some(FileType::Vendored));
281    }
282
283    #[test]
284    fn excludes_apply_to_included_paths_too() {
285        // Matches the loader: an `includes` root does not override `excludes`.
286        let dir = TempDir::new().unwrap();
287        touch(&dir, "vendor/foo/Lib.php");
288        let excludes = vec![Exclusion::Pattern(Cow::Borrowed("vendor/**"))];
289        let matcher = matcher(&config(&dir, &["src"], &["vendor/foo"], excludes));
290
291        assert_eq!(matcher.classify(&dir.path().join("vendor/foo/Lib.php")), None);
292    }
293
294    #[test]
295    fn patch_path_is_tracked_as_patch() {
296        let dir = TempDir::new().unwrap();
297        touch(&dir, "stubs/Override.php");
298        let mut configuration = config(&dir, &["src"], &[], vec![]);
299        configuration.patches = vec![Cow::Owned(b"stubs".to_vec())];
300        let matcher = matcher(&configuration);
301
302        assert_eq!(matcher.classify(&dir.path().join("stubs/Override.php")), Some(FileType::Patch));
303    }
304
305    #[test]
306    fn patch_beats_vendored_at_equal_specificity() {
307        // Mirrors the loader's USER_DEFINED > PATCH > BUILT_IN > VENDORED tier order: a file
308        // covered by both `includes` and `patches` at the same specificity resolves to Patch.
309        let dir = TempDir::new().unwrap();
310        touch(&dir, "lib/Lib.php");
311        let mut configuration = config(&dir, &["src"], &["lib"], vec![]);
312        configuration.patches = vec![Cow::Owned(b"lib".to_vec())];
313        let matcher = matcher(&configuration);
314
315        assert_eq!(matcher.classify(&dir.path().join("lib/Lib.php")), Some(FileType::Patch));
316    }
317
318    #[test]
319    fn wrong_extension_is_not_tracked() {
320        let dir = TempDir::new().unwrap();
321        touch(&dir, "src/notes.txt");
322        let matcher = matcher(&config(&dir, &["src"], &[], vec![]));
323
324        assert_eq!(matcher.classify(&dir.path().join("src/notes.txt")), None);
325    }
326
327    #[test]
328    fn empty_paths_track_the_whole_workspace() {
329        let dir = TempDir::new().unwrap();
330        touch(&dir, "anywhere/Foo.php");
331        let matcher = matcher(&config(&dir, &[], &[], vec![]));
332
333        assert_eq!(matcher.classify(&dir.path().join("anywhere/Foo.php")), Some(FileType::Host));
334    }
335}