use std::borrow::Cow;
use std::collections::hash_map::Entry;
use std::ffi::OsString;
use std::io::ErrorKind;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::PoisonError;
#[cfg(unix)]
use std::sync::atomic::AtomicBool;
#[cfg(unix)]
use std::sync::atomic::Ordering;
use foldhash::HashMap;
use foldhash::HashSet;
use globset::GlobSet;
use rayon::prelude::*;
use walkdir::WalkDir;
use crate::Database;
use crate::DatabaseConfiguration;
use crate::error::DatabaseError;
use crate::exclusion::Exclusion;
use crate::file::File;
use crate::file::FileId;
use crate::file::FileType;
use crate::git::GitIgnores;
use crate::matcher::build_glob_set;
use crate::matcher::directory_patterns;
use crate::utils::bytes_to_os_str;
use crate::utils::bytes_to_path;
use crate::utils::bytes_to_string_lossy;
use crate::utils::read_file;
#[derive(Debug)]
struct FileWithSpecificity {
file: File,
specificity: usize,
}
pub struct DatabaseLoader<'config> {
database: Option<Database<'config>>,
configuration: DatabaseConfiguration<'config>,
memory_sources: Vec<(&'static [u8], &'static [u8], FileType)>,
stdin_override: Option<(Cow<'config, [u8]>, Vec<u8>)>,
directory_symlinks: Option<Mutex<HashSet<PathBuf>>>,
git_ignores: Option<Arc<GitIgnores>>,
}
impl<'config> DatabaseLoader<'config> {
#[inline]
#[must_use]
pub fn new(configuration: DatabaseConfiguration<'config>) -> Self {
Self {
configuration,
memory_sources: vec![],
database: None,
stdin_override: None,
directory_symlinks: None,
git_ignores: None,
}
}
#[inline]
#[must_use]
pub fn with_git_ignores(mut self, ignores: Arc<GitIgnores>) -> Self {
self.git_ignores = Some(ignores);
self
}
#[inline]
#[must_use]
pub fn with_database(mut self, database: Database<'config>) -> Self {
self.database = Some(database);
self
}
#[inline]
#[must_use]
pub fn with_stdin_override(mut self, logical_name: impl AsRef<[u8]>, content: Vec<u8>) -> Self {
self.stdin_override = Some((Cow::Owned(logical_name.as_ref().to_vec()), content));
self
}
#[inline]
pub fn add_memory_source(&mut self, name: &'static str, contents: &'static str, file_type: FileType) {
self.memory_sources.push((name.as_bytes(), contents.as_bytes(), file_type));
}
#[inline]
pub fn load(mut self) -> Result<Database<'config>, DatabaseError> {
self.load_inner()
}
pub fn load_with_directory_symlinks(mut self) -> Result<(Database<'config>, Vec<PathBuf>), DatabaseError> {
self.directory_symlinks = Some(Mutex::default());
let database = self.load_inner()?;
let symlinks = self.directory_symlinks.unwrap_or_default().into_inner().unwrap_or_else(PoisonError::into_inner);
Ok((database, symlinks.into_iter().collect()))
}
fn load_inner(&mut self) -> Result<Database<'config>, DatabaseError> {
let mut db = self.database.take().unwrap_or_else(|| Database::new(self.configuration.clone()));
db.configuration = self.configuration.clone();
let extensions_set: HashSet<OsString> =
self.configuration.extensions.iter().map(|s| bytes_to_os_str(s.as_ref()).into_owned()).collect();
let glob_exclude_patterns: Vec<&str> = self
.configuration
.excludes
.iter()
.filter_map(|ex| match ex {
Exclusion::Pattern(pat) => Some(pat.as_ref()),
Exclusion::Path(_) => None,
})
.collect();
let glob_excludes = build_glob_set(glob_exclude_patterns.iter().copied(), self.configuration.glob)?;
let dir_prune_globs =
build_glob_set(directory_patterns(glob_exclude_patterns.iter().copied()), self.configuration.glob)?;
let path_excludes: HashSet<_> = self
.configuration
.excludes
.iter()
.filter_map(|ex| match ex {
Exclusion::Path(p) => Some(p),
Exclusion::Pattern(_) => None,
})
.collect();
let (host_files_with_spec, (vendored_files_with_spec, patch_files_with_spec)) = rayon::join(
|| {
self.load_paths(
&self.configuration.paths,
FileType::Host,
&extensions_set,
&glob_excludes,
&dir_prune_globs,
&path_excludes,
)
},
|| {
rayon::join(
|| {
self.load_paths(
&self.configuration.includes,
FileType::Vendored,
&extensions_set,
&glob_excludes,
&dir_prune_globs,
&path_excludes,
)
},
|| {
self.load_paths(
&self.configuration.patches,
FileType::Patch,
&extensions_set,
&glob_excludes,
&dir_prune_globs,
&path_excludes,
)
},
)
},
);
let host_files_with_spec = host_files_with_spec?;
let (host_files_with_spec, ignored_files_with_spec): (Vec<_>, Vec<_>) = match &self.git_ignores {
Some(ignores) => host_files_with_spec.into_par_iter().partition(|file_with_spec| {
!file_with_spec.file.path.as_deref().is_some_and(|path| ignores.is_ignored(path, false))
}),
None => (host_files_with_spec, Vec::new()),
};
let vendored_files_with_spec = vendored_files_with_spec?;
let patch_files_with_spec = patch_files_with_spec?;
type TierSpecs = (Option<usize>, Option<usize>, Option<usize>);
let file_count = host_files_with_spec.len()
+ ignored_files_with_spec.len()
+ vendored_files_with_spec.len()
+ patch_files_with_spec.len();
let mut files: Vec<(File, TierSpecs)> = Vec::with_capacity(file_count);
let mut slots: HashMap<FileId, usize> =
HashMap::with_capacity_and_hasher(file_count, foldhash::fast::RandomState::default());
for file_with_spec in host_files_with_spec {
let file_id = file_with_spec.file.id;
let specificity = file_with_spec.specificity;
match slots.entry(file_id) {
Entry::Vacant(entry) => {
entry.insert(files.len());
files.push((file_with_spec.file, (Some(specificity), None, None)));
}
Entry::Occupied(entry) => {
let (file, specs) = &mut files[*entry.get()];
*file = file_with_spec.file;
bump_spec(&mut specs.0, specificity);
}
}
}
if let Some((name, content)) = &self.stdin_override {
let virtual_path = self.configuration.workspace.join(bytes_to_path(name.as_ref()).as_ref());
let virtual_path_canonical = virtual_path.canonicalize().unwrap_or_else(|_| virtual_path.clone());
let virtual_path_str = virtual_path_canonical.to_string_lossy();
let matched_glob = !glob_excludes.is_empty()
&& (glob_excludes.is_match(virtual_path_canonical.as_path())
|| glob_excludes.is_match(bytes_to_path(name.as_ref()).as_ref()));
let matched_path = path_excludes.iter().any(|excl| {
let canonical = if Path::new(excl.as_ref()).is_absolute() {
excl.as_ref().to_path_buf()
} else {
self.configuration.workspace.join(excl.as_ref())
};
let canonical = canonical.canonicalize().unwrap_or(canonical);
let canonical_str = canonical.to_string_lossy();
virtual_path_str.starts_with(canonical_str.as_ref())
&& matches!(virtual_path_str.as_bytes().get(canonical_str.len()), None | Some(&b'/' | &b'\\'))
});
if !matched_glob && !matched_path {
let file = File::ephemeral(Cow::Owned(name.as_ref().to_vec()), Cow::Owned(content.clone()));
let file_id = file.id;
if let Entry::Vacant(entry) = slots.entry(file_id) {
entry.insert(files.len());
files.push((file, (Some(usize::MAX), None, None)));
}
}
}
for file_with_spec in vendored_files_with_spec.into_iter().chain(ignored_files_with_spec) {
let file_id = file_with_spec.file.id;
let vendored_specificity = file_with_spec.specificity;
let slot = *slots.entry(file_id).or_insert_with(|| {
files.push((file_with_spec.file, (None, None, None)));
files.len() - 1
});
bump_spec(&mut files[slot].1.1, vendored_specificity);
}
for file_with_spec in patch_files_with_spec {
let file_id = file_with_spec.file.id;
let specificity = file_with_spec.specificity;
let slot = *slots.entry(file_id).or_insert_with(|| {
files.push((file_with_spec.file, (None, None, None)));
files.len() - 1
});
bump_spec(&mut files[slot].1.2, specificity);
}
db.reserve(files.len() + self.memory_sources.len());
for (mut file, (host_spec, vendored_spec, patch_spec)) in files {
file.file_type = resolve_file_type(host_spec, vendored_spec, patch_spec);
db.add(file);
}
for (name, contents, file_type) in std::mem::take(&mut self.memory_sources) {
let file = File::new(Cow::Borrowed(name), file_type, None, Cow::Borrowed(contents));
db.add(file);
}
Ok(db)
}
#[allow(clippy::set_contains_or_insert, reason = "A duplicate insert can grow a full set.")]
fn record_directory_symlink(&self, entry: &walkdir::DirEntry) {
if let Some(symlinks) = &self.directory_symlinks
&& entry.file_type().is_dir()
&& entry.path_is_symlink()
{
let mut symlinks = symlinks.lock().unwrap_or_else(PoisonError::into_inner);
if !symlinks.contains(entry.path()) {
symlinks.insert(entry.path().to_path_buf());
}
}
}
#[allow(clippy::set_contains_or_insert, reason = "A duplicate insert can grow a full set.")]
fn record_missing_symlink(&self, error: &walkdir::Error) {
let Some(symlinks) = &self.directory_symlinks else { return };
if error.io_error().is_some_and(|error| matches!(error.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory))
&& let Some(path) = error.path()
&& path.read_link().is_ok()
{
let mut symlinks = symlinks.lock().unwrap_or_else(PoisonError::into_inner);
if !symlinks.contains(path) {
symlinks.insert(path.to_path_buf());
}
}
}
fn load_paths(
&self,
roots: &[Cow<'config, [u8]>],
file_type: FileType,
extensions: &HashSet<OsString>,
glob_excludes: &GlobSet,
dir_prune_globs: &GlobSet,
path_excludes: &HashSet<&Cow<'config, Path>>,
) -> Result<Vec<FileWithSpecificity>, DatabaseError> {
let canonical_workspace =
self.configuration.workspace.canonicalize().unwrap_or_else(|_| self.configuration.workspace.to_path_buf());
let canonical_excludes: Vec<String> = path_excludes
.iter()
.filter_map(|ex| {
let p = if Path::new(ex.as_ref()).is_absolute() {
ex.as_ref().to_path_buf()
} else {
self.configuration.workspace.join(ex.as_ref())
};
p.canonicalize().ok()?.into_os_string().into_string().ok()
})
.collect();
let mut paths_to_process: Vec<(PathBuf, usize, bool)> = Vec::new();
let mut directory_roots: Vec<(PathBuf, usize)> = Vec::new();
for root in roots {
let root_path = bytes_to_path(root.as_ref());
let resolved_path = if root_path.is_absolute() {
root_path.as_ref().to_path_buf()
} else {
self.configuration.workspace.join(root_path.as_ref())
};
let is_glob_pattern = !resolved_path.exists()
&& (root.contains(&b'*') || root.contains(&b'?') || root.contains(&b'[') || root.contains(&b'{'));
let specificity = calculate_pattern_specificity(root.as_ref());
if is_glob_pattern {
let pattern = if root_path.is_absolute() {
bytes_to_string_lossy(root.as_ref()).into_owned()
} else {
self.configuration.workspace.join(root_path.as_ref()).to_string_lossy().to_string()
};
match glob::glob(&pattern) {
Ok(entries) => {
for entry in entries {
match entry {
Ok(path) => {
if path.is_file() {
let canonical = path.canonicalize().unwrap_or(path);
paths_to_process.push((canonical, specificity, false));
}
}
Err(e) => {
tracing::warn!("Failed to read glob entry: {}", e);
}
}
}
}
Err(e) => {
return Err(DatabaseError::Glob(e.to_string()));
}
}
} else {
let canonical_root = resolved_path.canonicalize().unwrap_or(resolved_path);
if canonical_root.is_file() {
paths_to_process.push((canonical_root, specificity, true));
continue;
}
for entry in WalkDir::new(&canonical_root).follow_links(true).max_depth(1) {
match entry {
Ok(entry) => {
if entry.depth() == 0 {
continue;
}
if entry.file_type().is_dir() {
if !is_pruned_directory(
entry.path(),
canonical_workspace.as_path(),
&canonical_excludes,
dir_prune_globs,
) {
self.record_directory_symlink(&entry);
directory_roots.push((entry.into_path(), specificity));
}
} else {
paths_to_process.push((entry.into_path(), specificity, false));
}
}
Err(err) => {
self.record_missing_symlink(&err);
warn_walk_error(&err, canonical_root.as_path());
}
}
}
}
}
let has_path_excludes = !canonical_excludes.is_empty();
let has_glob_excludes = !glob_excludes.is_empty();
let load_path = |(path, specificity, skip_ext_check): (PathBuf, usize, bool)| {
if has_glob_excludes
&& (glob_excludes.is_match(&path)
|| glob_excludes.is_match(workspace_relative_string(&path, canonical_workspace.as_path())))
{
return None;
}
if !skip_ext_check {
let ext = path.extension()?;
if !extensions.contains(ext) {
return None;
}
}
if has_path_excludes {
let excluded = path.to_str().is_some_and(|s| {
canonical_excludes.iter().any(|excl| {
s.starts_with(excl.as_str())
&& matches!(s.as_bytes().get(excl.len()), None | Some(&b'/' | &b'\\'))
})
});
if excluded {
return None;
}
}
let workspace = canonical_workspace.as_path();
if let Some((override_name, override_content)) = &self.stdin_override {
#[cfg(windows)]
let logical_name =
path.strip_prefix(workspace).unwrap_or(path.as_path()).to_string_lossy().replace('\\', "/");
#[cfg(not(windows))]
let logical_name =
path.strip_prefix(workspace).unwrap_or(path.as_path()).to_string_lossy().into_owned();
if override_name.as_ref() == logical_name.as_bytes() {
let file = File::new(
Cow::Owned(logical_name.into_bytes()),
file_type,
Some(path),
Cow::Owned(override_content.clone()),
);
return Some(Ok(FileWithSpecificity { file, specificity }));
}
}
match read_file(workspace, &path, file_type) {
Ok(file) => Some(Ok(FileWithSpecificity { file, specificity })),
Err(e) => Some(Err(e)),
}
};
let (direct_files, directory_files) = rayon::join(
|| paths_to_process.into_par_iter().filter_map(&load_path).collect::<Result<Vec<FileWithSpecificity>, _>>(),
|| {
directory_roots
.into_par_iter()
.map(|(root, specificity)| {
#[cfg(unix)]
if rayon::current_num_threads() > 1
&& root.symlink_metadata().is_ok_and(|metadata| metadata.file_type().is_dir())
{
let fallback = AtomicBool::new(false);
if let Some(files) = try_load_directory_parallel(
&root,
specificity,
&load_path,
&|path| {
is_pruned_directory(
path,
canonical_workspace.as_path(),
&canonical_excludes,
dir_prune_globs,
)
},
&fallback,
0,
) {
return files;
}
}
let walker = WalkDir::new(&root).follow_links(true).into_iter().filter_entry(|entry| {
let keep = entry.depth() == 0
|| !entry.file_type().is_dir()
|| !is_pruned_directory(
entry.path(),
canonical_workspace.as_path(),
&canonical_excludes,
dir_prune_globs,
);
if keep {
self.record_directory_symlink(entry);
}
keep
});
let mut paths = walker.filter_map(|entry| match entry {
Ok(entry) if !entry.file_type().is_dir() => Some((entry.into_path(), specificity, false)),
Ok(_) => None,
Err(err) => {
self.record_missing_symlink(&err);
warn_walk_error(&err, root.as_path());
None
}
});
let batches = std::iter::from_fn(|| {
let batch: Vec<_> = paths.by_ref().take(128).collect();
(!batch.is_empty()).then_some(batch)
});
let loaded = Mutex::new(Vec::new());
let load_path = &load_path;
rayon::scope(|scope| {
for (index, paths) in batches.enumerate() {
let loaded = &loaded;
scope.spawn(move |_| {
let files = paths.into_iter().filter_map(load_path).collect::<Result<Vec<_>, _>>();
loaded.lock().unwrap_or_else(PoisonError::into_inner).push((index, files));
});
}
});
let mut loaded = loaded.into_inner().unwrap_or_else(PoisonError::into_inner);
loaded.sort_unstable_by_key(|(index, _)| *index);
let mut files = Vec::new();
for (_, batch) in loaded {
files.extend(batch?);
}
Ok(files)
})
.collect::<Result<Vec<Vec<FileWithSpecificity>>, DatabaseError>>()
},
);
let mut files = direct_files?;
files.extend(directory_files?.into_iter().flatten());
Ok(files)
}
}
#[cfg(unix)]
enum LoadedDirectoryEntry {
File(Option<Result<FileWithSpecificity, DatabaseError>>),
Directory(Option<Result<Vec<FileWithSpecificity>, DatabaseError>>),
}
#[cfg(unix)]
fn try_load_directory_parallel<F, P>(
root: &Path,
specificity: usize,
load_path: &F,
is_pruned: &P,
fallback: &AtomicBool,
depth: usize,
) -> Option<Result<Vec<FileWithSpecificity>, DatabaseError>>
where
F: Fn((PathBuf, usize, bool)) -> Option<Result<FileWithSpecificity, DatabaseError>> + Sync,
P: Fn(&Path) -> bool + Sync,
{
let use_walker = || {
fallback.store(true, Ordering::Relaxed);
None
};
if depth == 64 || fallback.load(Ordering::Relaxed) {
return use_walker();
}
let Ok(directory) = std::fs::read_dir(root) else {
return use_walker();
};
let entries = directory
.map(|entry| {
let entry = entry?;
Ok((entry.path(), entry.file_type()?))
})
.collect::<Result<Vec<_>, std::io::Error>>();
let Ok(entries) = entries else {
return use_walker();
};
if entries.iter().any(|(_, file_type)| !file_type.is_file() && !file_type.is_dir()) {
return use_walker();
}
let entries: Vec<_> = entries
.into_par_iter()
.map(|(path, file_type)| {
if fallback.load(Ordering::Relaxed) {
LoadedDirectoryEntry::Directory(None)
} else if file_type.is_dir() {
if is_pruned(&path) {
LoadedDirectoryEntry::File(None)
} else {
LoadedDirectoryEntry::Directory(try_load_directory_parallel(
&path,
specificity,
load_path,
is_pruned,
fallback,
depth + 1,
))
}
} else {
LoadedDirectoryEntry::File(load_path((path, specificity, false)))
}
})
.collect();
if fallback.load(Ordering::Relaxed) {
return None;
}
let mut files = Vec::new();
for entry in entries {
match entry {
LoadedDirectoryEntry::File(Some(Ok(file))) => files.push(file),
LoadedDirectoryEntry::Directory(Some(Ok(children))) => files.extend(children),
LoadedDirectoryEntry::File(Some(Err(error))) | LoadedDirectoryEntry::Directory(Some(Err(error))) => {
return Some(Err(error));
}
LoadedDirectoryEntry::File(None) | LoadedDirectoryEntry::Directory(None) => {}
}
}
Some(Ok(files))
}
fn workspace_relative_string(path: &Path, workspace: &Path) -> String {
let relative = path.strip_prefix(workspace).unwrap_or(path).to_string_lossy();
#[cfg(windows)]
{
relative.replace('\\', "/")
}
#[cfg(not(windows))]
{
relative.into_owned()
}
}
fn is_pruned_directory(
path: &Path,
workspace: &Path,
canonical_excludes: &[String],
dir_prune_globs: &GlobSet,
) -> bool {
if let Some(path) = path.to_str()
&& canonical_excludes.iter().any(|excluded| {
path.starts_with(excluded.as_str())
&& matches!(path.as_bytes().get(excluded.len()), None | Some(&b'/' | &b'\\'))
})
{
return true;
}
!dir_prune_globs.is_empty()
&& (dir_prune_globs.is_match(path) || dir_prune_globs.is_match(workspace_relative_string(path, workspace)))
}
fn warn_walk_error(error: &walkdir::Error, fallback: &Path) {
let path = error.path().unwrap_or(fallback).display();
if let Some(ancestor) = error.loop_ancestor() {
tracing::warn!("Skipping symlink loop at `{path}`: link cycles back to `{}`.", ancestor.display());
} else {
tracing::warn!("Failed to walk `{path}`: {error}. Entry will be skipped.");
}
}
fn bump_spec(slot: &mut Option<usize>, s: usize) {
*slot = Some(slot.map_or(s, |e| e.max(s)));
}
pub(crate) fn resolve_file_type(
host_spec: Option<usize>,
vendored_spec: Option<usize>,
patch_spec: Option<usize>,
) -> FileType {
let mut decision: Option<(FileType, usize)> = host_spec.map(|s| (FileType::Host, s));
if let Some(v) = vendored_spec {
decision = match decision {
Some((FileType::Host, h)) if v < h => decision,
_ => Some((FileType::Vendored, v)),
};
}
if let Some(p) = patch_spec {
decision = match decision {
Some((FileType::Host | FileType::Patch, e)) if p <= e => decision,
_ => Some((FileType::Patch, p)),
};
}
decision.map(|(ft, _)| ft).unwrap_or(FileType::Host)
}
pub(crate) fn calculate_pattern_specificity(pattern: &[u8]) -> usize {
let pattern_path = bytes_to_path(pattern);
let component_count = pattern_path.components().count();
let is_glob =
pattern.contains(&b'*') || pattern.contains(&b'?') || pattern.contains(&b'[') || pattern.contains(&b'{');
if is_glob {
let non_wildcard_components = pattern_path
.components()
.filter(|c| {
let s = c.as_os_str().to_string_lossy();
!s.contains('*') && !s.contains('?') && !s.contains('[') && !s.contains('{')
})
.count();
non_wildcard_components * 10
} else if pattern_path.is_file()
|| pattern_path.extension().is_some()
|| pattern.rsplit(|&b| b == b'.').next().is_some_and(|ext| ext.eq_ignore_ascii_case(b"php"))
{
component_count * 1000
} else {
component_count * 100
}
}
#[cfg(test)]
mod resolution_tests {
use super::*;
#[test]
fn defaults_to_host_when_nothing_matches() {
assert_eq!(resolve_file_type(None, None, None), FileType::Host);
}
#[test]
fn host_only_match_yields_host() {
assert_eq!(resolve_file_type(Some(100), None, None), FileType::Host);
}
#[test]
fn vendored_only_match_yields_vendored() {
assert_eq!(resolve_file_type(None, Some(100), None), FileType::Vendored);
}
#[test]
fn patch_only_match_yields_patch() {
assert_eq!(resolve_file_type(None, None, Some(100)), FileType::Patch);
}
#[test]
fn vendored_beats_host_at_equal_specificity() {
assert_eq!(resolve_file_type(Some(100), Some(100), None), FileType::Vendored);
}
#[test]
fn vendored_beats_host_when_more_specific() {
assert_eq!(resolve_file_type(Some(100), Some(2000), None), FileType::Vendored);
}
#[test]
fn host_beats_vendored_only_when_strictly_more_specific() {
assert_eq!(resolve_file_type(Some(2000), Some(100), None), FileType::Host);
}
#[test]
fn patch_beats_vendored_unconditionally() {
assert_eq!(resolve_file_type(None, Some(2000), Some(100)), FileType::Patch);
}
#[test]
fn host_beats_patch_at_equal_specificity() {
assert_eq!(resolve_file_type(Some(100), None, Some(100)), FileType::Host);
}
#[test]
fn patch_beats_host_when_strictly_more_specific() {
assert_eq!(resolve_file_type(Some(100), None, Some(2000)), FileType::Patch);
}
#[test]
fn patch_beats_host_that_won_over_vendored() {
assert_eq!(resolve_file_type(Some(100), Some(2000), Some(50)), FileType::Patch);
}
#[test]
fn exact_file_path_beats_directory_at_same_component_count() {
assert!(calculate_pattern_specificity(b"src/foo.php") > calculate_pattern_specificity(b"src/foo"));
}
#[test]
fn directory_beats_glob_at_same_non_wildcard_count() {
assert!(calculate_pattern_specificity(b"src/") > calculate_pattern_specificity(b"src/**/*.php"));
}
#[test]
fn deeper_path_beats_shallower_at_same_kind() {
assert!(calculate_pattern_specificity(b"src/inner/") > calculate_pattern_specificity(b"src/"));
}
#[test]
fn extensionless_phpish_pattern_treated_as_file() {
assert_eq!(calculate_pattern_specificity(b"src/foo.PHP"), calculate_pattern_specificity(b"src/foo.php"),);
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
use crate::DatabaseReader;
use crate::GlobSettings;
use std::borrow::Cow;
use tempfile::TempDir;
fn create_test_config(temp_dir: &TempDir, paths: Vec<&str>, includes: Vec<&str>) -> DatabaseConfiguration<'static> {
create_test_config_with_patches(temp_dir, paths, includes, vec![])
}
fn create_test_config_with_patches(
temp_dir: &TempDir,
paths: Vec<&str>,
includes: Vec<&str>,
patches: Vec<&str>,
) -> DatabaseConfiguration<'static> {
let normalize = |s: &str| s.replace('/', std::path::MAIN_SEPARATOR_STR);
DatabaseConfiguration {
workspace: Cow::Owned(temp_dir.path().to_path_buf()),
paths: paths.into_iter().map(|s| Cow::Owned(normalize(s).into_bytes())).collect(),
includes: includes.into_iter().map(|s| Cow::Owned(normalize(s).into_bytes())).collect(),
patches: patches.into_iter().map(|s| Cow::Owned(normalize(s).into_bytes())).collect(),
excludes: vec![],
extensions: vec![Cow::Borrowed(b"php")],
glob: GlobSettings::default(),
}
}
fn name_str(name: &[u8]) -> std::borrow::Cow<'_, str> {
String::from_utf8_lossy(name)
}
fn create_test_file(temp_dir: &TempDir, relative_path: &str, content: &str) {
let file_path = temp_dir.path().join(relative_path);
if let Some(parent) = file_path.parent() {
std::fs::create_dir_all(parent).unwrap();
}
std::fs::write(file_path, content).unwrap();
}
#[test]
fn test_batched_walk_keeps_file_order() {
let temp_dir = TempDir::new().unwrap();
for index in 0..385 {
create_test_file(&temp_dir, &format!("src/nested/{}/{index}.php", index / 64), "<?php");
}
let root = temp_dir.path().join("src/nested").canonicalize().unwrap();
let expected: Vec<_> = WalkDir::new(root)
.follow_links(true)
.into_iter()
.map(Result::unwrap)
.filter(|entry| !entry.file_type().is_dir())
.map(walkdir::DirEntry::into_path)
.collect();
let config = create_test_config(&temp_dir, vec!["src"], vec![]);
let loader = DatabaseLoader::new(config);
let extensions = std::iter::once(OsString::from("php")).collect();
let globs = GlobSet::empty();
let path_excludes = HashSet::default();
for threads in [1, 4] {
let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap();
let files = pool
.install(|| {
loader.load_paths(
&loader.configuration.paths,
FileType::Host,
&extensions,
&globs,
&globs,
&path_excludes,
)
})
.unwrap();
let actual: Vec<_> = files.into_iter().map(|entry| entry.file.path.unwrap()).collect();
assert_eq!(actual, expected);
}
}
#[test]
fn test_nested_files_match_with_one_and_many_threads() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "src/deep/a.php", "<?php // host");
create_test_file(&temp_dir, "src/deep/b.php", "<?php // vendor");
create_test_file(&temp_dir, "src/deep/patch/c.php", "<?php // patch");
create_test_file(&temp_dir, "src/deep/skip/d.php", "<?php // excluded");
create_test_file(&temp_dir, "src/deep/e.txt", "<?php // wrong extension");
let mut config = create_test_config_with_patches(
&temp_dir,
vec!["src", "src/deep/a.php"],
vec!["src/deep"],
vec!["src/deep/patch"],
);
config.excludes.push(Exclusion::Pattern(Cow::Borrowed("src/deep/skip/**")));
for threads in [1, 4] {
let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap();
let db = pool.install(|| {
DatabaseLoader::new(config.clone())
.with_stdin_override(b"src/deep/a.php", b"<?php // edited".to_vec())
.load()
.unwrap()
});
let mut files =
db.files().map(|file| (file.name.to_vec(), file.file_type, file.contents.to_vec())).collect::<Vec<_>>();
files.sort_by(|left, right| left.0.cmp(&right.0));
assert_eq!(
files,
vec![
(b"src/deep/a.php".to_vec(), FileType::Host, b"<?php // edited".to_vec()),
(b"src/deep/b.php".to_vec(), FileType::Vendored, b"<?php // vendor".to_vec()),
(b"src/deep/patch/c.php".to_vec(), FileType::Patch, b"<?php // patch".to_vec()),
],
);
}
}
#[test]
fn test_exact_file_vs_directory() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "src/b.php", "<?php");
create_test_file(&temp_dir, "src/a.php", "<?php");
let config = create_test_config(&temp_dir, vec!["src/b.php"], vec!["src/"]);
let loader = DatabaseLoader::new(config);
let db = loader.load().unwrap();
let b_file = db.files().find(|f| name_str(&f.name).contains("b.php")).unwrap();
assert_eq!(b_file.file_type, FileType::Host, "src/b.php should be Host (exact file beats directory)");
let a_file = db.files().find(|f| name_str(&f.name).contains("a.php")).unwrap();
assert_eq!(a_file.file_type, FileType::Vendored, "src/a.php should be Vendored");
}
#[test]
fn test_deeper_vs_shallower_directory() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "src/foo/bar.php", "<?php");
let config = create_test_config(&temp_dir, vec!["src/foo/"], vec!["src/"]);
let loader = DatabaseLoader::new(config);
let db = loader.load().unwrap();
let file = db.files().find(|f| name_str(&f.name).contains("bar.php")).unwrap();
assert_eq!(file.file_type, FileType::Host, "Deeper directory pattern should win");
}
#[test]
fn test_exact_file_vs_glob() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "src/b.php", "<?php");
let config = create_test_config(&temp_dir, vec!["src/b.php"], vec!["src/*.php"]);
let loader = DatabaseLoader::new(config);
let db = loader.load().unwrap();
let file = db.files().find(|f| name_str(&f.name).contains("b.php")).unwrap();
assert_eq!(file.file_type, FileType::Host, "Exact file should beat glob pattern");
}
#[test]
fn test_equal_specificity_includes_wins() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "src/a.php", "<?php");
let config = create_test_config(&temp_dir, vec!["src/"], vec!["src/"]);
let loader = DatabaseLoader::new(config);
let db = loader.load().unwrap();
let file = db.files().find(|f| name_str(&f.name).contains("a.php")).unwrap();
assert_eq!(file.file_type, FileType::Vendored, "Equal specificity: includes should win");
}
#[test]
fn test_complex_scenario_from_bug_report() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "src/a.php", "<?php");
create_test_file(&temp_dir, "src/b.php", "<?php");
create_test_file(&temp_dir, "src/c/d.php", "<?php");
create_test_file(&temp_dir, "src/c/e.php", "<?php");
create_test_file(&temp_dir, "vendor/lib1.php", "<?php");
create_test_file(&temp_dir, "vendor/lib2.php", "<?php");
let config = create_test_config(&temp_dir, vec!["src/b.php"], vec!["vendor", "src/c", "src/"]);
let loader = DatabaseLoader::new(config);
let db = loader.load().unwrap();
let b_file = db
.files()
.find(|f| name_str(&f.name).contains("src/b.php") || name_str(&f.name).ends_with("b.php"))
.unwrap();
assert_eq!(b_file.file_type, FileType::Host, "src/b.php should be Host in bug scenario");
let d_file = db.files().find(|f| name_str(&f.name).contains("d.php")).unwrap();
assert_eq!(d_file.file_type, FileType::Vendored, "src/c/d.php should be Vendored");
let lib_file = db.files().find(|f| name_str(&f.name).contains("lib1.php")).unwrap();
assert_eq!(lib_file.file_type, FileType::Vendored, "vendor/lib1.php should be Vendored");
}
#[test]
fn test_files_only_in_paths() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "src/a.php", "<?php");
let config = create_test_config(&temp_dir, vec!["src/"], vec![]);
let loader = DatabaseLoader::new(config);
let db = loader.load().unwrap();
let file = db.files().find(|f| name_str(&f.name).contains("a.php")).unwrap();
assert_eq!(file.file_type, FileType::Host, "File only in paths should be Host");
}
#[test]
fn test_files_only_in_includes() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "vendor/lib.php", "<?php");
let config = create_test_config(&temp_dir, vec![], vec!["vendor/"]);
let loader = DatabaseLoader::new(config);
let db = loader.load().unwrap();
let file = db.files().find(|f| name_str(&f.name).contains("lib.php")).unwrap();
assert_eq!(file.file_type, FileType::Vendored, "File only in includes should be Vendored");
}
#[test]
fn test_stdin_override_replaces_file_content() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "src/foo.php", "<?php\n// on disk");
let config = create_test_config(&temp_dir, vec!["src/"], vec![]);
let loader = DatabaseLoader::new(config).with_stdin_override("src/foo.php", b"<?php\n// from stdin".to_vec());
let db = loader.load().unwrap();
let file = db.files().find(|f| name_str(&f.name).contains("foo.php")).unwrap();
assert_eq!(
file.contents.as_ref(),
b"<?php\n// from stdin",
"stdin override content should be used instead of disk"
);
}
#[test]
fn test_glob_excludes_match_workspace_relative_paths() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "src/Absences/Foo/Foo.php", "<?php");
create_test_file(&temp_dir, "src/Absences/Test/Faker/Provider/AbsencesProvider.php", "<?php");
create_test_file(&temp_dir, "src/Calendar/Test/Helper.php", "<?php");
let mut config = create_test_config(&temp_dir, vec!["src"], vec![]);
config.excludes = vec![Exclusion::Pattern(Cow::Borrowed("src/*/Test/**"))];
let loader = DatabaseLoader::new(config);
let db = loader.load().unwrap();
let names: Vec<String> = db.files().map(|f| name_str(&f.name).into_owned()).collect();
assert!(names.iter().any(|n| n.ends_with("src/Absences/Foo/Foo.php")), "non-Test file should be loaded");
assert!(
!names.iter().any(|n| n.contains("src/Absences/Test/")),
"files under src/*/Test/** should be excluded, got {names:?}"
);
assert!(
!names.iter().any(|n| n.contains("src/Calendar/Test/")),
"files under src/*/Test/** should be excluded, got {names:?}"
);
}
#[test]
fn test_glob_excludes_match_legacy_absolute_prefix_patterns() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "packages/foo/src/main.php", "<?php");
create_test_file(&temp_dir, "packages/foo/vendor/lib.php", "<?php");
let mut config = create_test_config(&temp_dir, vec!["packages"], vec![]);
config.excludes = vec![Exclusion::Pattern(Cow::Borrowed("*/packages/**/vendor/*"))];
let loader = DatabaseLoader::new(config);
let db = loader.load().unwrap();
let names: Vec<String> = db.files().map(|f| name_str(&f.name).into_owned()).collect();
assert!(names.iter().any(|n| n.ends_with("packages/foo/src/main.php")));
assert!(
!names.iter().any(|n| n.contains("/vendor/")),
"legacy `*/packages/**/vendor/*` style should still exclude vendor files, got {names:?}"
);
}
#[test]
fn test_glob_dir_prune_skips_relative_directories() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "vendor/slevomat/coding-standard/main.php", "<?php");
create_test_file(&temp_dir, "vendor/slevomat/coding-standard/tests/Sniffs/Foo.php", "<?php");
create_test_file(&temp_dir, "vendor/another/lib.php", "<?php");
let mut config = create_test_config(&temp_dir, vec![], vec!["vendor"]);
config.excludes = vec![Exclusion::Pattern(Cow::Borrowed("vendor/**/tests/**"))];
let loader = DatabaseLoader::new(config);
let db = loader.load().unwrap();
let names: Vec<String> = db.files().map(|f| name_str(&f.name).into_owned()).collect();
assert!(names.iter().any(|n| n.ends_with("vendor/slevomat/coding-standard/main.php")));
assert!(names.iter().any(|n| n.ends_with("vendor/another/lib.php")));
assert!(
!names.iter().any(|n| n.contains("/tests/")),
"files under vendor/**/tests/** should be pruned, got {names:?}"
);
}
#[test]
fn test_stdin_override_adds_file_when_not_on_disk() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "src/.gitkeep", "");
let config = create_test_config(&temp_dir, vec!["src/"], vec![]);
let loader =
DatabaseLoader::new(config).with_stdin_override("src/unsaved.php", b"<?php\n// unsaved buffer".to_vec());
let db = loader.load().unwrap();
let file = db.files().find(|f| name_str(&f.name).contains("unsaved.php")).unwrap();
assert_eq!(file.file_type, FileType::Host);
assert_eq!(file.contents.as_ref(), b"<?php\n// unsaved buffer");
}
#[test]
fn test_stdin_override_accepts_non_utf8_content() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "src/.gitkeep", "");
let config = create_test_config(&temp_dir, vec!["src/"], vec![]);
let content = b"<?php\n\nfunction f\xC9\xFF(): void {}\n".to_vec();
assert!(std::str::from_utf8(&content).is_err(), "test buffer must contain non-UTF-8 bytes");
let loader = DatabaseLoader::new(config).with_stdin_override("src/buffer.php", content.clone());
let db = loader.load().unwrap();
let file = db.files().find(|f| name_str(&f.name).contains("buffer.php")).unwrap();
assert_eq!(file.contents.as_ref(), content.as_slice());
}
#[cfg(unix)]
#[test]
fn test_symlinked_file_under_include_is_loaded() {
let temp_dir = TempDir::new().unwrap();
let external = TempDir::new().unwrap();
create_test_file(&external, "Bar.php", "<?php class Bar {}\n");
std::fs::create_dir_all(temp_dir.path().join("vendor")).unwrap();
std::os::unix::fs::symlink(external.path().join("Bar.php"), temp_dir.path().join("vendor/Bar.php")).unwrap();
let config = create_test_config(&temp_dir, vec![], vec!["vendor/"]);
let db = DatabaseLoader::new(config).load().unwrap();
let bar = db.files().find(|f| name_str(&f.name).contains("Bar.php"));
assert!(bar.is_some(), "symlinked Bar.php should be loaded via include = ['vendor/']");
}
#[cfg(unix)]
#[test]
fn test_symlinked_directory_under_include_is_descended() {
let temp_dir = TempDir::new().unwrap();
let external = TempDir::new().unwrap();
create_test_file(&external, "src/Foo.php", "<?php class Foo {}\n");
create_test_file(&external, "src/Bar.php", "<?php class Bar {}\n");
std::fs::create_dir_all(temp_dir.path().join("vendor")).unwrap();
std::os::unix::fs::symlink(external.path(), temp_dir.path().join("vendor/example-package")).unwrap();
let config = create_test_config(&temp_dir, vec![], vec!["vendor/"]);
let db = DatabaseLoader::new(config).load().unwrap();
assert!(db.files().any(|f| name_str(&f.name).contains("Foo.php")), "Foo.php inside symlinked dir not found");
assert!(db.files().any(|f| name_str(&f.name).contains("Bar.php")), "Bar.php inside symlinked dir not found");
}
#[cfg(unix)]
#[test]
fn directory_walks_report_empty_symlinks_without_changing_loaded_files() {
let temp_dir = TempDir::new().unwrap();
let external = TempDir::new().unwrap();
create_test_file(&temp_dir, "vendor/Kept.php", "<?php class Kept {}\n");
std::fs::create_dir_all(temp_dir.path().join("vendor/deep")).unwrap();
for path in ["vendor/shallow", "vendor/deep/package"] {
std::os::unix::fs::symlink(external.path(), temp_dir.path().join(path)).unwrap();
}
let config = create_test_config(&temp_dir, vec![], vec!["vendor/"]);
for threads in [1, 4] {
let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap();
let (database, mut symlinks) =
pool.install(|| DatabaseLoader::new(config.clone()).load_with_directory_symlinks().unwrap());
symlinks.sort();
let root = temp_dir.path().canonicalize().unwrap();
assert_eq!(symlinks, [root.join("vendor/deep/package"), root.join("vendor/shallow")]);
let ordinary = pool.install(|| DatabaseLoader::new(config.clone()).load().unwrap());
let summarize = |database: &Database<'_>| {
database
.files()
.map(|file| (file.name.to_vec(), file.file_type, file.contents.to_vec()))
.collect::<Vec<_>>()
};
assert_eq!(summarize(&database), summarize(&ordinary));
}
}
#[cfg(unix)]
#[test]
fn directory_walks_report_dangling_symlinks_without_changing_loaded_files() {
let temp_dir = TempDir::new().unwrap();
let external = TempDir::new().unwrap();
create_test_file(&temp_dir, "vendor/Kept.php", "<?php class Kept {}\n");
create_test_file(&external, "blocked", "not a directory");
std::fs::create_dir_all(temp_dir.path().join("vendor/deep")).unwrap();
for (link, target) in [
("vendor/shallow", external.path().join("missing")),
("vendor/deep/relative", PathBuf::from("../../missing")),
("vendor/deep/blocked", external.path().join("blocked/child")),
] {
std::os::unix::fs::symlink(target, temp_dir.path().join(link)).unwrap();
}
let config = create_test_config(&temp_dir, vec![], vec!["vendor/"]);
let root = temp_dir.path().canonicalize().unwrap();
for threads in [1, 4] {
let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap();
let (database, mut symlinks) =
pool.install(|| DatabaseLoader::new(config.clone()).load_with_directory_symlinks().unwrap());
symlinks.sort();
assert_eq!(
symlinks,
[root.join("vendor/deep/blocked"), root.join("vendor/deep/relative"), root.join("vendor/shallow")]
);
let ordinary = pool.install(|| DatabaseLoader::new(config.clone()).load().unwrap());
let summarize = |database: &Database<'_>| {
database
.files()
.map(|file| (file.name.to_vec(), file.file_type, file.contents.to_vec()))
.collect::<Vec<_>>()
};
assert_eq!(summarize(&database), summarize(&ordinary));
}
}
#[cfg(unix)]
#[test]
fn file_only_globs_do_not_discover_empty_directory_symlinks() {
let temp_dir = TempDir::new().unwrap();
let external = TempDir::new().unwrap();
std::fs::create_dir_all(temp_dir.path().join("vendor")).unwrap();
std::os::unix::fs::symlink(external.path(), temp_dir.path().join("vendor/package")).unwrap();
let config = create_test_config(&temp_dir, vec![], vec!["vendor/**/*.php"]);
let (database, symlinks) = DatabaseLoader::new(config).load_with_directory_symlinks().unwrap();
assert!(database.files().next().is_none());
assert!(symlinks.is_empty());
}
#[cfg(unix)]
#[test]
fn test_symlink_cycle_is_warned_and_skipped() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "src/nested/Real.php", "<?php class Real {}\n");
std::os::unix::fs::symlink(temp_dir.path().join("src/nested"), temp_dir.path().join("src/nested/loop"))
.unwrap();
let config = create_test_config(&temp_dir, vec![], vec!["src/"]);
for threads in [1, 4] {
let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap();
let db = pool.install(|| {
DatabaseLoader::new(config.clone()).load().expect("symlink cycle should not abort the load")
});
let names = db.files().map(|file| file.name.to_vec()).collect::<Vec<_>>();
assert_eq!(names, [b"src/nested/Real.php".to_vec()]);
}
}
#[test]
fn test_exact_extensionless_file_is_loaded() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "bin/console", "<?php\n// entrypoint");
let config = create_test_config(&temp_dir, vec!["bin/console"], vec![]);
let db = DatabaseLoader::new(config).load().unwrap();
let file = db.files().find(|f| name_str(&f.name).ends_with("bin/console")).unwrap();
assert_eq!(file.file_type, FileType::Host);
assert_eq!(file.contents.as_ref(), b"<?php\n// entrypoint");
}
#[test]
fn test_extensionless_file_in_directory_is_skipped() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "bin/console", "<?php");
create_test_file(&temp_dir, "bin/run.php", "<?php");
let config = create_test_config(&temp_dir, vec!["bin"], vec![]);
let db = DatabaseLoader::new(config).load().unwrap();
let names: Vec<String> = db.files().map(|f| name_str(&f.name).into_owned()).collect();
assert!(names.iter().any(|n| n.ends_with("bin/run.php")), "run.php should be loaded, got {names:?}");
assert!(!names.iter().any(|n| n.ends_with("bin/console")), "extensionless console should be skipped");
}
#[test]
fn test_patch_beats_vendored_at_equal_specificity() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "lib/Foo.php", "<?php");
let config = create_test_config_with_patches(&temp_dir, vec![], vec!["lib/"], vec!["lib/"]);
let db = DatabaseLoader::new(config).load().unwrap();
let file = db.files().find(|f| String::from_utf8_lossy(&f.name).contains("Foo.php")).unwrap();
assert_eq!(file.file_type, FileType::Patch, "patch should beat vendored at equal specificity");
}
#[test]
fn test_host_beats_patch_at_equal_specificity() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "src/Foo.php", "<?php");
let config = create_test_config_with_patches(&temp_dir, vec!["src/"], vec![], vec!["src/"]);
let db = DatabaseLoader::new(config).load().unwrap();
let file = db.files().find(|f| String::from_utf8_lossy(&f.name).contains("Foo.php")).unwrap();
assert_eq!(file.file_type, FileType::Host, "host should beat patch at equal specificity");
}
#[test]
fn test_patch_beats_host_when_strictly_more_specific() {
let temp_dir = TempDir::new().unwrap();
create_test_file(&temp_dir, "src/Foo.php", "<?php");
create_test_file(&temp_dir, "src/Bar.php", "<?php");
let config = create_test_config_with_patches(&temp_dir, vec!["src/"], vec![], vec!["src/Foo.php"]);
let db = DatabaseLoader::new(config).load().unwrap();
let foo = db.files().find(|f| String::from_utf8_lossy(&f.name).contains("Foo.php")).unwrap();
assert_eq!(foo.file_type, FileType::Patch, "exact-file patch should beat directory-level host pattern");
let bar = db.files().find(|f| String::from_utf8_lossy(&f.name).contains("Bar.php")).unwrap();
assert_eq!(bar.file_type, FileType::Host, "file not covered by patch should remain Host");
}
#[test]
fn git_ignored_sources_load_as_vendored() {
let temp_dir = TempDir::new().unwrap();
std::fs::create_dir_all(temp_dir.path().join(".git")).unwrap();
create_test_file(&temp_dir, ".gitignore", "/vendor/\n.claude/worktrees/\n");
create_test_file(&temp_dir, "src/Service.php", "<?php");
create_test_file(&temp_dir, "vendor/package/Library.php", "<?php");
create_test_file(&temp_dir, ".claude/worktrees/copy/src/Service.php", "<?php");
let root = temp_dir.path().to_string_lossy().into_owned();
let ignores = Arc::new(GitIgnores::discover_with_global(temp_dir.path(), None).unwrap());
let db = DatabaseLoader::new(create_test_config(&temp_dir, vec![&root], vec![]))
.with_git_ignores(ignores)
.load()
.unwrap();
let types: HashMap<String, FileType> =
db.files().map(|file| (name_str(&file.name).into_owned(), file.file_type)).collect();
assert_eq!(types.get("src/Service.php"), Some(&FileType::Host));
assert_eq!(types.get("vendor/package/Library.php"), Some(&FileType::Vendored));
assert_eq!(types.get(".claude/worktrees/copy/src/Service.php"), Some(&FileType::Vendored));
}
}