Skip to main content

mago_database/
loader.rs

1//! Database loader for scanning and loading project files.
2
3use std::borrow::Cow;
4use std::collections::hash_map::Entry;
5use std::ffi::OsString;
6use std::path::Path;
7use std::path::PathBuf;
8
9use foldhash::HashMap;
10use foldhash::HashSet;
11use globset::GlobSet;
12use rayon::prelude::*;
13use walkdir::WalkDir;
14
15use crate::Database;
16use crate::DatabaseConfiguration;
17use crate::error::DatabaseError;
18use crate::exclusion::Exclusion;
19use crate::file::File;
20use crate::file::FileId;
21use crate::file::FileType;
22use crate::matcher::build_glob_set;
23use crate::utils::bytes_to_os_str;
24use crate::utils::bytes_to_path;
25use crate::utils::bytes_to_string_lossy;
26use crate::utils::read_file;
27
28/// Holds a file along with the specificity of the pattern that matched it.
29///
30/// Specificity is used to resolve conflicts when a file matches both `paths` and `includes`.
31/// Higher specificity values indicate more specific matches (e.g., exact file paths have higher
32/// specificity than directory patterns).
33#[derive(Debug)]
34struct FileWithSpecificity {
35    file: File,
36    specificity: usize,
37}
38
39/// Builder for loading files into a Database from the filesystem and memory.
40pub struct DatabaseLoader<'config> {
41    database: Option<Database<'config>>,
42    configuration: DatabaseConfiguration<'config>,
43    memory_sources: Vec<(&'static [u8], &'static [u8], FileType)>,
44    stdin_override: Option<(Cow<'config, [u8]>, Vec<u8>)>,
45}
46
47impl<'config> DatabaseLoader<'config> {
48    #[inline]
49    #[must_use]
50    pub fn new(configuration: DatabaseConfiguration<'config>) -> Self {
51        Self { configuration, memory_sources: vec![], database: None, stdin_override: None }
52    }
53
54    #[inline]
55    #[must_use]
56    pub fn with_database(mut self, database: Database<'config>) -> Self {
57        self.database = Some(database);
58        self
59    }
60
61    /// When set, the file with this logical name (workspace-relative path) will use the given
62    /// content instead of being read from disk. The logical name is used for baseline and reporting.
63    ///
64    /// `content` is raw bytes: PHP source is binary-safe, so a buffer piped in via `--stdin-input`
65    /// may not be valid UTF-8.
66    #[inline]
67    #[must_use]
68    pub fn with_stdin_override(mut self, logical_name: impl AsRef<[u8]>, content: Vec<u8>) -> Self {
69        self.stdin_override = Some((Cow::Owned(logical_name.as_ref().to_vec()), content));
70        self
71    }
72
73    #[inline]
74    pub fn add_memory_source(&mut self, name: &'static str, contents: &'static str, file_type: FileType) {
75        self.memory_sources.push((name.as_bytes(), contents.as_bytes(), file_type));
76    }
77
78    /// Loads files from disk into the database.
79    ///
80    /// # Errors
81    ///
82    /// Returns a [`DatabaseError`] if:
83    /// - A glob pattern is invalid
84    /// - File system operations fail (reading directories, files)
85    /// - A file exceeds the maximum supported size
86    #[inline]
87    pub fn load(mut self) -> Result<Database<'config>, DatabaseError> {
88        let mut db = self.database.take().unwrap_or_else(|| Database::new(self.configuration.clone()));
89
90        // Update database configuration to use the loader's configuration
91        // (fixes workspace path when merging with prelude database)
92        db.configuration = self.configuration.clone();
93
94        let extensions_set: HashSet<OsString> =
95            self.configuration.extensions.iter().map(|s| bytes_to_os_str(s.as_ref()).into_owned()).collect();
96
97        let glob_exclude_patterns: Vec<&str> = self
98            .configuration
99            .excludes
100            .iter()
101            .filter_map(|ex| match ex {
102                Exclusion::Pattern(pat) => Some(pat.as_ref()),
103                Exclusion::Path(_) => None,
104            })
105            .collect();
106
107        let glob_excludes = build_glob_set(glob_exclude_patterns.iter().copied(), self.configuration.glob)?;
108        let dir_prune_patterns: Vec<&str> = glob_exclude_patterns
109            .iter()
110            .filter_map(|pat| {
111                let stripped =
112                    pat.strip_suffix("/**/*").or_else(|| pat.strip_suffix("/**")).or_else(|| pat.strip_suffix("/*"))?;
113                if stripped.is_empty() || stripped == "*" || stripped == "**" {
114                    return None;
115                }
116                Some(stripped)
117            })
118            .collect();
119
120        let dir_prune_globs = build_glob_set(dir_prune_patterns.iter().copied(), self.configuration.glob)?;
121
122        let path_excludes: HashSet<_> = self
123            .configuration
124            .excludes
125            .iter()
126            .filter_map(|ex| match ex {
127                Exclusion::Path(p) => Some(p),
128                Exclusion::Pattern(_) => None,
129            })
130            .collect();
131
132        let (host_files_with_spec, (vendored_files_with_spec, patch_files_with_spec)) = rayon::join(
133            || {
134                self.load_paths(
135                    &self.configuration.paths,
136                    FileType::Host,
137                    &extensions_set,
138                    &glob_excludes,
139                    &dir_prune_globs,
140                    &path_excludes,
141                )
142            },
143            || {
144                rayon::join(
145                    || {
146                        self.load_paths(
147                            &self.configuration.includes,
148                            FileType::Vendored,
149                            &extensions_set,
150                            &glob_excludes,
151                            &dir_prune_globs,
152                            &path_excludes,
153                        )
154                    },
155                    || {
156                        self.load_paths(
157                            &self.configuration.patches,
158                            FileType::Patch,
159                            &extensions_set,
160                            &glob_excludes,
161                            &dir_prune_globs,
162                            &path_excludes,
163                        )
164                    },
165                )
166            },
167        );
168        let host_files_with_spec = host_files_with_spec?;
169        let vendored_files_with_spec = vendored_files_with_spec?;
170        let patch_files_with_spec = patch_files_with_spec?;
171
172        let mut all_files: HashMap<FileId, File> = HashMap::default();
173        // Per-file maximum specificity for each tier the file matched. `None` in a slot means
174        // the file did not match any configured pattern in that tier; otherwise it carries the
175        // best specificity score that tier could offer, scored by `calculate_pattern_specificity`.
176        type TierSpecs = (Option<usize>, Option<usize>, Option<usize>);
177        let mut tier_specs: HashMap<FileId, TierSpecs> = HashMap::default();
178
179        // Process host files (from paths)
180        for file_with_spec in host_files_with_spec {
181            let file_id = file_with_spec.file.id;
182            let specificity = file_with_spec.specificity;
183
184            all_files.insert(file_id, file_with_spec.file);
185            bump_spec(&mut tier_specs.entry(file_id).or_insert((None, None, None)).0, specificity);
186        }
187
188        // When stdin override is set, ensure that the file is in the database
189        // (covers new/unsaved files, not on disk). Excluded paths are skipped
190        // so that editor integrations using `--stdin-input` honor the same
191        // exclude rules as a regular filesystem scan.
192        if let Some((name, content)) = &self.stdin_override {
193            let virtual_path = self.configuration.workspace.join(bytes_to_path(name.as_ref()).as_ref());
194            let virtual_path_canonical = virtual_path.canonicalize().unwrap_or_else(|_| virtual_path.clone());
195            let virtual_path_str = virtual_path_canonical.to_string_lossy();
196
197            let matched_glob = !glob_excludes.is_empty()
198                && (glob_excludes.is_match(virtual_path_canonical.as_path())
199                    || glob_excludes.is_match(bytes_to_path(name.as_ref()).as_ref()));
200
201            let matched_path = path_excludes.iter().any(|excl| {
202                let canonical = if Path::new(excl.as_ref()).is_absolute() {
203                    excl.as_ref().to_path_buf()
204                } else {
205                    self.configuration.workspace.join(excl.as_ref())
206                };
207                let canonical = canonical.canonicalize().unwrap_or(canonical);
208                let canonical_str = canonical.to_string_lossy();
209
210                virtual_path_str.starts_with(canonical_str.as_ref())
211                    && matches!(virtual_path_str.as_bytes().get(canonical_str.len()), None | Some(&b'/' | &b'\\'))
212            });
213
214            if !matched_glob && !matched_path {
215                let file = File::ephemeral(Cow::Owned(name.as_ref().to_vec()), Cow::Owned(content.clone()));
216                let file_id = file.id;
217                if let Entry::Vacant(e) = all_files.entry(file_id) {
218                    e.insert(file);
219
220                    bump_spec(&mut tier_specs.entry(file_id).or_insert((None, None, None)).0, usize::MAX);
221                }
222            }
223        }
224
225        for file_with_spec in vendored_files_with_spec {
226            let file_id = file_with_spec.file.id;
227            let vendored_specificity = file_with_spec.specificity;
228
229            all_files.entry(file_id).or_insert(file_with_spec.file);
230            bump_spec(&mut tier_specs.entry(file_id).or_insert((None, None, None)).1, vendored_specificity);
231        }
232
233        for file_with_spec in patch_files_with_spec {
234            let file_id = file_with_spec.file.id;
235            let specificity = file_with_spec.specificity;
236            all_files.entry(file_id).or_insert(file_with_spec.file);
237            bump_spec(&mut tier_specs.entry(file_id).or_insert((None, None, None)).2, specificity);
238        }
239
240        db.reserve(tier_specs.len() + self.memory_sources.len());
241
242        for (file_id, (host_spec, vendored_spec, patch_spec)) in tier_specs {
243            if let Some(mut file) = all_files.remove(&file_id) {
244                file.file_type = resolve_file_type(host_spec, vendored_spec, patch_spec);
245                db.add(file);
246            }
247        }
248
249        for (name, contents, file_type) in self.memory_sources {
250            let file = File::new(Cow::Borrowed(name), file_type, None, Cow::Borrowed(contents));
251
252            db.add(file);
253        }
254
255        Ok(db)
256    }
257
258    /// Discovers and reads all files from a set of root paths or glob patterns in parallel.
259    ///
260    /// Supports both:
261    /// - Directory paths (e.g., "src", "tests") - recursively walks all files
262    /// - Glob patterns (e.g., "src/**/*.php", "tests/Unit/*Test.php") - matches files using glob syntax
263    ///
264    /// Returns files along with their pattern specificity for conflict resolution.
265    fn load_paths(
266        &self,
267        roots: &[Cow<'config, [u8]>],
268        file_type: FileType,
269        extensions: &HashSet<OsString>,
270        glob_excludes: &GlobSet,
271        dir_prune_globs: &GlobSet,
272        path_excludes: &HashSet<&Cow<'config, Path>>,
273    ) -> Result<Vec<FileWithSpecificity>, DatabaseError> {
274        // Canonicalize the workspace once.  All WalkDir roots are canonicalized
275        // before traversal so their paths inherit the canonical prefix without
276        // any per-file syscalls.
277        let canonical_workspace =
278            self.configuration.workspace.canonicalize().unwrap_or_else(|_| self.configuration.workspace.to_path_buf());
279
280        // Pre-canonicalize path excludes once as strings.  A plain byte-string
281        // prefix check is then sufficient in the parallel section, replacing the
282        // per-file canonicalize() + Path::starts_with (Components iteration).
283        let canonical_excludes: Vec<String> = path_excludes
284            .iter()
285            .filter_map(|ex| {
286                let p = if Path::new(ex.as_ref()).is_absolute() {
287                    ex.as_ref().to_path_buf()
288                } else {
289                    self.configuration.workspace.join(ex.as_ref())
290                };
291
292                p.canonicalize().ok()?.into_os_string().into_string().ok()
293            })
294            .collect();
295
296        // The bool flags a path that was named exactly (a literal file on disk) rather than
297        // discovered by walking a configured directory. Such paths bypass the extension filter.
298        let mut paths_to_process: Vec<(PathBuf, usize, bool)> = Vec::new();
299        let mut directory_roots: Vec<(PathBuf, usize)> = Vec::new();
300
301        for root in roots {
302            // Check if this is a glob pattern (contains glob metacharacters).
303            // First check if it's an actual file/directory on disk. if so, treat it
304            // as a literal path even if the name contains glob metacharacters like `[]`.
305            let root_path = bytes_to_path(root.as_ref());
306            let resolved_path = if root_path.is_absolute() {
307                root_path.as_ref().to_path_buf()
308            } else {
309                self.configuration.workspace.join(root_path.as_ref())
310            };
311
312            let is_glob_pattern = !resolved_path.exists()
313                && (root.contains(&b'*') || root.contains(&b'?') || root.contains(&b'[') || root.contains(&b'{'));
314
315            let specificity = calculate_pattern_specificity(root.as_ref());
316            if is_glob_pattern {
317                // Handle as glob pattern
318                let pattern = if root_path.is_absolute() {
319                    bytes_to_string_lossy(root.as_ref()).into_owned()
320                } else {
321                    // Make relative patterns absolute by prepending workspace
322                    self.configuration.workspace.join(root_path.as_ref()).to_string_lossy().to_string()
323                };
324
325                match glob::glob(&pattern) {
326                    Ok(entries) => {
327                        for entry in entries {
328                            match entry {
329                                Ok(path) => {
330                                    if path.is_file() {
331                                        // Canonicalize so the path shares the same prefix as
332                                        // `canonical_workspace` (important on macOS where
333                                        // TempDir / glob return /var/… but canonicalize gives
334                                        // /private/var/…).  Fall back to the original on error.
335                                        let canonical = path.canonicalize().unwrap_or(path);
336                                        paths_to_process.push((canonical, specificity, false));
337                                    }
338                                }
339                                Err(e) => {
340                                    tracing::warn!("Failed to read glob entry: {}", e);
341                                }
342                            }
343                        }
344                    }
345                    Err(e) => {
346                        return Err(DatabaseError::Glob(e.to_string()));
347                    }
348                }
349            } else {
350                let canonical_root = resolved_path.canonicalize().unwrap_or(resolved_path);
351
352                // A path that resolves to a regular file was named explicitly rather than
353                // discovered by walking a directory. Honor it verbatim, bypassing the extension
354                // filter so extensionless PHP files (e.g. `bin/console`) can be loaded.
355                if canonical_root.is_file() {
356                    paths_to_process.push((canonical_root, specificity, true));
357                    continue;
358                }
359
360                for entry in WalkDir::new(&canonical_root).follow_links(true).max_depth(1) {
361                    match entry {
362                        Ok(entry) => {
363                            if entry.depth() == 0 {
364                                continue;
365                            }
366
367                            if entry.file_type().is_dir() {
368                                if !is_pruned_directory(
369                                    entry.path(),
370                                    canonical_workspace.as_path(),
371                                    &canonical_excludes,
372                                    dir_prune_globs,
373                                ) {
374                                    directory_roots.push((entry.into_path(), specificity));
375                                }
376                            } else {
377                                paths_to_process.push((entry.into_path(), specificity, false));
378                            }
379                        }
380                        Err(err) => warn_walk_error(&err, canonical_root.as_path()),
381                    }
382                }
383            }
384        }
385
386        let has_path_excludes = !canonical_excludes.is_empty();
387        let has_glob_excludes = !glob_excludes.is_empty();
388        let load_path = |(path, specificity, skip_ext_check): (PathBuf, usize, bool)| {
389            if has_glob_excludes
390                && (glob_excludes.is_match(&path)
391                    || glob_excludes.is_match(workspace_relative_string(&path, canonical_workspace.as_path())))
392            {
393                return None;
394            }
395
396            if !skip_ext_check {
397                let ext = path.extension()?;
398                if !extensions.contains(ext) {
399                    return None;
400                }
401            }
402
403            if has_path_excludes {
404                let excluded = path.to_str().is_some_and(|s| {
405                    canonical_excludes.iter().any(|excl| {
406                        s.starts_with(excl.as_str())
407                            && matches!(s.as_bytes().get(excl.len()), None | Some(&b'/' | &b'\\'))
408                    })
409                });
410
411                if excluded {
412                    return None;
413                }
414            }
415
416            let workspace = canonical_workspace.as_path();
417            if let Some((override_name, override_content)) = &self.stdin_override {
418                #[cfg(windows)]
419                let logical_name =
420                    path.strip_prefix(workspace).unwrap_or(path.as_path()).to_string_lossy().replace('\\', "/");
421                #[cfg(not(windows))]
422                let logical_name =
423                    path.strip_prefix(workspace).unwrap_or(path.as_path()).to_string_lossy().into_owned();
424
425                if override_name.as_ref() == logical_name.as_bytes() {
426                    let file = File::new(
427                        Cow::Owned(logical_name.into_bytes()),
428                        file_type,
429                        Some(path),
430                        Cow::Owned(override_content.clone()),
431                    );
432
433                    return Some(Ok(FileWithSpecificity { file, specificity }));
434                }
435            }
436
437            match read_file(workspace, &path, file_type) {
438                Ok(file) => Some(Ok(FileWithSpecificity { file, specificity })),
439                Err(e) => Some(Err(e)),
440            }
441        };
442
443        let (direct_files, directory_files) = rayon::join(
444            || paths_to_process.into_par_iter().filter_map(&load_path).collect::<Result<Vec<FileWithSpecificity>, _>>(),
445            || {
446                directory_roots
447                    .into_par_iter()
448                    .map(|(root, specificity)| {
449                        let walker = WalkDir::new(&root).follow_links(true).into_iter().filter_entry(|entry| {
450                            entry.depth() == 0
451                                || !entry.file_type().is_dir()
452                                || !is_pruned_directory(
453                                    entry.path(),
454                                    canonical_workspace.as_path(),
455                                    &canonical_excludes,
456                                    dir_prune_globs,
457                                )
458                        });
459
460                        let mut paths = Vec::new();
461                        for entry in walker {
462                            match entry {
463                                Ok(entry) if !entry.file_type().is_dir() => {
464                                    paths.push((entry.into_path(), specificity, false));
465                                }
466                                Ok(_) => {}
467                                Err(err) => warn_walk_error(&err, root.as_path()),
468                            }
469                        }
470
471                        paths.into_par_iter().filter_map(&load_path).collect::<Result<Vec<_>, _>>()
472                    })
473                    .collect::<Result<Vec<Vec<FileWithSpecificity>>, DatabaseError>>()
474            },
475        );
476
477        let mut files = direct_files?;
478        files.extend(directory_files?.into_iter().flatten());
479
480        Ok(files)
481    }
482}
483
484fn workspace_relative_string(path: &Path, workspace: &Path) -> String {
485    let relative = path.strip_prefix(workspace).unwrap_or(path).to_string_lossy();
486    #[cfg(windows)]
487    {
488        relative.replace('\\', "/")
489    }
490    #[cfg(not(windows))]
491    {
492        relative.into_owned()
493    }
494}
495
496fn is_pruned_directory(
497    path: &Path,
498    workspace: &Path,
499    canonical_excludes: &[String],
500    dir_prune_globs: &GlobSet,
501) -> bool {
502    if let Some(path) = path.to_str()
503        && canonical_excludes.iter().any(|excluded| {
504            path.starts_with(excluded.as_str())
505                && matches!(path.as_bytes().get(excluded.len()), None | Some(&b'/' | &b'\\'))
506        })
507    {
508        return true;
509    }
510
511    !dir_prune_globs.is_empty()
512        && (dir_prune_globs.is_match(path) || dir_prune_globs.is_match(workspace_relative_string(path, workspace)))
513}
514
515fn warn_walk_error(error: &walkdir::Error, fallback: &Path) {
516    let path = error.path().unwrap_or(fallback).display();
517    if let Some(ancestor) = error.loop_ancestor() {
518        tracing::warn!("Skipping symlink loop at `{path}`: link cycles back to `{}`.", ancestor.display());
519    } else {
520        tracing::warn!("Failed to walk `{path}`: {error}. Entry will be skipped.");
521    }
522}
523
524fn bump_spec(slot: &mut Option<usize>, s: usize) {
525    *slot = Some(slot.map_or(s, |e| e.max(s)));
526}
527
528/// Picks the final [`FileType`] for a file that matched configured base paths in one or
529/// more tiers.
530///
531/// Each argument carries the maximum specificity of any matching base path in that tier, or
532/// `None` if no base path in that tier matched. Vendored wins over Host at equal-or-more
533/// specificity; Host wins only when strictly more specific. Patch beats Vendored
534/// unconditionally; Patch beats Host only when strictly more specific. When nothing matches
535/// the result is `Host`.
536pub(crate) fn resolve_file_type(
537    host_spec: Option<usize>,
538    vendored_spec: Option<usize>,
539    patch_spec: Option<usize>,
540) -> FileType {
541    let mut decision: Option<(FileType, usize)> = host_spec.map(|s| (FileType::Host, s));
542
543    if let Some(v) = vendored_spec {
544        decision = match decision {
545            Some((FileType::Host, h)) if v < h => decision,
546            _ => Some((FileType::Vendored, v)),
547        };
548    }
549
550    if let Some(p) = patch_spec {
551        decision = match decision {
552            Some((FileType::Host | FileType::Patch, e)) if p <= e => decision,
553            _ => Some((FileType::Patch, p)),
554        };
555    }
556
557    decision.map(|(ft, _)| ft).unwrap_or(FileType::Host)
558}
559
560/// Calculates how specific a configured base path or glob pattern is for conflict resolution.
561///
562/// Examples:
563///
564/// - "src/b.php" matching src/b.php: ~2000 (exact file, 2 components)
565/// - "src/" matching src/b.php: ~100 (directory, 1 component)
566/// - "src" matching src/b.php: ~100 (directory, 1 component)
567pub(crate) fn calculate_pattern_specificity(pattern: &[u8]) -> usize {
568    let pattern_path = bytes_to_path(pattern);
569
570    let component_count = pattern_path.components().count();
571    let is_glob =
572        pattern.contains(&b'*') || pattern.contains(&b'?') || pattern.contains(&b'[') || pattern.contains(&b'{');
573
574    if is_glob {
575        let non_wildcard_components = pattern_path
576            .components()
577            .filter(|c| {
578                let s = c.as_os_str().to_string_lossy();
579                !s.contains('*') && !s.contains('?') && !s.contains('[') && !s.contains('{')
580            })
581            .count();
582        non_wildcard_components * 10
583    } else if pattern_path.is_file()
584        || pattern_path.extension().is_some()
585        || pattern.rsplit(|&b| b == b'.').next().is_some_and(|ext| ext.eq_ignore_ascii_case(b"php"))
586    {
587        component_count * 1000
588    } else {
589        component_count * 100
590    }
591}
592
593#[cfg(test)]
594mod resolution_tests {
595    use super::*;
596
597    #[test]
598    fn defaults_to_host_when_nothing_matches() {
599        assert_eq!(resolve_file_type(None, None, None), FileType::Host);
600    }
601
602    #[test]
603    fn host_only_match_yields_host() {
604        assert_eq!(resolve_file_type(Some(100), None, None), FileType::Host);
605    }
606
607    #[test]
608    fn vendored_only_match_yields_vendored() {
609        assert_eq!(resolve_file_type(None, Some(100), None), FileType::Vendored);
610    }
611
612    #[test]
613    fn patch_only_match_yields_patch() {
614        assert_eq!(resolve_file_type(None, None, Some(100)), FileType::Patch);
615    }
616
617    #[test]
618    fn vendored_beats_host_at_equal_specificity() {
619        assert_eq!(resolve_file_type(Some(100), Some(100), None), FileType::Vendored);
620    }
621
622    #[test]
623    fn vendored_beats_host_when_more_specific() {
624        assert_eq!(resolve_file_type(Some(100), Some(2000), None), FileType::Vendored);
625    }
626
627    #[test]
628    fn host_beats_vendored_only_when_strictly_more_specific() {
629        assert_eq!(resolve_file_type(Some(2000), Some(100), None), FileType::Host);
630    }
631
632    #[test]
633    fn patch_beats_vendored_unconditionally() {
634        assert_eq!(resolve_file_type(None, Some(2000), Some(100)), FileType::Patch);
635    }
636
637    #[test]
638    fn host_beats_patch_at_equal_specificity() {
639        assert_eq!(resolve_file_type(Some(100), None, Some(100)), FileType::Host);
640    }
641
642    #[test]
643    fn patch_beats_host_when_strictly_more_specific() {
644        assert_eq!(resolve_file_type(Some(100), None, Some(2000)), FileType::Patch);
645    }
646
647    #[test]
648    fn patch_beats_host_that_won_over_vendored() {
649        assert_eq!(resolve_file_type(Some(100), Some(2000), Some(50)), FileType::Patch);
650    }
651
652    #[test]
653    fn exact_file_path_beats_directory_at_same_component_count() {
654        assert!(calculate_pattern_specificity(b"src/foo.php") > calculate_pattern_specificity(b"src/foo"));
655    }
656
657    #[test]
658    fn directory_beats_glob_at_same_non_wildcard_count() {
659        assert!(calculate_pattern_specificity(b"src/") > calculate_pattern_specificity(b"src/**/*.php"));
660    }
661
662    #[test]
663    fn deeper_path_beats_shallower_at_same_kind() {
664        assert!(calculate_pattern_specificity(b"src/inner/") > calculate_pattern_specificity(b"src/"));
665    }
666
667    #[test]
668    fn extensionless_phpish_pattern_treated_as_file() {
669        assert_eq!(calculate_pattern_specificity(b"src/foo.PHP"), calculate_pattern_specificity(b"src/foo.php"),);
670    }
671}
672
673#[cfg(test)]
674#[allow(clippy::unwrap_used, clippy::expect_used)]
675mod tests {
676    use super::*;
677    use crate::DatabaseReader;
678    use crate::GlobSettings;
679    use std::borrow::Cow;
680    use tempfile::TempDir;
681
682    fn create_test_config(temp_dir: &TempDir, paths: Vec<&str>, includes: Vec<&str>) -> DatabaseConfiguration<'static> {
683        create_test_config_with_patches(temp_dir, paths, includes, vec![])
684    }
685
686    fn create_test_config_with_patches(
687        temp_dir: &TempDir,
688        paths: Vec<&str>,
689        includes: Vec<&str>,
690        patches: Vec<&str>,
691    ) -> DatabaseConfiguration<'static> {
692        // Normalize path separators to platform-specific separators
693        let normalize = |s: &str| s.replace('/', std::path::MAIN_SEPARATOR_STR);
694
695        DatabaseConfiguration {
696            workspace: Cow::Owned(temp_dir.path().to_path_buf()),
697            paths: paths.into_iter().map(|s| Cow::Owned(normalize(s).into_bytes())).collect(),
698            includes: includes.into_iter().map(|s| Cow::Owned(normalize(s).into_bytes())).collect(),
699            patches: patches.into_iter().map(|s| Cow::Owned(normalize(s).into_bytes())).collect(),
700            excludes: vec![],
701            extensions: vec![Cow::Borrowed(b"php")],
702            glob: GlobSettings::default(),
703        }
704    }
705
706    /// Returns the file's logical name as a lossy UTF-8 string for assertion matching.
707    fn name_str(name: &[u8]) -> std::borrow::Cow<'_, str> {
708        String::from_utf8_lossy(name)
709    }
710
711    fn create_test_file(temp_dir: &TempDir, relative_path: &str, content: &str) {
712        let file_path = temp_dir.path().join(relative_path);
713        if let Some(parent) = file_path.parent() {
714            std::fs::create_dir_all(parent).unwrap();
715        }
716        std::fs::write(file_path, content).unwrap();
717    }
718
719    #[test]
720    fn test_nested_files_match_with_one_and_many_threads() {
721        let temp_dir = TempDir::new().unwrap();
722        create_test_file(&temp_dir, "src/deep/a.php", "<?php // host");
723        create_test_file(&temp_dir, "src/deep/b.php", "<?php // vendor");
724        create_test_file(&temp_dir, "src/deep/patch/c.php", "<?php // patch");
725        create_test_file(&temp_dir, "src/deep/skip/d.php", "<?php // excluded");
726        create_test_file(&temp_dir, "src/deep/e.txt", "<?php // wrong extension");
727
728        let mut config = create_test_config_with_patches(
729            &temp_dir,
730            vec!["src", "src/deep/a.php"],
731            vec!["src/deep"],
732            vec!["src/deep/patch"],
733        );
734        config.excludes.push(Exclusion::Pattern(Cow::Borrowed("src/deep/skip/**")));
735
736        for threads in [1, 4] {
737            let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap();
738            let db = pool.install(|| {
739                DatabaseLoader::new(config.clone())
740                    .with_stdin_override(b"src/deep/a.php", b"<?php // edited".to_vec())
741                    .load()
742                    .unwrap()
743            });
744            let mut files =
745                db.files().map(|file| (file.name.to_vec(), file.file_type, file.contents.to_vec())).collect::<Vec<_>>();
746            files.sort_by(|left, right| left.0.cmp(&right.0));
747
748            assert_eq!(
749                files,
750                vec![
751                    (b"src/deep/a.php".to_vec(), FileType::Host, b"<?php // edited".to_vec()),
752                    (b"src/deep/b.php".to_vec(), FileType::Vendored, b"<?php // vendor".to_vec()),
753                    (b"src/deep/patch/c.php".to_vec(), FileType::Patch, b"<?php // patch".to_vec()),
754                ],
755            );
756        }
757    }
758
759    #[test]
760    fn test_exact_file_vs_directory() {
761        let temp_dir = TempDir::new().unwrap();
762
763        create_test_file(&temp_dir, "src/b.php", "<?php");
764        create_test_file(&temp_dir, "src/a.php", "<?php");
765
766        let config = create_test_config(&temp_dir, vec!["src/b.php"], vec!["src/"]);
767        let loader = DatabaseLoader::new(config);
768        let db = loader.load().unwrap();
769
770        let b_file = db.files().find(|f| name_str(&f.name).contains("b.php")).unwrap();
771        assert_eq!(b_file.file_type, FileType::Host, "src/b.php should be Host (exact file beats directory)");
772
773        let a_file = db.files().find(|f| name_str(&f.name).contains("a.php")).unwrap();
774        assert_eq!(a_file.file_type, FileType::Vendored, "src/a.php should be Vendored");
775    }
776
777    #[test]
778    fn test_deeper_vs_shallower_directory() {
779        let temp_dir = TempDir::new().unwrap();
780
781        create_test_file(&temp_dir, "src/foo/bar.php", "<?php");
782
783        let config = create_test_config(&temp_dir, vec!["src/foo/"], vec!["src/"]);
784        let loader = DatabaseLoader::new(config);
785        let db = loader.load().unwrap();
786
787        let file = db.files().find(|f| name_str(&f.name).contains("bar.php")).unwrap();
788        assert_eq!(file.file_type, FileType::Host, "Deeper directory pattern should win");
789    }
790
791    #[test]
792    fn test_exact_file_vs_glob() {
793        let temp_dir = TempDir::new().unwrap();
794
795        create_test_file(&temp_dir, "src/b.php", "<?php");
796
797        let config = create_test_config(&temp_dir, vec!["src/b.php"], vec!["src/*.php"]);
798        let loader = DatabaseLoader::new(config);
799        let db = loader.load().unwrap();
800
801        let file = db.files().find(|f| name_str(&f.name).contains("b.php")).unwrap();
802        assert_eq!(file.file_type, FileType::Host, "Exact file should beat glob pattern");
803    }
804
805    #[test]
806    fn test_equal_specificity_includes_wins() {
807        let temp_dir = TempDir::new().unwrap();
808
809        create_test_file(&temp_dir, "src/a.php", "<?php");
810
811        let config = create_test_config(&temp_dir, vec!["src/"], vec!["src/"]);
812        let loader = DatabaseLoader::new(config);
813        let db = loader.load().unwrap();
814
815        let file = db.files().find(|f| name_str(&f.name).contains("a.php")).unwrap();
816        assert_eq!(file.file_type, FileType::Vendored, "Equal specificity: includes should win");
817    }
818
819    #[test]
820    fn test_complex_scenario_from_bug_report() {
821        let temp_dir = TempDir::new().unwrap();
822
823        create_test_file(&temp_dir, "src/a.php", "<?php");
824        create_test_file(&temp_dir, "src/b.php", "<?php");
825        create_test_file(&temp_dir, "src/c/d.php", "<?php");
826        create_test_file(&temp_dir, "src/c/e.php", "<?php");
827        create_test_file(&temp_dir, "vendor/lib1.php", "<?php");
828        create_test_file(&temp_dir, "vendor/lib2.php", "<?php");
829
830        let config = create_test_config(&temp_dir, vec!["src/b.php"], vec!["vendor", "src/c", "src/"]);
831        let loader = DatabaseLoader::new(config);
832        let db = loader.load().unwrap();
833
834        let b_file = db
835            .files()
836            .find(|f| name_str(&f.name).contains("src/b.php") || name_str(&f.name).ends_with("b.php"))
837            .unwrap();
838        assert_eq!(b_file.file_type, FileType::Host, "src/b.php should be Host in bug scenario");
839
840        let d_file = db.files().find(|f| name_str(&f.name).contains("d.php")).unwrap();
841        assert_eq!(d_file.file_type, FileType::Vendored, "src/c/d.php should be Vendored");
842
843        let lib_file = db.files().find(|f| name_str(&f.name).contains("lib1.php")).unwrap();
844        assert_eq!(lib_file.file_type, FileType::Vendored, "vendor/lib1.php should be Vendored");
845    }
846
847    #[test]
848    fn test_files_only_in_paths() {
849        let temp_dir = TempDir::new().unwrap();
850
851        create_test_file(&temp_dir, "src/a.php", "<?php");
852
853        let config = create_test_config(&temp_dir, vec!["src/"], vec![]);
854        let loader = DatabaseLoader::new(config);
855        let db = loader.load().unwrap();
856
857        let file = db.files().find(|f| name_str(&f.name).contains("a.php")).unwrap();
858        assert_eq!(file.file_type, FileType::Host, "File only in paths should be Host");
859    }
860
861    #[test]
862    fn test_files_only_in_includes() {
863        let temp_dir = TempDir::new().unwrap();
864
865        create_test_file(&temp_dir, "vendor/lib.php", "<?php");
866
867        let config = create_test_config(&temp_dir, vec![], vec!["vendor/"]);
868        let loader = DatabaseLoader::new(config);
869        let db = loader.load().unwrap();
870
871        let file = db.files().find(|f| name_str(&f.name).contains("lib.php")).unwrap();
872        assert_eq!(file.file_type, FileType::Vendored, "File only in includes should be Vendored");
873    }
874
875    #[test]
876    fn test_stdin_override_replaces_file_content() {
877        let temp_dir = TempDir::new().unwrap();
878        create_test_file(&temp_dir, "src/foo.php", "<?php\n// on disk");
879
880        let config = create_test_config(&temp_dir, vec!["src/"], vec![]);
881        let loader = DatabaseLoader::new(config).with_stdin_override("src/foo.php", b"<?php\n// from stdin".to_vec());
882        let db = loader.load().unwrap();
883
884        let file = db.files().find(|f| name_str(&f.name).contains("foo.php")).unwrap();
885        assert_eq!(
886            file.contents.as_ref(),
887            b"<?php\n// from stdin",
888            "stdin override content should be used instead of disk"
889        );
890    }
891
892    #[test]
893    fn test_glob_excludes_match_workspace_relative_paths() {
894        let temp_dir = TempDir::new().unwrap();
895
896        create_test_file(&temp_dir, "src/Absences/Foo/Foo.php", "<?php");
897        create_test_file(&temp_dir, "src/Absences/Test/Faker/Provider/AbsencesProvider.php", "<?php");
898        create_test_file(&temp_dir, "src/Calendar/Test/Helper.php", "<?php");
899
900        let mut config = create_test_config(&temp_dir, vec!["src"], vec![]);
901        config.excludes = vec![Exclusion::Pattern(Cow::Borrowed("src/*/Test/**"))];
902
903        let loader = DatabaseLoader::new(config);
904        let db = loader.load().unwrap();
905
906        let names: Vec<String> = db.files().map(|f| name_str(&f.name).into_owned()).collect();
907        assert!(names.iter().any(|n| n.ends_with("src/Absences/Foo/Foo.php")), "non-Test file should be loaded");
908        assert!(
909            !names.iter().any(|n| n.contains("src/Absences/Test/")),
910            "files under src/*/Test/** should be excluded, got {names:?}"
911        );
912        assert!(
913            !names.iter().any(|n| n.contains("src/Calendar/Test/")),
914            "files under src/*/Test/** should be excluded, got {names:?}"
915        );
916    }
917
918    #[test]
919    fn test_glob_excludes_match_legacy_absolute_prefix_patterns() {
920        let temp_dir = TempDir::new().unwrap();
921
922        create_test_file(&temp_dir, "packages/foo/src/main.php", "<?php");
923        create_test_file(&temp_dir, "packages/foo/vendor/lib.php", "<?php");
924
925        let mut config = create_test_config(&temp_dir, vec!["packages"], vec![]);
926        config.excludes = vec![Exclusion::Pattern(Cow::Borrowed("*/packages/**/vendor/*"))];
927
928        let loader = DatabaseLoader::new(config);
929        let db = loader.load().unwrap();
930
931        let names: Vec<String> = db.files().map(|f| name_str(&f.name).into_owned()).collect();
932        assert!(names.iter().any(|n| n.ends_with("packages/foo/src/main.php")));
933        assert!(
934            !names.iter().any(|n| n.contains("/vendor/")),
935            "legacy `*/packages/**/vendor/*` style should still exclude vendor files, got {names:?}"
936        );
937    }
938
939    #[test]
940    fn test_glob_dir_prune_skips_relative_directories() {
941        let temp_dir = TempDir::new().unwrap();
942
943        create_test_file(&temp_dir, "vendor/slevomat/coding-standard/main.php", "<?php");
944        create_test_file(&temp_dir, "vendor/slevomat/coding-standard/tests/Sniffs/Foo.php", "<?php");
945        create_test_file(&temp_dir, "vendor/another/lib.php", "<?php");
946
947        let mut config = create_test_config(&temp_dir, vec![], vec!["vendor"]);
948        config.excludes = vec![Exclusion::Pattern(Cow::Borrowed("vendor/**/tests/**"))];
949
950        let loader = DatabaseLoader::new(config);
951        let db = loader.load().unwrap();
952
953        let names: Vec<String> = db.files().map(|f| name_str(&f.name).into_owned()).collect();
954        assert!(names.iter().any(|n| n.ends_with("vendor/slevomat/coding-standard/main.php")));
955        assert!(names.iter().any(|n| n.ends_with("vendor/another/lib.php")));
956        assert!(
957            !names.iter().any(|n| n.contains("/tests/")),
958            "files under vendor/**/tests/** should be pruned, got {names:?}"
959        );
960    }
961
962    #[test]
963    fn test_stdin_override_adds_file_when_not_on_disk() {
964        let temp_dir = TempDir::new().unwrap();
965        create_test_file(&temp_dir, "src/.gitkeep", "");
966
967        let config = create_test_config(&temp_dir, vec!["src/"], vec![]);
968        let loader =
969            DatabaseLoader::new(config).with_stdin_override("src/unsaved.php", b"<?php\n// unsaved buffer".to_vec());
970        let db = loader.load().unwrap();
971
972        let file = db.files().find(|f| name_str(&f.name).contains("unsaved.php")).unwrap();
973        assert_eq!(file.file_type, FileType::Host);
974        assert_eq!(file.contents.as_ref(), b"<?php\n// unsaved buffer");
975    }
976
977    #[test]
978    fn test_stdin_override_accepts_non_utf8_content() {
979        let temp_dir = TempDir::new().unwrap();
980        create_test_file(&temp_dir, "src/.gitkeep", "");
981
982        let config = create_test_config(&temp_dir, vec!["src/"], vec![]);
983        // PHP identifiers are binary-safe, so a buffer piped in via `--stdin-input` may not
984        // be valid UTF-8. The loaded file must carry those bytes through verbatim.
985        let content = b"<?php\n\nfunction f\xC9\xFF(): void {}\n".to_vec();
986        assert!(std::str::from_utf8(&content).is_err(), "test buffer must contain non-UTF-8 bytes");
987
988        let loader = DatabaseLoader::new(config).with_stdin_override("src/buffer.php", content.clone());
989        let db = loader.load().unwrap();
990
991        let file = db.files().find(|f| name_str(&f.name).contains("buffer.php")).unwrap();
992        assert_eq!(file.contents.as_ref(), content.as_slice());
993    }
994
995    #[cfg(unix)]
996    #[test]
997    fn test_symlinked_file_under_include_is_loaded() {
998        let temp_dir = TempDir::new().unwrap();
999        let external = TempDir::new().unwrap();
1000
1001        create_test_file(&external, "Bar.php", "<?php class Bar {}\n");
1002        std::fs::create_dir_all(temp_dir.path().join("vendor")).unwrap();
1003        std::os::unix::fs::symlink(external.path().join("Bar.php"), temp_dir.path().join("vendor/Bar.php")).unwrap();
1004
1005        let config = create_test_config(&temp_dir, vec![], vec!["vendor/"]);
1006        let db = DatabaseLoader::new(config).load().unwrap();
1007
1008        let bar = db.files().find(|f| name_str(&f.name).contains("Bar.php"));
1009        assert!(bar.is_some(), "symlinked Bar.php should be loaded via include = ['vendor/']");
1010    }
1011
1012    #[cfg(unix)]
1013    #[test]
1014    fn test_symlinked_directory_under_include_is_descended() {
1015        let temp_dir = TempDir::new().unwrap();
1016        let external = TempDir::new().unwrap();
1017
1018        create_test_file(&external, "src/Foo.php", "<?php class Foo {}\n");
1019        create_test_file(&external, "src/Bar.php", "<?php class Bar {}\n");
1020
1021        std::fs::create_dir_all(temp_dir.path().join("vendor")).unwrap();
1022        std::os::unix::fs::symlink(external.path(), temp_dir.path().join("vendor/example-package")).unwrap();
1023
1024        let config = create_test_config(&temp_dir, vec![], vec!["vendor/"]);
1025        let db = DatabaseLoader::new(config).load().unwrap();
1026
1027        assert!(db.files().any(|f| name_str(&f.name).contains("Foo.php")), "Foo.php inside symlinked dir not found");
1028        assert!(db.files().any(|f| name_str(&f.name).contains("Bar.php")), "Bar.php inside symlinked dir not found");
1029    }
1030
1031    #[cfg(unix)]
1032    #[test]
1033    fn test_symlink_cycle_is_warned_and_skipped() {
1034        let temp_dir = TempDir::new().unwrap();
1035        create_test_file(&temp_dir, "src/Real.php", "<?php class Real {}\n");
1036        std::os::unix::fs::symlink(temp_dir.path().join("src"), temp_dir.path().join("src/loop")).unwrap();
1037
1038        let config = create_test_config(&temp_dir, vec![], vec!["src/"]);
1039        let db = DatabaseLoader::new(config).load().expect("symlink cycle should not abort the load");
1040
1041        assert!(
1042            db.files().any(|f| name_str(&f.name).contains("Real.php")),
1043            "Real.php still reachable despite the loop"
1044        );
1045    }
1046
1047    #[test]
1048    fn test_exact_extensionless_file_is_loaded() {
1049        let temp_dir = TempDir::new().unwrap();
1050        create_test_file(&temp_dir, "bin/console", "<?php\n// entrypoint");
1051
1052        // `bin/console` has no extension, so it would be filtered out when discovered by
1053        // walking a directory. Naming it exactly must bypass the extension requirement.
1054        let config = create_test_config(&temp_dir, vec!["bin/console"], vec![]);
1055        let db = DatabaseLoader::new(config).load().unwrap();
1056
1057        let file = db.files().find(|f| name_str(&f.name).ends_with("bin/console")).unwrap();
1058        assert_eq!(file.file_type, FileType::Host);
1059        assert_eq!(file.contents.as_ref(), b"<?php\n// entrypoint");
1060    }
1061
1062    #[test]
1063    fn test_extensionless_file_in_directory_is_skipped() {
1064        let temp_dir = TempDir::new().unwrap();
1065        create_test_file(&temp_dir, "bin/console", "<?php");
1066        create_test_file(&temp_dir, "bin/run.php", "<?php");
1067
1068        // Walking the directory must still honor the extension filter: only `run.php` loads.
1069        let config = create_test_config(&temp_dir, vec!["bin"], vec![]);
1070        let db = DatabaseLoader::new(config).load().unwrap();
1071
1072        let names: Vec<String> = db.files().map(|f| name_str(&f.name).into_owned()).collect();
1073        assert!(names.iter().any(|n| n.ends_with("bin/run.php")), "run.php should be loaded, got {names:?}");
1074        assert!(!names.iter().any(|n| n.ends_with("bin/console")), "extensionless console should be skipped");
1075    }
1076
1077    #[test]
1078    fn test_patch_beats_vendored_at_equal_specificity() {
1079        // A file covered by both patches and includes at the same directory-level specificity
1080        // should be classified as Patch, not Vendored.
1081        let temp_dir = TempDir::new().unwrap();
1082        create_test_file(&temp_dir, "lib/Foo.php", "<?php");
1083
1084        let config = create_test_config_with_patches(&temp_dir, vec![], vec!["lib/"], vec!["lib/"]);
1085        let db = DatabaseLoader::new(config).load().unwrap();
1086
1087        let file = db.files().find(|f| String::from_utf8_lossy(&f.name).contains("Foo.php")).unwrap();
1088        assert_eq!(file.file_type, FileType::Patch, "patch should beat vendored at equal specificity");
1089    }
1090
1091    #[test]
1092    fn test_host_beats_patch_at_equal_specificity() {
1093        // When a file is covered by both paths and patches at the same directory-level specificity,
1094        // the host (paths) classification wins.  Patches only override host when strictly more specific.
1095        let temp_dir = TempDir::new().unwrap();
1096        create_test_file(&temp_dir, "src/Foo.php", "<?php");
1097
1098        let config = create_test_config_with_patches(&temp_dir, vec!["src/"], vec![], vec!["src/"]);
1099        let db = DatabaseLoader::new(config).load().unwrap();
1100
1101        let file = db.files().find(|f| String::from_utf8_lossy(&f.name).contains("Foo.php")).unwrap();
1102        assert_eq!(file.file_type, FileType::Host, "host should beat patch at equal specificity");
1103    }
1104
1105    #[test]
1106    fn test_patch_beats_host_when_strictly_more_specific() {
1107        // An exact-file patch pattern has higher specificity than a directory paths pattern,
1108        // so the patch wins and the file is treated as Patch rather than Host.
1109        let temp_dir = TempDir::new().unwrap();
1110        create_test_file(&temp_dir, "src/Foo.php", "<?php");
1111        create_test_file(&temp_dir, "src/Bar.php", "<?php");
1112
1113        // Patch covers only Foo.php exactly; paths covers the whole directory.
1114        let config = create_test_config_with_patches(&temp_dir, vec!["src/"], vec![], vec!["src/Foo.php"]);
1115        let db = DatabaseLoader::new(config).load().unwrap();
1116
1117        let foo = db.files().find(|f| String::from_utf8_lossy(&f.name).contains("Foo.php")).unwrap();
1118        assert_eq!(foo.file_type, FileType::Patch, "exact-file patch should beat directory-level host pattern");
1119
1120        let bar = db.files().find(|f| String::from_utf8_lossy(&f.name).contains("Bar.php")).unwrap();
1121        assert_eq!(bar.file_type, FileType::Host, "file not covered by patch should remain Host");
1122    }
1123}