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