Skip to main content

mago_database/
loader.rs

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