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    #[allow(clippy::set_contains_or_insert, reason = "A duplicate insert can grow a full set.")]
316    fn record_directory_symlink(&self, entry: &walkdir::DirEntry) {
317        if let Some(symlinks) = &self.directory_symlinks
318            && entry.file_type().is_dir()
319            && entry.path_is_symlink()
320        {
321            let mut symlinks = symlinks.lock().unwrap_or_else(PoisonError::into_inner);
322            if !symlinks.contains(entry.path()) {
323                symlinks.insert(entry.path().to_path_buf());
324            }
325        }
326    }
327
328    #[allow(clippy::set_contains_or_insert, reason = "A duplicate insert can grow a full set.")]
329    fn record_missing_symlink(&self, error: &walkdir::Error) {
330        let Some(symlinks) = &self.directory_symlinks else { return };
331        if error.io_error().is_some_and(|error| matches!(error.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory))
332            && let Some(path) = error.path()
333            && path.read_link().is_ok()
334        {
335            let mut symlinks = symlinks.lock().unwrap_or_else(PoisonError::into_inner);
336            if !symlinks.contains(path) {
337                symlinks.insert(path.to_path_buf());
338            }
339        }
340    }
341
342    /// Discovers and reads all files from a set of root paths or glob patterns in parallel.
343    ///
344    /// Supports both:
345    /// - Directory paths (e.g., "src", "tests") - recursively walks all files
346    /// - Glob patterns (e.g., "src/**/*.php", "tests/Unit/*Test.php") - matches files using glob syntax
347    ///
348    /// Returns files along with their pattern specificity for conflict resolution.
349    fn load_paths(
350        &self,
351        roots: &[Cow<'config, [u8]>],
352        file_type: FileType,
353        extensions: &HashSet<OsString>,
354        glob_excludes: &GlobSet,
355        dir_prune_globs: &GlobSet,
356        path_excludes: &HashSet<&Cow<'config, Path>>,
357    ) -> Result<Vec<FileWithSpecificity>, DatabaseError> {
358        // Canonicalize the workspace once.  All WalkDir roots are canonicalized
359        // before traversal so their paths inherit the canonical prefix without
360        // any per-file syscalls.
361        let canonical_workspace =
362            self.configuration.workspace.canonicalize().unwrap_or_else(|_| self.configuration.workspace.to_path_buf());
363
364        // Pre-canonicalize path excludes once as strings.  A plain byte-string
365        // prefix check is then sufficient in the parallel section, replacing the
366        // per-file canonicalize() + Path::starts_with (Components iteration).
367        let canonical_excludes: Vec<String> = path_excludes
368            .iter()
369            .filter_map(|ex| {
370                let p = if Path::new(ex.as_ref()).is_absolute() {
371                    ex.as_ref().to_path_buf()
372                } else {
373                    self.configuration.workspace.join(ex.as_ref())
374                };
375
376                p.canonicalize().ok()?.into_os_string().into_string().ok()
377            })
378            .collect();
379
380        // The bool flags a path that was named exactly (a literal file on disk) rather than
381        // discovered by walking a configured directory. Such paths bypass the extension filter.
382        let mut paths_to_process: Vec<(PathBuf, usize, bool)> = Vec::new();
383        let mut directory_roots: Vec<(PathBuf, usize)> = Vec::new();
384
385        for root in roots {
386            // Check if this is a glob pattern (contains glob metacharacters).
387            // First check if it's an actual file/directory on disk. if so, treat it
388            // as a literal path even if the name contains glob metacharacters like `[]`.
389            let root_path = bytes_to_path(root.as_ref());
390            let resolved_path = if root_path.is_absolute() {
391                root_path.as_ref().to_path_buf()
392            } else {
393                self.configuration.workspace.join(root_path.as_ref())
394            };
395
396            let is_glob_pattern = !resolved_path.exists()
397                && (root.contains(&b'*') || root.contains(&b'?') || root.contains(&b'[') || root.contains(&b'{'));
398
399            let specificity = calculate_pattern_specificity(root.as_ref());
400            if is_glob_pattern {
401                // Handle as glob pattern
402                let pattern = if root_path.is_absolute() {
403                    bytes_to_string_lossy(root.as_ref()).into_owned()
404                } else {
405                    // Make relative patterns absolute by prepending workspace
406                    self.configuration.workspace.join(root_path.as_ref()).to_string_lossy().to_string()
407                };
408
409                match glob::glob(&pattern) {
410                    Ok(entries) => {
411                        for entry in entries {
412                            match entry {
413                                Ok(path) => {
414                                    if path.is_file() {
415                                        // Canonicalize so the path shares the same prefix as
416                                        // `canonical_workspace` (important on macOS where
417                                        // TempDir / glob return /var/… but canonicalize gives
418                                        // /private/var/…).  Fall back to the original on error.
419                                        let canonical = path.canonicalize().unwrap_or(path);
420                                        paths_to_process.push((canonical, specificity, false));
421                                    }
422                                }
423                                Err(e) => {
424                                    tracing::warn!("Failed to read glob entry: {}", e);
425                                }
426                            }
427                        }
428                    }
429                    Err(e) => {
430                        return Err(DatabaseError::Glob(e.to_string()));
431                    }
432                }
433            } else {
434                // A path that resolves to a regular file was named explicitly rather than
435                // discovered by walking a directory. Honor it verbatim, bypassing the extension
436                // filter so extensionless PHP files (e.g. `bin/console`) can be loaded.
437                //
438                // It keeps the name it was given: a relative path is joined to
439                // `canonical_workspace` instead of being canonicalized, and otherwise only its
440                // directory is canonicalized, so the path shares the canonical workspace prefix
441                // while symlinks below the workspace are not resolved, as for files found by
442                // walking a directory. Resolving them would replace a symlink with its target,
443                // which may lie outside the workspace (e.g. build systems such as Bazel stage
444                // inputs as symlinks), and baselines and path-scoped ignores would then no longer
445                // match the file's workspace-relative name.
446                if resolved_path.is_file() {
447                    let path = if root_path.is_relative()
448                        && !root_path.components().any(|component| matches!(component, Component::ParentDir))
449                    {
450                        canonical_workspace.join(root_path.as_ref())
451                    } else {
452                        resolved_path
453                            .parent()
454                            .zip(resolved_path.file_name())
455                            .and_then(|(parent, name)| parent.canonicalize().ok().map(|parent| parent.join(name)))
456                            .unwrap_or_else(|| resolved_path.canonicalize().unwrap_or(resolved_path))
457                    };
458                    paths_to_process.push((path, specificity, true));
459                    continue;
460                }
461
462                let canonical_root = resolved_path.canonicalize().unwrap_or(resolved_path);
463
464                for entry in WalkDir::new(&canonical_root).follow_links(true).max_depth(1) {
465                    match entry {
466                        Ok(entry) => {
467                            if entry.depth() == 0 {
468                                continue;
469                            }
470
471                            if entry.file_type().is_dir() {
472                                if !is_pruned_directory(
473                                    entry.path(),
474                                    canonical_workspace.as_path(),
475                                    &canonical_excludes,
476                                    dir_prune_globs,
477                                ) {
478                                    self.record_directory_symlink(&entry);
479                                    directory_roots.push((entry.into_path(), specificity));
480                                }
481                            } else {
482                                paths_to_process.push((entry.into_path(), specificity, false));
483                            }
484                        }
485                        Err(err) => {
486                            self.record_missing_symlink(&err);
487                            warn_walk_error(&err, canonical_root.as_path());
488                        }
489                    }
490                }
491            }
492        }
493
494        let has_path_excludes = !canonical_excludes.is_empty();
495        let has_glob_excludes = !glob_excludes.is_empty();
496        let load_path = |(path, specificity, skip_ext_check): (PathBuf, usize, bool)| {
497            if has_glob_excludes
498                && (glob_excludes.is_match(&path)
499                    || glob_excludes.is_match(workspace_relative_string(&path, canonical_workspace.as_path())))
500            {
501                return None;
502            }
503
504            if !skip_ext_check {
505                let ext = path.extension()?;
506                if !extensions.contains(ext) {
507                    return None;
508                }
509            }
510
511            if has_path_excludes {
512                let excluded = path.to_str().is_some_and(|s| {
513                    canonical_excludes.iter().any(|excl| {
514                        s.starts_with(excl.as_str())
515                            && matches!(s.as_bytes().get(excl.len()), None | Some(&b'/' | &b'\\'))
516                    })
517                });
518
519                if excluded {
520                    return None;
521                }
522            }
523
524            let workspace = canonical_workspace.as_path();
525            if let Some((override_name, override_content)) = &self.stdin_override {
526                #[cfg(windows)]
527                let logical_name = path.trim_prefix(workspace).to_string_lossy().replace('\\', "/");
528                #[cfg(not(windows))]
529                let logical_name = path.trim_prefix(workspace).to_string_lossy().into_owned();
530
531                if override_name.as_ref() == logical_name.as_bytes() {
532                    let file = File::new(
533                        Cow::Owned(logical_name.into_bytes()),
534                        file_type,
535                        Some(path),
536                        Cow::Owned(override_content.clone()),
537                    );
538
539                    return Some(Ok(FileWithSpecificity { file, specificity }));
540                }
541            }
542
543            match read_file(workspace, &path, file_type) {
544                Ok(file) => Some(Ok(FileWithSpecificity { file, specificity })),
545                Err(e) => Some(Err(e)),
546            }
547        };
548
549        let (direct_files, directory_files) = rayon::join(
550            || paths_to_process.into_par_iter().filter_map(&load_path).collect::<Result<Vec<FileWithSpecificity>, _>>(),
551            || {
552                directory_roots
553                    .into_par_iter()
554                    .map(|(root, specificity)| {
555                        #[cfg(unix)]
556                        if rayon::current_num_threads() > 1
557                            && root.symlink_metadata().is_ok_and(|metadata| metadata.file_type().is_dir())
558                        {
559                            let fallback = AtomicBool::new(false);
560                            if let Some(files) = try_load_directory_parallel(
561                                &root,
562                                specificity,
563                                &load_path,
564                                &|path| {
565                                    is_pruned_directory(
566                                        path,
567                                        canonical_workspace.as_path(),
568                                        &canonical_excludes,
569                                        dir_prune_globs,
570                                    )
571                                },
572                                &fallback,
573                                0,
574                            ) {
575                                return files;
576                            }
577                        }
578
579                        let walker = WalkDir::new(&root).follow_links(true).into_iter().filter_entry(|entry| {
580                            let keep = entry.depth() == 0
581                                || !entry.file_type().is_dir()
582                                || !is_pruned_directory(
583                                    entry.path(),
584                                    canonical_workspace.as_path(),
585                                    &canonical_excludes,
586                                    dir_prune_globs,
587                                );
588
589                            if keep {
590                                self.record_directory_symlink(entry);
591                            }
592
593                            keep
594                        });
595
596                        let mut paths = walker.filter_map(|entry| match entry {
597                            Ok(entry) if !entry.file_type().is_dir() => Some((entry.into_path(), specificity, false)),
598                            Ok(_) => None,
599                            Err(err) => {
600                                self.record_missing_symlink(&err);
601                                warn_walk_error(&err, root.as_path());
602                                None
603                            }
604                        });
605
606                        let batches = std::iter::from_fn(|| {
607                            let batch: Vec<_> = paths.by_ref().take(128).collect();
608                            (!batch.is_empty()).then_some(batch)
609                        });
610
611                        let loaded = Mutex::new(Vec::new());
612                        let load_path = &load_path;
613                        // Let workers read batches while this worker walks the directory.
614                        rayon::scope(|scope| {
615                            for (index, paths) in batches.enumerate() {
616                                let loaded = &loaded;
617                                scope.spawn(move |_| {
618                                    let files = paths.into_iter().filter_map(load_path).collect::<Result<Vec<_>, _>>();
619                                    loaded.lock().unwrap_or_else(PoisonError::into_inner).push((index, files));
620                                });
621                            }
622                        });
623
624                        let mut loaded = loaded.into_inner().unwrap_or_else(PoisonError::into_inner);
625                        loaded.sort_unstable_by_key(|(index, _)| *index);
626                        let mut files = Vec::new();
627                        for (_, batch) in loaded {
628                            files.extend(batch?);
629                        }
630
631                        Ok(files)
632                    })
633                    .collect::<Result<Vec<Vec<FileWithSpecificity>>, DatabaseError>>()
634            },
635        );
636
637        let mut files = direct_files?;
638        files.extend(directory_files?.into_iter().flatten());
639
640        Ok(files)
641    }
642}
643
644#[cfg(unix)]
645enum LoadedDirectoryEntry {
646    File(Option<Result<FileWithSpecificity, DatabaseError>>),
647    Directory(Option<Result<Vec<FileWithSpecificity>, DatabaseError>>),
648}
649
650// Windows WalkDir also opens ancestor handles, with distinct error behavior.
651#[cfg(unix)]
652fn try_load_directory_parallel<F, P>(
653    root: &Path,
654    specificity: usize,
655    load_path: &F,
656    is_pruned: &P,
657    fallback: &AtomicBool,
658    depth: usize,
659) -> Option<Result<Vec<FileWithSpecificity>, DatabaseError>>
660where
661    F: Fn((PathBuf, usize, bool)) -> Option<Result<FileWithSpecificity, DatabaseError>> + Sync,
662    P: Fn(&Path) -> bool + Sync,
663{
664    let use_walker = || {
665        fallback.store(true, Ordering::Relaxed);
666        None
667    };
668
669    if depth == 64 || fallback.load(Ordering::Relaxed) {
670        return use_walker();
671    }
672
673    let Ok(directory) = std::fs::read_dir(root) else {
674        return use_walker();
675    };
676
677    let entries = directory
678        .map(|entry| {
679            let entry = entry?;
680            Ok((entry.path(), entry.file_type()?))
681        })
682        .collect::<Result<Vec<_>, std::io::Error>>();
683    let Ok(entries) = entries else {
684        return use_walker();
685    };
686    if entries.iter().any(|(_, file_type)| !file_type.is_file() && !file_type.is_dir()) {
687        return use_walker();
688    }
689
690    // Drop directory handles before recursing; keep native entry order in the result.
691    let entries: Vec<_> = entries
692        .into_par_iter()
693        .map(|(path, file_type)| {
694            if fallback.load(Ordering::Relaxed) {
695                LoadedDirectoryEntry::Directory(None)
696            } else if file_type.is_dir() {
697                if is_pruned(&path) {
698                    LoadedDirectoryEntry::File(None)
699                } else {
700                    LoadedDirectoryEntry::Directory(try_load_directory_parallel(
701                        &path,
702                        specificity,
703                        load_path,
704                        is_pruned,
705                        fallback,
706                        depth + 1,
707                    ))
708                }
709            } else {
710                LoadedDirectoryEntry::File(load_path((path, specificity, false)))
711            }
712        })
713        .collect();
714    if fallback.load(Ordering::Relaxed) {
715        return None;
716    }
717
718    let mut files = Vec::new();
719    for entry in entries {
720        match entry {
721            LoadedDirectoryEntry::File(Some(Ok(file))) => files.push(file),
722            LoadedDirectoryEntry::Directory(Some(Ok(children))) => files.extend(children),
723            LoadedDirectoryEntry::File(Some(Err(error))) | LoadedDirectoryEntry::Directory(Some(Err(error))) => {
724                return Some(Err(error));
725            }
726            LoadedDirectoryEntry::File(None) | LoadedDirectoryEntry::Directory(None) => {}
727        }
728    }
729
730    Some(Ok(files))
731}
732
733fn workspace_relative_string(path: &Path, workspace: &Path) -> String {
734    let relative = path.trim_prefix(workspace).to_string_lossy();
735    #[cfg(windows)]
736    {
737        relative.replace('\\', "/")
738    }
739    #[cfg(not(windows))]
740    {
741        relative.into_owned()
742    }
743}
744
745fn is_pruned_directory(
746    path: &Path,
747    workspace: &Path,
748    canonical_excludes: &[String],
749    dir_prune_globs: &GlobSet,
750) -> bool {
751    if let Some(path) = path.to_str()
752        && canonical_excludes.iter().any(|excluded| {
753            path.starts_with(excluded.as_str())
754                && matches!(path.as_bytes().get(excluded.len()), None | Some(&b'/' | &b'\\'))
755        })
756    {
757        return true;
758    }
759
760    !dir_prune_globs.is_empty()
761        && (dir_prune_globs.is_match(path) || dir_prune_globs.is_match(workspace_relative_string(path, workspace)))
762}
763
764fn warn_walk_error(error: &walkdir::Error, fallback: &Path) {
765    let path = error.path().unwrap_or(fallback).display();
766    if let Some(ancestor) = error.loop_ancestor() {
767        tracing::warn!("Skipping symlink loop at `{path}`: link cycles back to `{}`.", ancestor.display());
768    } else {
769        tracing::warn!("Failed to walk `{path}`: {error}. Entry will be skipped.");
770    }
771}
772
773fn bump_spec(slot: &mut Option<usize>, s: usize) {
774    *slot = Some(slot.map_or(s, |e| e.max(s)));
775}
776
777/// Picks the final [`FileType`] for a file that matched configured base paths in one or
778/// more tiers.
779///
780/// Each argument carries the maximum specificity of any matching base path in that tier, or
781/// `None` if no base path in that tier matched. Vendored wins over Host at equal-or-more
782/// specificity; Host wins only when strictly more specific. Patch beats Vendored
783/// unconditionally; Patch beats Host only when strictly more specific. When nothing matches
784/// the result is `Host`.
785pub(crate) fn resolve_file_type(
786    host_spec: Option<usize>,
787    vendored_spec: Option<usize>,
788    patch_spec: Option<usize>,
789) -> FileType {
790    let mut decision: Option<(FileType, usize)> = host_spec.map(|s| (FileType::Host, s));
791
792    if let Some(v) = vendored_spec {
793        decision = match decision {
794            Some((FileType::Host, h)) if v < h => decision,
795            _ => Some((FileType::Vendored, v)),
796        };
797    }
798
799    if let Some(p) = patch_spec {
800        decision = match decision {
801            Some((FileType::Host | FileType::Patch, e)) if p <= e => decision,
802            _ => Some((FileType::Patch, p)),
803        };
804    }
805
806    decision.map(|(ft, _)| ft).unwrap_or(FileType::Host)
807}
808
809/// Calculates how specific a configured base path or glob pattern is for conflict resolution.
810///
811/// Examples:
812///
813/// - "src/b.php" matching src/b.php: ~2000 (exact file, 2 components)
814/// - "src/" matching src/b.php: ~100 (directory, 1 component)
815/// - "src" matching src/b.php: ~100 (directory, 1 component)
816pub(crate) fn calculate_pattern_specificity(pattern: &[u8]) -> usize {
817    let pattern_path = bytes_to_path(pattern);
818
819    let component_count = pattern_path.components().count();
820    let is_glob =
821        pattern.contains(&b'*') || pattern.contains(&b'?') || pattern.contains(&b'[') || pattern.contains(&b'{');
822
823    if is_glob {
824        let non_wildcard_components = pattern_path
825            .components()
826            .filter(|c| {
827                let s = c.as_os_str().to_string_lossy();
828                !s.contains('*') && !s.contains('?') && !s.contains('[') && !s.contains('{')
829            })
830            .count();
831        non_wildcard_components * 10
832    } else if pattern_path.is_file()
833        || pattern_path.extension().is_some()
834        || pattern.rsplit(|&b| b == b'.').next().is_some_and(|ext| ext.eq_ignore_ascii_case(b"php"))
835    {
836        component_count * 1000
837    } else {
838        component_count * 100
839    }
840}
841
842#[cfg(test)]
843mod resolution_tests {
844    use super::*;
845
846    #[test]
847    fn defaults_to_host_when_nothing_matches() {
848        assert_eq!(resolve_file_type(None, None, None), FileType::Host);
849    }
850
851    #[test]
852    fn host_only_match_yields_host() {
853        assert_eq!(resolve_file_type(Some(100), None, None), FileType::Host);
854    }
855
856    #[test]
857    fn vendored_only_match_yields_vendored() {
858        assert_eq!(resolve_file_type(None, Some(100), None), FileType::Vendored);
859    }
860
861    #[test]
862    fn patch_only_match_yields_patch() {
863        assert_eq!(resolve_file_type(None, None, Some(100)), FileType::Patch);
864    }
865
866    #[test]
867    fn vendored_beats_host_at_equal_specificity() {
868        assert_eq!(resolve_file_type(Some(100), Some(100), None), FileType::Vendored);
869    }
870
871    #[test]
872    fn vendored_beats_host_when_more_specific() {
873        assert_eq!(resolve_file_type(Some(100), Some(2000), None), FileType::Vendored);
874    }
875
876    #[test]
877    fn host_beats_vendored_only_when_strictly_more_specific() {
878        assert_eq!(resolve_file_type(Some(2000), Some(100), None), FileType::Host);
879    }
880
881    #[test]
882    fn patch_beats_vendored_unconditionally() {
883        assert_eq!(resolve_file_type(None, Some(2000), Some(100)), FileType::Patch);
884    }
885
886    #[test]
887    fn host_beats_patch_at_equal_specificity() {
888        assert_eq!(resolve_file_type(Some(100), None, Some(100)), FileType::Host);
889    }
890
891    #[test]
892    fn patch_beats_host_when_strictly_more_specific() {
893        assert_eq!(resolve_file_type(Some(100), None, Some(2000)), FileType::Patch);
894    }
895
896    #[test]
897    fn patch_beats_host_that_won_over_vendored() {
898        assert_eq!(resolve_file_type(Some(100), Some(2000), Some(50)), FileType::Patch);
899    }
900
901    #[test]
902    fn exact_file_path_beats_directory_at_same_component_count() {
903        assert!(calculate_pattern_specificity(b"src/foo.php") > calculate_pattern_specificity(b"src/foo"));
904    }
905
906    #[test]
907    fn directory_beats_glob_at_same_non_wildcard_count() {
908        assert!(calculate_pattern_specificity(b"src/") > calculate_pattern_specificity(b"src/**/*.php"));
909    }
910
911    #[test]
912    fn deeper_path_beats_shallower_at_same_kind() {
913        assert!(calculate_pattern_specificity(b"src/inner/") > calculate_pattern_specificity(b"src/"));
914    }
915
916    #[test]
917    fn extensionless_phpish_pattern_treated_as_file() {
918        assert_eq!(calculate_pattern_specificity(b"src/foo.PHP"), calculate_pattern_specificity(b"src/foo.php"),);
919    }
920}
921
922#[cfg(test)]
923#[allow(clippy::unwrap_used, clippy::expect_used)]
924mod tests {
925    use super::*;
926    use crate::DatabaseReader;
927    use crate::GlobSettings;
928    use std::borrow::Cow;
929    use tempfile::TempDir;
930
931    fn create_test_config(temp_dir: &TempDir, paths: Vec<&str>, includes: Vec<&str>) -> DatabaseConfiguration<'static> {
932        create_test_config_with_patches(temp_dir, paths, includes, vec![])
933    }
934
935    fn create_test_config_with_patches(
936        temp_dir: &TempDir,
937        paths: Vec<&str>,
938        includes: Vec<&str>,
939        patches: Vec<&str>,
940    ) -> DatabaseConfiguration<'static> {
941        // Normalize path separators to platform-specific separators
942        let normalize = |s: &str| s.replace('/', std::path::MAIN_SEPARATOR_STR);
943
944        DatabaseConfiguration {
945            workspace: Cow::Owned(temp_dir.path().to_path_buf()),
946            paths: paths.into_iter().map(|s| Cow::Owned(normalize(s).into_bytes())).collect(),
947            includes: includes.into_iter().map(|s| Cow::Owned(normalize(s).into_bytes())).collect(),
948            patches: patches.into_iter().map(|s| Cow::Owned(normalize(s).into_bytes())).collect(),
949            excludes: vec![],
950            extensions: vec![Cow::Borrowed(b"php")],
951            glob: GlobSettings::default(),
952        }
953    }
954
955    /// Returns the file's logical name as a lossy UTF-8 string for assertion matching.
956    fn name_str(name: &[u8]) -> std::borrow::Cow<'_, str> {
957        String::from_utf8_lossy(name)
958    }
959
960    fn create_test_file(temp_dir: &TempDir, relative_path: &str, content: &str) {
961        let file_path = temp_dir.path().join(relative_path);
962        if let Some(parent) = file_path.parent() {
963            std::fs::create_dir_all(parent).unwrap();
964        }
965        std::fs::write(file_path, content).unwrap();
966    }
967
968    #[test]
969    fn test_batched_walk_keeps_file_order() {
970        let temp_dir = TempDir::new().unwrap();
971        for index in 0..385 {
972            create_test_file(&temp_dir, &format!("src/nested/{}/{index}.php", index / 64), "<?php");
973        }
974
975        let root = temp_dir.path().join("src/nested").canonicalize().unwrap();
976        let expected: Vec<_> = WalkDir::new(root)
977            .follow_links(true)
978            .into_iter()
979            .map(Result::unwrap)
980            .filter(|entry| !entry.file_type().is_dir())
981            .map(walkdir::DirEntry::into_path)
982            .collect();
983
984        let config = create_test_config(&temp_dir, vec!["src"], vec![]);
985        let loader = DatabaseLoader::new(config);
986        let extensions = std::iter::once(OsString::from("php")).collect();
987        let globs = GlobSet::empty();
988        let path_excludes = HashSet::default();
989        // ?
990        for threads in [1, 4] {
991            let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap();
992            let files = pool
993                .install(|| {
994                    loader.load_paths(
995                        &loader.configuration.paths,
996                        FileType::Host,
997                        &extensions,
998                        &globs,
999                        &globs,
1000                        &path_excludes,
1001                    )
1002                })
1003                .unwrap();
1004            let actual: Vec<_> = files.into_iter().map(|entry| entry.file.path.unwrap()).collect();
1005            assert_eq!(actual, expected);
1006        }
1007    }
1008
1009    #[test]
1010    fn test_nested_files_match_with_one_and_many_threads() {
1011        let temp_dir = TempDir::new().unwrap();
1012        create_test_file(&temp_dir, "src/deep/a.php", "<?php // host");
1013        create_test_file(&temp_dir, "src/deep/b.php", "<?php // vendor");
1014        create_test_file(&temp_dir, "src/deep/patch/c.php", "<?php // patch");
1015        create_test_file(&temp_dir, "src/deep/skip/d.php", "<?php // excluded");
1016        create_test_file(&temp_dir, "src/deep/e.txt", "<?php // wrong extension");
1017
1018        let mut config = create_test_config_with_patches(
1019            &temp_dir,
1020            vec!["src", "src/deep/a.php"],
1021            vec!["src/deep"],
1022            vec!["src/deep/patch"],
1023        );
1024        config.excludes.push(Exclusion::Pattern(Cow::Borrowed("src/deep/skip/**")));
1025
1026        for threads in [1, 4] {
1027            let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap();
1028            let db = pool.install(|| {
1029                DatabaseLoader::new(config.clone())
1030                    .with_stdin_override(b"src/deep/a.php", b"<?php // edited".to_vec())
1031                    .load()
1032                    .unwrap()
1033            });
1034            let mut files =
1035                db.files().map(|file| (file.name.to_vec(), file.file_type, file.contents.to_vec())).collect::<Vec<_>>();
1036            files.sort_by(|left, right| left.0.cmp(&right.0));
1037
1038            assert_eq!(
1039                files,
1040                vec![
1041                    (b"src/deep/a.php".to_vec(), FileType::Host, b"<?php // edited".to_vec()),
1042                    (b"src/deep/b.php".to_vec(), FileType::Vendored, b"<?php // vendor".to_vec()),
1043                    (b"src/deep/patch/c.php".to_vec(), FileType::Patch, b"<?php // patch".to_vec()),
1044                ],
1045            );
1046        }
1047    }
1048
1049    #[test]
1050    fn test_exact_file_vs_directory() {
1051        let temp_dir = TempDir::new().unwrap();
1052
1053        create_test_file(&temp_dir, "src/b.php", "<?php");
1054        create_test_file(&temp_dir, "src/a.php", "<?php");
1055
1056        let config = create_test_config(&temp_dir, vec!["src/b.php"], vec!["src/"]);
1057        let loader = DatabaseLoader::new(config);
1058        let db = loader.load().unwrap();
1059
1060        let b_file = db.files().find(|f| name_str(&f.name).contains("b.php")).unwrap();
1061        assert_eq!(b_file.file_type, FileType::Host, "src/b.php should be Host (exact file beats directory)");
1062
1063        let a_file = db.files().find(|f| name_str(&f.name).contains("a.php")).unwrap();
1064        assert_eq!(a_file.file_type, FileType::Vendored, "src/a.php should be Vendored");
1065    }
1066
1067    #[test]
1068    fn test_deeper_vs_shallower_directory() {
1069        let temp_dir = TempDir::new().unwrap();
1070
1071        create_test_file(&temp_dir, "src/foo/bar.php", "<?php");
1072
1073        let config = create_test_config(&temp_dir, vec!["src/foo/"], vec!["src/"]);
1074        let loader = DatabaseLoader::new(config);
1075        let db = loader.load().unwrap();
1076
1077        let file = db.files().find(|f| name_str(&f.name).contains("bar.php")).unwrap();
1078        assert_eq!(file.file_type, FileType::Host, "Deeper directory pattern should win");
1079    }
1080
1081    #[test]
1082    fn test_exact_file_vs_glob() {
1083        let temp_dir = TempDir::new().unwrap();
1084
1085        create_test_file(&temp_dir, "src/b.php", "<?php");
1086
1087        let config = create_test_config(&temp_dir, vec!["src/b.php"], vec!["src/*.php"]);
1088        let loader = DatabaseLoader::new(config);
1089        let db = loader.load().unwrap();
1090
1091        let file = db.files().find(|f| name_str(&f.name).contains("b.php")).unwrap();
1092        assert_eq!(file.file_type, FileType::Host, "Exact file should beat glob pattern");
1093    }
1094
1095    #[test]
1096    fn test_equal_specificity_includes_wins() {
1097        let temp_dir = TempDir::new().unwrap();
1098
1099        create_test_file(&temp_dir, "src/a.php", "<?php");
1100
1101        let config = create_test_config(&temp_dir, vec!["src/"], vec!["src/"]);
1102        let loader = DatabaseLoader::new(config);
1103        let db = loader.load().unwrap();
1104
1105        let file = db.files().find(|f| name_str(&f.name).contains("a.php")).unwrap();
1106        assert_eq!(file.file_type, FileType::Vendored, "Equal specificity: includes should win");
1107    }
1108
1109    #[test]
1110    fn test_complex_scenario_from_bug_report() {
1111        let temp_dir = TempDir::new().unwrap();
1112
1113        create_test_file(&temp_dir, "src/a.php", "<?php");
1114        create_test_file(&temp_dir, "src/b.php", "<?php");
1115        create_test_file(&temp_dir, "src/c/d.php", "<?php");
1116        create_test_file(&temp_dir, "src/c/e.php", "<?php");
1117        create_test_file(&temp_dir, "vendor/lib1.php", "<?php");
1118        create_test_file(&temp_dir, "vendor/lib2.php", "<?php");
1119
1120        let config = create_test_config(&temp_dir, vec!["src/b.php"], vec!["vendor", "src/c", "src/"]);
1121        let loader = DatabaseLoader::new(config);
1122        let db = loader.load().unwrap();
1123
1124        let b_file = db
1125            .files()
1126            .find(|f| name_str(&f.name).contains("src/b.php") || name_str(&f.name).ends_with("b.php"))
1127            .unwrap();
1128        assert_eq!(b_file.file_type, FileType::Host, "src/b.php should be Host in bug scenario");
1129
1130        let d_file = db.files().find(|f| name_str(&f.name).contains("d.php")).unwrap();
1131        assert_eq!(d_file.file_type, FileType::Vendored, "src/c/d.php should be Vendored");
1132
1133        let lib_file = db.files().find(|f| name_str(&f.name).contains("lib1.php")).unwrap();
1134        assert_eq!(lib_file.file_type, FileType::Vendored, "vendor/lib1.php should be Vendored");
1135    }
1136
1137    #[test]
1138    fn test_files_only_in_paths() {
1139        let temp_dir = TempDir::new().unwrap();
1140
1141        create_test_file(&temp_dir, "src/a.php", "<?php");
1142
1143        let config = create_test_config(&temp_dir, vec!["src/"], vec![]);
1144        let loader = DatabaseLoader::new(config);
1145        let db = loader.load().unwrap();
1146
1147        let file = db.files().find(|f| name_str(&f.name).contains("a.php")).unwrap();
1148        assert_eq!(file.file_type, FileType::Host, "File only in paths should be Host");
1149    }
1150
1151    #[test]
1152    fn test_files_only_in_includes() {
1153        let temp_dir = TempDir::new().unwrap();
1154
1155        create_test_file(&temp_dir, "vendor/lib.php", "<?php");
1156
1157        let config = create_test_config(&temp_dir, vec![], vec!["vendor/"]);
1158        let loader = DatabaseLoader::new(config);
1159        let db = loader.load().unwrap();
1160
1161        let file = db.files().find(|f| name_str(&f.name).contains("lib.php")).unwrap();
1162        assert_eq!(file.file_type, FileType::Vendored, "File only in includes should be Vendored");
1163    }
1164
1165    #[test]
1166    fn test_stdin_override_replaces_file_content() {
1167        let temp_dir = TempDir::new().unwrap();
1168        create_test_file(&temp_dir, "src/foo.php", "<?php\n// on disk");
1169
1170        let config = create_test_config(&temp_dir, vec!["src/"], vec![]);
1171        let loader = DatabaseLoader::new(config).with_stdin_override("src/foo.php", b"<?php\n// from stdin".to_vec());
1172        let db = loader.load().unwrap();
1173
1174        let file = db.files().find(|f| name_str(&f.name).contains("foo.php")).unwrap();
1175        assert_eq!(
1176            file.contents.as_ref(),
1177            b"<?php\n// from stdin",
1178            "stdin override content should be used instead of disk"
1179        );
1180    }
1181
1182    #[test]
1183    fn test_glob_excludes_match_workspace_relative_paths() {
1184        let temp_dir = TempDir::new().unwrap();
1185
1186        create_test_file(&temp_dir, "src/Absences/Foo/Foo.php", "<?php");
1187        create_test_file(&temp_dir, "src/Absences/Test/Faker/Provider/AbsencesProvider.php", "<?php");
1188        create_test_file(&temp_dir, "src/Calendar/Test/Helper.php", "<?php");
1189
1190        let mut config = create_test_config(&temp_dir, vec!["src"], vec![]);
1191        config.excludes = vec![Exclusion::Pattern(Cow::Borrowed("src/*/Test/**"))];
1192
1193        let loader = DatabaseLoader::new(config);
1194        let db = loader.load().unwrap();
1195
1196        let names: Vec<String> = db.files().map(|f| name_str(&f.name).into_owned()).collect();
1197        assert!(names.iter().any(|n| n.ends_with("src/Absences/Foo/Foo.php")), "non-Test file should be loaded");
1198        assert!(
1199            !names.iter().any(|n| n.contains("src/Absences/Test/")),
1200            "files under src/*/Test/** should be excluded, got {names:?}"
1201        );
1202        assert!(
1203            !names.iter().any(|n| n.contains("src/Calendar/Test/")),
1204            "files under src/*/Test/** should be excluded, got {names:?}"
1205        );
1206    }
1207
1208    #[test]
1209    fn test_glob_excludes_match_legacy_absolute_prefix_patterns() {
1210        let temp_dir = TempDir::new().unwrap();
1211
1212        create_test_file(&temp_dir, "packages/foo/src/main.php", "<?php");
1213        create_test_file(&temp_dir, "packages/foo/vendor/lib.php", "<?php");
1214
1215        let mut config = create_test_config(&temp_dir, vec!["packages"], vec![]);
1216        config.excludes = vec![Exclusion::Pattern(Cow::Borrowed("*/packages/**/vendor/*"))];
1217
1218        let loader = DatabaseLoader::new(config);
1219        let db = loader.load().unwrap();
1220
1221        let names: Vec<String> = db.files().map(|f| name_str(&f.name).into_owned()).collect();
1222        assert!(names.iter().any(|n| n.ends_with("packages/foo/src/main.php")));
1223        assert!(
1224            !names.iter().any(|n| n.contains("/vendor/")),
1225            "legacy `*/packages/**/vendor/*` style should still exclude vendor files, got {names:?}"
1226        );
1227    }
1228
1229    #[test]
1230    fn test_glob_dir_prune_skips_relative_directories() {
1231        let temp_dir = TempDir::new().unwrap();
1232
1233        create_test_file(&temp_dir, "vendor/slevomat/coding-standard/main.php", "<?php");
1234        create_test_file(&temp_dir, "vendor/slevomat/coding-standard/tests/Sniffs/Foo.php", "<?php");
1235        create_test_file(&temp_dir, "vendor/another/lib.php", "<?php");
1236
1237        let mut config = create_test_config(&temp_dir, vec![], vec!["vendor"]);
1238        config.excludes = vec![Exclusion::Pattern(Cow::Borrowed("vendor/**/tests/**"))];
1239
1240        let loader = DatabaseLoader::new(config);
1241        let db = loader.load().unwrap();
1242
1243        let names: Vec<String> = db.files().map(|f| name_str(&f.name).into_owned()).collect();
1244        assert!(names.iter().any(|n| n.ends_with("vendor/slevomat/coding-standard/main.php")));
1245        assert!(names.iter().any(|n| n.ends_with("vendor/another/lib.php")));
1246        assert!(
1247            !names.iter().any(|n| n.contains("/tests/")),
1248            "files under vendor/**/tests/** should be pruned, got {names:?}"
1249        );
1250    }
1251
1252    #[test]
1253    fn test_stdin_override_adds_file_when_not_on_disk() {
1254        let temp_dir = TempDir::new().unwrap();
1255        create_test_file(&temp_dir, "src/.gitkeep", "");
1256
1257        let config = create_test_config(&temp_dir, vec!["src/"], vec![]);
1258        let loader =
1259            DatabaseLoader::new(config).with_stdin_override("src/unsaved.php", b"<?php\n// unsaved buffer".to_vec());
1260        let db = loader.load().unwrap();
1261
1262        let file = db.files().find(|f| name_str(&f.name).contains("unsaved.php")).unwrap();
1263        assert_eq!(file.file_type, FileType::Host);
1264        assert_eq!(file.contents.as_ref(), b"<?php\n// unsaved buffer");
1265    }
1266
1267    #[test]
1268    fn test_stdin_override_accepts_non_utf8_content() {
1269        let temp_dir = TempDir::new().unwrap();
1270        create_test_file(&temp_dir, "src/.gitkeep", "");
1271
1272        let config = create_test_config(&temp_dir, vec!["src/"], vec![]);
1273        // PHP identifiers are binary-safe, so a buffer piped in via `--stdin-input` may not
1274        // be valid UTF-8. The loaded file must carry those bytes through verbatim.
1275        let content = b"<?php\n\nfunction f\xC9\xFF(): void {}\n".to_vec();
1276        assert!(std::str::from_utf8(&content).is_err(), "test buffer must contain non-UTF-8 bytes");
1277
1278        let loader = DatabaseLoader::new(config).with_stdin_override("src/buffer.php", content.clone());
1279        let db = loader.load().unwrap();
1280
1281        let file = db.files().find(|f| name_str(&f.name).contains("buffer.php")).unwrap();
1282        assert_eq!(file.contents.as_ref(), content.as_slice());
1283    }
1284
1285    #[cfg(unix)]
1286    #[test]
1287    fn test_symlinked_file_under_include_is_loaded() {
1288        let temp_dir = TempDir::new().unwrap();
1289        let external = TempDir::new().unwrap();
1290
1291        create_test_file(&external, "Bar.php", "<?php class Bar {}\n");
1292        std::fs::create_dir_all(temp_dir.path().join("vendor")).unwrap();
1293        std::os::unix::fs::symlink(external.path().join("Bar.php"), temp_dir.path().join("vendor/Bar.php")).unwrap();
1294
1295        let config = create_test_config(&temp_dir, vec![], vec!["vendor/"]);
1296        let db = DatabaseLoader::new(config).load().unwrap();
1297
1298        let bar = db.files().find(|f| name_str(&f.name).contains("Bar.php"));
1299        assert!(bar.is_some(), "symlinked Bar.php should be loaded via include = ['vendor/']");
1300    }
1301
1302    #[cfg(unix)]
1303    #[test]
1304    fn test_explicit_symlinked_file_keeps_workspace_relative_name() {
1305        let temp_dir = TempDir::new().unwrap();
1306        let external = TempDir::new().unwrap();
1307
1308        create_test_file(&external, "Foo.php", "<?php class Foo {}\n");
1309        std::fs::create_dir_all(temp_dir.path().join("src")).unwrap();
1310        std::os::unix::fs::symlink(external.path().join("Foo.php"), temp_dir.path().join("src/Foo.php")).unwrap();
1311
1312        let config = create_test_config(&temp_dir, vec!["src/Foo.php"], vec![]);
1313        let db = DatabaseLoader::new(config).load().unwrap();
1314
1315        let names: Vec<_> = db.files().map(|f| name_str(&f.name).into_owned()).collect();
1316        assert_eq!(names, ["src/Foo.php"], "an explicitly named symlink should keep its workspace-relative name");
1317    }
1318
1319    #[cfg(unix)]
1320    #[test]
1321    fn test_explicit_file_under_symlinked_directory_keeps_workspace_relative_name() {
1322        let temp_dir = TempDir::new().unwrap();
1323        let external = TempDir::new().unwrap();
1324
1325        create_test_file(&external, "Foo.php", "<?php class Foo {}\n");
1326        std::os::unix::fs::symlink(external.path(), temp_dir.path().join("src")).unwrap();
1327
1328        let config = create_test_config(&temp_dir, vec!["src/Foo.php"], vec![]);
1329        let db = DatabaseLoader::new(config).load().unwrap();
1330
1331        let names: Vec<_> = db.files().map(|f| name_str(&f.name).into_owned()).collect();
1332        assert_eq!(
1333            names,
1334            ["src/Foo.php"],
1335            "a file below a symlinked directory should keep its workspace-relative name"
1336        );
1337    }
1338
1339    #[cfg(unix)]
1340    #[test]
1341    fn test_symlinked_directory_under_include_is_descended() {
1342        let temp_dir = TempDir::new().unwrap();
1343        let external = TempDir::new().unwrap();
1344
1345        create_test_file(&external, "src/Foo.php", "<?php class Foo {}\n");
1346        create_test_file(&external, "src/Bar.php", "<?php class Bar {}\n");
1347
1348        std::fs::create_dir_all(temp_dir.path().join("vendor")).unwrap();
1349        std::os::unix::fs::symlink(external.path(), temp_dir.path().join("vendor/example-package")).unwrap();
1350
1351        let config = create_test_config(&temp_dir, vec![], vec!["vendor/"]);
1352        let db = DatabaseLoader::new(config).load().unwrap();
1353
1354        assert!(db.files().any(|f| name_str(&f.name).contains("Foo.php")), "Foo.php inside symlinked dir not found");
1355        assert!(db.files().any(|f| name_str(&f.name).contains("Bar.php")), "Bar.php inside symlinked dir not found");
1356    }
1357
1358    #[cfg(unix)]
1359    #[test]
1360    fn directory_walks_report_empty_symlinks_without_changing_loaded_files() {
1361        let temp_dir = TempDir::new().unwrap();
1362        let external = TempDir::new().unwrap();
1363        create_test_file(&temp_dir, "vendor/Kept.php", "<?php class Kept {}\n");
1364        std::fs::create_dir_all(temp_dir.path().join("vendor/deep")).unwrap();
1365        for path in ["vendor/shallow", "vendor/deep/package"] {
1366            std::os::unix::fs::symlink(external.path(), temp_dir.path().join(path)).unwrap();
1367        }
1368        let config = create_test_config(&temp_dir, vec![], vec!["vendor/"]);
1369        for threads in [1, 4] {
1370            let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap();
1371            let (database, mut symlinks) =
1372                pool.install(|| DatabaseLoader::new(config.clone()).load_with_directory_symlinks().unwrap());
1373            symlinks.sort();
1374            let root = temp_dir.path().canonicalize().unwrap();
1375            assert_eq!(symlinks, [root.join("vendor/deep/package"), root.join("vendor/shallow")]);
1376            let ordinary = pool.install(|| DatabaseLoader::new(config.clone()).load().unwrap());
1377            let summarize = |database: &Database<'_>| {
1378                database
1379                    .files()
1380                    .map(|file| (file.name.to_vec(), file.file_type, file.contents.to_vec()))
1381                    .collect::<Vec<_>>()
1382            };
1383            assert_eq!(summarize(&database), summarize(&ordinary));
1384        }
1385    }
1386
1387    #[cfg(unix)]
1388    #[test]
1389    fn directory_walks_report_dangling_symlinks_without_changing_loaded_files() {
1390        let temp_dir = TempDir::new().unwrap();
1391        let external = TempDir::new().unwrap();
1392        create_test_file(&temp_dir, "vendor/Kept.php", "<?php class Kept {}\n");
1393        create_test_file(&external, "blocked", "not a directory");
1394        std::fs::create_dir_all(temp_dir.path().join("vendor/deep")).unwrap();
1395        for (link, target) in [
1396            ("vendor/shallow", external.path().join("missing")),
1397            ("vendor/deep/relative", PathBuf::from("../../missing")),
1398            ("vendor/deep/blocked", external.path().join("blocked/child")),
1399        ] {
1400            std::os::unix::fs::symlink(target, temp_dir.path().join(link)).unwrap();
1401        }
1402        let config = create_test_config(&temp_dir, vec![], vec!["vendor/"]);
1403        let root = temp_dir.path().canonicalize().unwrap();
1404        for threads in [1, 4] {
1405            let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap();
1406            let (database, mut symlinks) =
1407                pool.install(|| DatabaseLoader::new(config.clone()).load_with_directory_symlinks().unwrap());
1408            symlinks.sort();
1409            assert_eq!(
1410                symlinks,
1411                [root.join("vendor/deep/blocked"), root.join("vendor/deep/relative"), root.join("vendor/shallow")]
1412            );
1413
1414            let ordinary = pool.install(|| DatabaseLoader::new(config.clone()).load().unwrap());
1415            let summarize = |database: &Database<'_>| {
1416                database
1417                    .files()
1418                    .map(|file| (file.name.to_vec(), file.file_type, file.contents.to_vec()))
1419                    .collect::<Vec<_>>()
1420            };
1421
1422            assert_eq!(summarize(&database), summarize(&ordinary));
1423        }
1424    }
1425
1426    #[cfg(unix)]
1427    #[test]
1428    fn file_only_globs_do_not_discover_empty_directory_symlinks() {
1429        let temp_dir = TempDir::new().unwrap();
1430        let external = TempDir::new().unwrap();
1431        std::fs::create_dir_all(temp_dir.path().join("vendor")).unwrap();
1432        std::os::unix::fs::symlink(external.path(), temp_dir.path().join("vendor/package")).unwrap();
1433        let config = create_test_config(&temp_dir, vec![], vec!["vendor/**/*.php"]);
1434        let (database, symlinks) = DatabaseLoader::new(config).load_with_directory_symlinks().unwrap();
1435        assert!(database.files().next().is_none());
1436        assert!(symlinks.is_empty());
1437    }
1438
1439    #[cfg(unix)]
1440    #[test]
1441    fn test_symlink_cycle_is_warned_and_skipped() {
1442        let temp_dir = TempDir::new().unwrap();
1443        create_test_file(&temp_dir, "src/nested/Real.php", "<?php class Real {}\n");
1444        std::os::unix::fs::symlink(temp_dir.path().join("src/nested"), temp_dir.path().join("src/nested/loop"))
1445            .unwrap();
1446
1447        let config = create_test_config(&temp_dir, vec![], vec!["src/"]);
1448        for threads in [1, 4] {
1449            let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap();
1450            let db = pool.install(|| {
1451                DatabaseLoader::new(config.clone()).load().expect("symlink cycle should not abort the load")
1452            });
1453            let names = db.files().map(|file| file.name.to_vec()).collect::<Vec<_>>();
1454            assert_eq!(names, [b"src/nested/Real.php".to_vec()]);
1455        }
1456    }
1457
1458    #[test]
1459    fn test_exact_extensionless_file_is_loaded() {
1460        let temp_dir = TempDir::new().unwrap();
1461        create_test_file(&temp_dir, "bin/console", "<?php\n// entrypoint");
1462
1463        // `bin/console` has no extension, so it would be filtered out when discovered by
1464        // walking a directory. Naming it exactly must bypass the extension requirement.
1465        let config = create_test_config(&temp_dir, vec!["bin/console"], vec![]);
1466        let db = DatabaseLoader::new(config).load().unwrap();
1467
1468        let file = db.files().find(|f| name_str(&f.name).ends_with("bin/console")).unwrap();
1469        assert_eq!(file.file_type, FileType::Host);
1470        assert_eq!(file.contents.as_ref(), b"<?php\n// entrypoint");
1471    }
1472
1473    #[test]
1474    fn test_extensionless_file_in_directory_is_skipped() {
1475        let temp_dir = TempDir::new().unwrap();
1476        create_test_file(&temp_dir, "bin/console", "<?php");
1477        create_test_file(&temp_dir, "bin/run.php", "<?php");
1478
1479        // Walking the directory must still honor the extension filter: only `run.php` loads.
1480        let config = create_test_config(&temp_dir, vec!["bin"], vec![]);
1481        let db = DatabaseLoader::new(config).load().unwrap();
1482
1483        let names: Vec<String> = db.files().map(|f| name_str(&f.name).into_owned()).collect();
1484        assert!(names.iter().any(|n| n.ends_with("bin/run.php")), "run.php should be loaded, got {names:?}");
1485        assert!(!names.iter().any(|n| n.ends_with("bin/console")), "extensionless console should be skipped");
1486    }
1487
1488    #[test]
1489    fn test_patch_beats_vendored_at_equal_specificity() {
1490        // A file covered by both patches and includes at the same directory-level specificity
1491        // should be classified as Patch, not Vendored.
1492        let temp_dir = TempDir::new().unwrap();
1493        create_test_file(&temp_dir, "lib/Foo.php", "<?php");
1494
1495        let config = create_test_config_with_patches(&temp_dir, vec![], vec!["lib/"], vec!["lib/"]);
1496        let db = DatabaseLoader::new(config).load().unwrap();
1497
1498        let file = db.files().find(|f| String::from_utf8_lossy(&f.name).contains("Foo.php")).unwrap();
1499        assert_eq!(file.file_type, FileType::Patch, "patch should beat vendored at equal specificity");
1500    }
1501
1502    #[test]
1503    fn test_host_beats_patch_at_equal_specificity() {
1504        // When a file is covered by both paths and patches at the same directory-level specificity,
1505        // the host (paths) classification wins.  Patches only override host when strictly more specific.
1506        let temp_dir = TempDir::new().unwrap();
1507        create_test_file(&temp_dir, "src/Foo.php", "<?php");
1508
1509        let config = create_test_config_with_patches(&temp_dir, vec!["src/"], vec![], vec!["src/"]);
1510        let db = DatabaseLoader::new(config).load().unwrap();
1511
1512        let file = db.files().find(|f| String::from_utf8_lossy(&f.name).contains("Foo.php")).unwrap();
1513        assert_eq!(file.file_type, FileType::Host, "host should beat patch at equal specificity");
1514    }
1515
1516    #[test]
1517    fn test_patch_beats_host_when_strictly_more_specific() {
1518        // An exact-file patch pattern has higher specificity than a directory paths pattern,
1519        // so the patch wins and the file is treated as Patch rather than Host.
1520        let temp_dir = TempDir::new().unwrap();
1521        create_test_file(&temp_dir, "src/Foo.php", "<?php");
1522        create_test_file(&temp_dir, "src/Bar.php", "<?php");
1523
1524        // Patch covers only Foo.php exactly; paths covers the whole directory.
1525        let config = create_test_config_with_patches(&temp_dir, vec!["src/"], vec![], vec!["src/Foo.php"]);
1526        let db = DatabaseLoader::new(config).load().unwrap();
1527
1528        let foo = db.files().find(|f| String::from_utf8_lossy(&f.name).contains("Foo.php")).unwrap();
1529        assert_eq!(foo.file_type, FileType::Patch, "exact-file patch should beat directory-level host pattern");
1530
1531        let bar = db.files().find(|f| String::from_utf8_lossy(&f.name).contains("Bar.php")).unwrap();
1532        assert_eq!(bar.file_type, FileType::Host, "file not covered by patch should remain Host");
1533    }
1534
1535    #[test]
1536    fn git_ignored_sources_load_as_vendored() {
1537        let temp_dir = TempDir::new().unwrap();
1538        std::fs::create_dir_all(temp_dir.path().join(".git")).unwrap();
1539        create_test_file(&temp_dir, ".gitignore", "/vendor/\n.claude/worktrees/\n");
1540        create_test_file(&temp_dir, "src/Service.php", "<?php");
1541        create_test_file(&temp_dir, "vendor/package/Library.php", "<?php");
1542        create_test_file(&temp_dir, ".claude/worktrees/copy/src/Service.php", "<?php");
1543
1544        let root = temp_dir.path().to_string_lossy().into_owned();
1545        let ignores = Arc::new(GitIgnores::discover_with_global(temp_dir.path(), None).unwrap());
1546        let db = DatabaseLoader::new(create_test_config(&temp_dir, vec![&root], vec![]))
1547            .with_git_ignores(ignores)
1548            .load()
1549            .unwrap();
1550
1551        let types: HashMap<String, FileType> =
1552            db.files().map(|file| (name_str(&file.name).into_owned(), file.file_type)).collect();
1553        assert_eq!(types.get("src/Service.php"), Some(&FileType::Host));
1554        assert_eq!(types.get("vendor/package/Library.php"), Some(&FileType::Vendored));
1555        assert_eq!(types.get(".claude/worktrees/copy/src/Service.php"), Some(&FileType::Vendored));
1556    }
1557}