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