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;
12use std::sync::Arc;
13
14use foldhash::HashSet;
15use globset::GlobSet;
16
17use crate::DatabaseConfiguration;
18use crate::GlobSettings;
19use crate::error::DatabaseError;
20use crate::exclusion::Exclusion;
21use crate::file::File;
22use crate::file::FileType;
23use crate::git::GitIgnores;
24use crate::loader::resolve_file_type;
25use crate::matcher::build_glob_set;
26use crate::matcher::directory_patterns;
27use crate::utils::bytes_to_os_str;
28use crate::utils::bytes_to_path;
29
30mod source;
31
32use source::SourcePattern;
33use source::canonical_path;
34
35/// Resolves whether a single path belongs to the workspace database and, if so,
36/// as which [`FileType`]. Built once from a [`DatabaseConfiguration`]; cheap to
37/// query per path.
38#[derive(Debug, Clone)]
39pub struct WorkspaceMatcher {
40    extensions: HashSet<OsString>,
41    exclusions: PathExclusions,
42    host_sources: Vec<SourcePattern>,
43    include_sources: Vec<SourcePattern>,
44    patch_sources: Vec<SourcePattern>,
45    git_ignores: Option<Arc<GitIgnores>>,
46}
47
48impl WorkspaceMatcher {
49    /// Builds a matcher from a database configuration.
50    ///
51    /// # Errors
52    ///
53    /// Returns a [`DatabaseError`] if a source or exclude glob fails to compile.
54    pub fn from_configuration(configuration: &DatabaseConfiguration<'_>) -> Result<Self, DatabaseError> {
55        let workspace = configuration.workspace.as_ref();
56        let workspace = canonical_path(workspace);
57
58        let extensions: HashSet<OsString> = if configuration.extensions.is_empty() {
59            std::iter::once(OsString::from("php")).collect()
60        } else {
61            configuration.extensions.iter().map(|s| bytes_to_os_str(s.as_ref()).into_owned()).collect()
62        };
63
64        let exclusions = PathExclusions::new(&workspace, &configuration.excludes, configuration.glob)?;
65
66        let make_sources = |patterns: &[Cow<'_, [u8]>]| -> Result<Vec<SourcePattern>, DatabaseError> {
67            patterns.iter().map(|pattern| SourcePattern::new(&workspace, pattern)).collect()
68        };
69
70        let host_sources = if configuration.paths.is_empty() {
71            vec![SourcePattern::new(&workspace, workspace.to_string_lossy().as_bytes())?]
72        } else {
73            make_sources(&configuration.paths)?
74        };
75
76        let include_sources = make_sources(&configuration.includes)?;
77        let patch_sources = make_sources(&configuration.patches)?;
78
79        Ok(Self { extensions, exclusions, host_sources, include_sources, patch_sources, git_ignores: None })
80    }
81
82    /// Classify source files that Git ignores as vendored, as the loader does.
83    #[must_use]
84    pub fn with_git_ignores(mut self, ignores: Arc<GitIgnores>) -> Self {
85        self.git_ignores = Some(ignores);
86        self
87    }
88
89    /// Returns the [`FileType`] for `file` if it would be part of the database,
90    /// or `None` if the path lies outside every configured root or is excluded.
91    #[must_use]
92    pub fn classify(&self, file: &Path) -> Option<FileType> {
93        let canonical = canonical_path(file);
94        let lexical = !file.components().any(|part| part == std::path::Component::ParentDir);
95
96        let specificity = |sources: &[SourcePattern]| {
97            let extension_ok = file.extension().is_some_and(|extension| self.extensions.contains(extension));
98            let canonical_extension_ok =
99                canonical.extension().is_some_and(|extension| self.extensions.contains(extension));
100
101            let requested = lexical.then(|| self.max_specificity(sources, file, extension_ok)).flatten();
102
103            requested.max(self.max_specificity(sources, &canonical, canonical_extension_ok))
104        };
105
106        let mut host = specificity(&self.host_sources);
107        let mut include = specificity(&self.include_sources);
108        let patch = specificity(&self.patch_sources);
109        if host.is_none() && include.is_none() && patch.is_none() {
110            return None;
111        }
112
113        if self.is_excluded(file) || self.is_excluded(&canonical) {
114            return None;
115        }
116
117        if host.is_some()
118            && let Some(ignores) = &self.git_ignores
119            && ignores.is_ignored(self.source_path(file, &canonical), false)
120        {
121            include = include.max(host.take());
122        }
123
124        Some(resolve_file_type(host, include, patch))
125    }
126
127    /// The path a file opened as `requested` is kept under: the requested path below a
128    /// source root, which keeps the loader's symlinked directories, or else `resolved`.
129    #[must_use]
130    pub fn source_path<'path>(&self, requested: &'path Path, resolved: &'path Path) -> &'path Path {
131        if !requested.components().any(|part| part == std::path::Component::ParentDir)
132            && self.watch_roots().any(|root| requested.starts_with(root))
133            && self.admits(requested)
134        {
135            requested
136        } else {
137            resolved
138        }
139    }
140
141    /// Whether some source loads `path` itself, before symlinks resolve.
142    fn admits(&self, path: &Path) -> bool {
143        let extension_ok = path.extension().is_some_and(|extension| self.extensions.contains(extension));
144        !self.exclusions.matches(path)
145            && [&self.host_sources, &self.include_sources, &self.patch_sources]
146                .into_iter()
147                .any(|sources| self.max_specificity(sources, path, extension_ok).is_some())
148    }
149
150    /// `exclusions` on top of these sources, matched the way the loader applies a
151    /// command's `excludes` while it walks them.
152    ///
153    /// # Errors
154    ///
155    /// Returns a [`DatabaseError`] if a glob fails to compile.
156    pub fn exclusions(
157        &self,
158        exclusions: &[Exclusion<'_>],
159        glob: GlobSettings,
160    ) -> Result<PathExclusions, DatabaseError> {
161        let mut compiled = PathExclusions::new(&self.exclusions.workspace, exclusions, glob)?;
162        compiled.sources = [self.host_sources.clone(), self.include_sources.clone(), self.patch_sources.clone()];
163        Ok(compiled)
164    }
165
166    fn max_specificity(&self, sources: &[SourcePattern], path: &Path, extension_ok: bool) -> Option<usize> {
167        sources
168            .iter()
169            .filter(|source| source.matches(path, extension_ok) && !self.exclusions.prunes(source, path))
170            .map(|source| source.specificity)
171            .max()
172    }
173
174    /// Returns `true` if `path` would be part of the database.
175    #[must_use]
176    pub fn contains(&self, path: &Path) -> bool {
177        self.classify(path).is_some()
178    }
179
180    /// Roots for filesystem watchers. The loader walks a root unless a path exclusion covers it.
181    pub fn watch_roots(&self) -> impl Iterator<Item = &Path> {
182        self.sources().map(|source| source.root.as_path()).filter(|root| !self.exclusions.covers(root))
183    }
184
185    /// Whether a directory can contain files from any configured source, as the loader walks them.
186    #[must_use]
187    pub fn can_contain_files(&self, directory: &Path) -> bool {
188        let lexical = !directory.components().any(|part| part == std::path::Component::ParentDir);
189        (lexical && self.reaches(directory)) || self.reaches(&canonical_path(directory))
190    }
191
192    fn reaches(&self, directory: &Path) -> bool {
193        !self.exclusions.covers(directory)
194            && self.sources().any(|source| {
195                source.root.starts_with(directory)
196                    || (directory.starts_with(&source.root) && !self.exclusions.prunes_directory(source, directory))
197            })
198    }
199
200    fn sources(&self) -> impl Iterator<Item = &SourcePattern> {
201        self.host_sources.iter().chain(&self.include_sources).chain(&self.patch_sources)
202    }
203
204    /// File extensions accepted below the configured roots.
205    pub fn extensions(&self) -> impl Iterator<Item = &OsStr> {
206        self.extensions.iter().map(OsString::as_os_str)
207    }
208
209    /// Check an absolute source path against the configured exclusions.
210    #[must_use]
211    pub fn is_excluded(&self, canonical: &Path) -> bool {
212        self.exclusions.matches(canonical)
213    }
214
215    /// Whether a path exclusion covers `directory`. File globs never exclude a
216    /// directory: the loader still walks one that a glob names.
217    #[must_use]
218    pub fn excludes_directory(&self, directory: &Path) -> bool {
219        self.exclusions.covers(directory)
220    }
221}
222
223/// Compiled [`Exclusion`]s, matched the way the loader skips files.
224#[derive(Debug, Clone, Default)]
225pub struct PathExclusions {
226    workspace: PathBuf,
227    globs: GlobSet,
228    /// Directories the loader prunes, with everything below them, while it walks a source directory.
229    directories: GlobSet,
230    paths: Vec<PathBuf>,
231    /// The host, include, and patch sources a command's own exclusions apply to.
232    sources: [Vec<SourcePattern>; 3],
233}
234
235impl PathExclusions {
236    fn new(workspace: &Path, exclusions: &[Exclusion<'_>], glob: GlobSettings) -> Result<Self, DatabaseError> {
237        let workspace = canonical_path(workspace);
238        let patterns = || {
239            exclusions.iter().filter_map(|exclusion| match exclusion {
240                Exclusion::Pattern(pattern) => Some(pattern.as_ref()),
241                Exclusion::Path(_) => None,
242            })
243        };
244        let globs = build_glob_set(patterns(), glob)?;
245        let directories = build_glob_set(directory_patterns(patterns()), glob)?;
246        let paths = exclusions
247            .iter()
248            .filter_map(|exclusion| match exclusion {
249                Exclusion::Path(path) => {
250                    Some(canonical_path(&if path.is_absolute() { path.to_path_buf() } else { workspace.join(path) }))
251                }
252                Exclusion::Pattern(_) => None,
253            })
254            .collect();
255
256        Ok(Self { workspace, globs, directories, paths, sources: <[Vec<SourcePattern>; 3]>::default() })
257    }
258
259    #[must_use]
260    pub fn is_empty(&self) -> bool {
261        self.globs.is_empty() && self.paths.is_empty()
262    }
263
264    /// Check a database file by its path, or by its logical name when it has none.
265    #[must_use]
266    pub fn excludes_file(&self, file: &File) -> bool {
267        !self.is_empty()
268            && match &file.path {
269                Some(path) => self.is_excluded(path, file.file_type),
270                None => self.is_excluded(&self.workspace.join(bytes_to_path(&file.name)), file.file_type),
271            }
272    }
273
274    /// Check an absolute source path loaded as `file_type`. A command's own exclusions
275    /// also skip a file when every source that can supply it in that tier prunes a
276    /// directory above it. Vendored files include host files Git ignores.
277    #[must_use]
278    pub fn is_excluded(&self, canonical: &Path, file_type: FileType) -> bool {
279        if self.matches(canonical) {
280            return true;
281        }
282
283        let (first, second): (&[SourcePattern], &[SourcePattern]) = match file_type {
284            FileType::Host => (&self.sources[0], &[]),
285            FileType::Vendored => (&self.sources[0], &self.sources[1]),
286            FileType::Patch => (&self.sources[2], &[]),
287            FileType::Builtin | FileType::External => (&[], &[]),
288        };
289        let mut reaching = first.iter().chain(second).filter(|source| source.matches(canonical, true)).peekable();
290        reaching.peek().is_some() && reaching.all(|source| self.prunes(source, canonical))
291    }
292
293    /// Whether a path exclusion covers `path`.
294    fn covers(&self, path: &Path) -> bool {
295        self.paths.iter().any(|excluded| path.starts_with(excluded))
296    }
297
298    fn matches(&self, canonical: &Path) -> bool {
299        if !self.globs.is_empty() {
300            if self.globs.is_match(canonical) {
301                return true;
302            }
303
304            if let Ok(relative) = canonical.strip_prefix(&self.workspace)
305                && self.globs.is_match(relative)
306            {
307                return true;
308            }
309        }
310
311        self.covers(canonical)
312    }
313
314    /// Whether walking `source` prunes a directory between its root and the file at `path`.
315    fn prunes(&self, source: &SourcePattern, path: &Path) -> bool {
316        path.parent().is_some_and(|directory| self.prunes_directory(source, directory))
317    }
318
319    /// Whether walking `source` prunes `directory` or a directory between it and the root.
320    fn prunes_directory(&self, source: &SourcePattern, directory: &Path) -> bool {
321        source.walks()
322            && !self.directories.is_empty()
323            && directory
324                .ancestors()
325                .take_while(|directory| *directory != source.root && directory.starts_with(&source.root))
326                .any(|directory| {
327                    self.directories.is_match(directory)
328                        || self.directories.is_match(directory.strip_prefix(&self.workspace).unwrap_or(directory))
329                })
330    }
331}
332
333#[cfg(test)]
334#[path = "membership/tests.rs"]
335mod parity_tests;
336
337#[cfg(test)]
338#[allow(clippy::unwrap_used)]
339mod tests {
340    use std::borrow::Cow;
341
342    use tempfile::TempDir;
343
344    use crate::GlobSettings;
345
346    use super::*;
347
348    fn touch(dir: &TempDir, relative: &str) {
349        let path = dir.path().join(relative);
350        if let Some(parent) = path.parent() {
351            std::fs::create_dir_all(parent).unwrap();
352        }
353        std::fs::write(path, "<?php\n").unwrap();
354    }
355
356    fn config(
357        dir: &TempDir,
358        paths: &[&str],
359        includes: &[&str],
360        excludes: Vec<Exclusion<'static>>,
361    ) -> DatabaseConfiguration<'static> {
362        DatabaseConfiguration {
363            workspace: Cow::Owned(dir.path().to_path_buf()),
364            paths: paths.iter().map(|s| Cow::Owned(s.as_bytes().to_vec())).collect(),
365            includes: includes.iter().map(|s| Cow::Owned(s.as_bytes().to_vec())).collect(),
366            patches: Vec::new(),
367            excludes,
368            extensions: vec![Cow::Borrowed(b"php")],
369            glob: GlobSettings::default(),
370        }
371    }
372
373    fn matcher(configuration: &DatabaseConfiguration<'_>) -> WorkspaceMatcher {
374        WorkspaceMatcher::from_configuration(configuration).unwrap()
375    }
376
377    #[test]
378    fn file_under_a_configured_path_is_tracked_as_host() {
379        let dir = TempDir::new().unwrap();
380        touch(&dir, "src/Foo.php");
381        let matcher = matcher(&config(&dir, &["src"], &[], vec![]));
382
383        assert_eq!(matcher.classify(&dir.path().join("src/Foo.php")), Some(FileType::Host));
384    }
385
386    #[test]
387    fn file_outside_every_configured_path_is_not_tracked() {
388        let dir = TempDir::new().unwrap();
389        touch(&dir, "src/Foo.php");
390        touch(&dir, "scripts/build.php");
391        let matcher = matcher(&config(&dir, &["src"], &[], vec![]));
392
393        assert_eq!(matcher.classify(&dir.path().join("scripts/build.php")), None);
394    }
395
396    #[test]
397    fn glob_excluded_file_is_not_tracked() {
398        let dir = TempDir::new().unwrap();
399        touch(&dir, "src/Foo.php");
400        touch(&dir, "src/generated/Bar.php");
401        let excludes = vec![Exclusion::Pattern(Cow::Borrowed("src/generated/**"))];
402        let matcher = matcher(&config(&dir, &["src"], &[], excludes));
403
404        assert_eq!(matcher.classify(&dir.path().join("src/Foo.php")), Some(FileType::Host));
405        assert_eq!(matcher.classify(&dir.path().join("src/generated/Bar.php")), None);
406    }
407
408    #[test]
409    fn path_excluded_directory_is_not_tracked() {
410        let dir = TempDir::new().unwrap();
411        touch(&dir, "app/Foo.php");
412        touch(&dir, "app/cache/Bar.php");
413        let excludes = vec![Exclusion::Path(Cow::Owned(dir.path().join("app/cache")))];
414        let matcher = matcher(&config(&dir, &["app"], &[], excludes));
415
416        assert_eq!(matcher.classify(&dir.path().join("app/cache/Bar.php")), None);
417    }
418
419    #[test]
420    fn git_ignored_paths_are_vendored_even_before_they_exist() {
421        let dir = TempDir::new().unwrap();
422        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
423        std::fs::write(dir.path().join(".gitignore"), ".claude/worktrees/\n").unwrap();
424        touch(&dir, "src/Foo.php");
425        let ignores = Arc::new(GitIgnores::discover_with_global(dir.path(), None).unwrap());
426        let matcher = matcher(&config(&dir, &[], &[], vec![])).with_git_ignores(ignores);
427
428        assert_eq!(matcher.classify(&dir.path().join("src/Foo.php")), Some(FileType::Host));
429        assert_eq!(matcher.classify(&dir.path().join(".claude/worktrees/new/src/Foo.php")), Some(FileType::Vendored));
430    }
431
432    #[test]
433    fn included_path_is_tracked_as_vendored() {
434        let dir = TempDir::new().unwrap();
435        touch(&dir, "vendor/foo/Lib.php");
436        let matcher = matcher(&config(&dir, &["src"], &["vendor/foo"], vec![]));
437
438        assert_eq!(matcher.classify(&dir.path().join("vendor/foo/Lib.php")), Some(FileType::Vendored));
439    }
440
441    #[test]
442    fn excludes_apply_to_included_paths_too() {
443        // Matches the loader: an `includes` root does not override `excludes`.
444        let dir = TempDir::new().unwrap();
445        touch(&dir, "vendor/foo/Lib.php");
446        let excludes = vec![Exclusion::Pattern(Cow::Borrowed("vendor/**"))];
447        let matcher = matcher(&config(&dir, &["src"], &["vendor/foo"], excludes));
448
449        assert_eq!(matcher.classify(&dir.path().join("vendor/foo/Lib.php")), None);
450    }
451
452    #[test]
453    fn patch_path_is_tracked_as_patch() {
454        let dir = TempDir::new().unwrap();
455        touch(&dir, "stubs/Override.php");
456        let mut configuration = config(&dir, &["src"], &[], vec![]);
457        configuration.patches = vec![Cow::Owned(b"stubs".to_vec())];
458        let matcher = matcher(&configuration);
459
460        assert_eq!(matcher.classify(&dir.path().join("stubs/Override.php")), Some(FileType::Patch));
461    }
462
463    #[test]
464    fn patch_beats_vendored_at_equal_specificity() {
465        // Mirrors the loader's USER_DEFINED > PATCH > BUILT_IN > VENDORED tier order: a file
466        // covered by both `includes` and `patches` at the same specificity resolves to Patch.
467        let dir = TempDir::new().unwrap();
468        touch(&dir, "lib/Lib.php");
469        let mut configuration = config(&dir, &["src"], &["lib"], vec![]);
470        configuration.patches = vec![Cow::Owned(b"lib".to_vec())];
471        let matcher = matcher(&configuration);
472
473        assert_eq!(matcher.classify(&dir.path().join("lib/Lib.php")), Some(FileType::Patch));
474    }
475
476    #[test]
477    fn wrong_extension_is_not_tracked() {
478        let dir = TempDir::new().unwrap();
479        touch(&dir, "src/notes.txt");
480        let matcher = matcher(&config(&dir, &["src"], &[], vec![]));
481
482        assert_eq!(matcher.classify(&dir.path().join("src/notes.txt")), None);
483    }
484
485    #[test]
486    fn empty_paths_track_the_whole_workspace() {
487        let dir = TempDir::new().unwrap();
488        touch(&dir, "anywhere/Foo.php");
489        let matcher = matcher(&config(&dir, &[], &[], vec![]));
490
491        assert_eq!(matcher.classify(&dir.path().join("anywhere/Foo.php")), Some(FileType::Host));
492    }
493}