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