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