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