mago-database 1.20.1

Provides a high-performance, in-memory database for source code analysis, featuring distinct mutable and immutable states and transactional updates.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
//! Database loader for scanning and loading project files.

use std::borrow::Cow;
use std::collections::hash_map::Entry;
use std::ffi::OsString;
use std::path::Path;

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::matcher::build_glob_set;
use crate::utils::read_file;

/// Holds a file along with the specificity of the pattern that matched it.
///
/// Specificity is used to resolve conflicts when a file matches both `paths` and `includes`.
/// Higher specificity values indicate more specific matches (e.g., exact file paths have higher
/// specificity than directory patterns).
#[derive(Debug)]
struct FileWithSpecificity {
    file: File,
    specificity: usize,
}

/// Builder for loading files into a Database from the filesystem and memory.
pub struct DatabaseLoader<'a> {
    database: Option<Database<'a>>,
    configuration: DatabaseConfiguration<'a>,
    memory_sources: Vec<(&'static str, &'static str, FileType)>,
    /// When set, content for this file (by logical name) is taken from here instead of disk.
    /// Used for editor integrations: read content from stdin but use the given path for baseline and reporting.
    stdin_override: Option<(Cow<'a, str>, String)>,
}

impl<'a> DatabaseLoader<'a> {
    #[must_use]
    pub fn new(configuration: DatabaseConfiguration<'a>) -> Self {
        Self { configuration, memory_sources: vec![], database: None, stdin_override: None }
    }

    #[must_use]
    pub fn with_database(mut self, database: Database<'a>) -> Self {
        self.database = Some(database);
        self
    }

    /// When set, the file with this logical name (workspace-relative path) will use the given
    /// content instead of being read from disk. The logical name is used for baseline and reporting.
    #[must_use]
    pub fn with_stdin_override(mut self, logical_name: impl Into<Cow<'a, str>>, content: String) -> Self {
        self.stdin_override = Some((logical_name.into(), content));
        self
    }

    pub fn add_memory_source(&mut self, name: &'static str, contents: &'static str, file_type: FileType) {
        self.memory_sources.push((name, contents, file_type));
    }

    /// Loads files from disk into the database.
    ///
    /// # Errors
    ///
    /// Returns a [`DatabaseError`] if:
    /// - A glob pattern is invalid
    /// - File system operations fail (reading directories, files)
    /// - File content cannot be read as valid UTF-8
    pub fn load(mut self) -> Result<Database<'a>, DatabaseError> {
        let mut db = self.database.take().unwrap_or_else(|| Database::new(self.configuration.clone()));

        // Update database configuration to use the loader's configuration
        // (fixes workspace path when merging with prelude database)
        db.configuration = self.configuration.clone();

        let extensions_set: HashSet<OsString> =
            self.configuration.extensions.iter().map(|s| OsString::from(s.as_ref())).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_patterns: Vec<&str> = glob_exclude_patterns
            .iter()
            .filter_map(|pat| {
                let stripped =
                    pat.strip_suffix("/**/*").or_else(|| pat.strip_suffix("/**")).or_else(|| pat.strip_suffix("/*"))?;
                if stripped.is_empty() || stripped == "*" || stripped == "**" {
                    return None;
                }
                Some(stripped)
            })
            .collect();

        let dir_prune_globs = build_glob_set(dir_prune_patterns.iter().copied(), self.configuration.glob)?;

        let path_excludes: HashSet<_> = self
            .configuration
            .excludes
            .iter()
            .filter_map(|ex| match ex {
                Exclusion::Path(p) => Some(p),
                _ => None,
            })
            .collect();

        let host_files_with_spec = self.load_paths(
            &self.configuration.paths,
            FileType::Host,
            &extensions_set,
            &glob_excludes,
            &dir_prune_globs,
            &path_excludes,
        )?;

        let vendored_files_with_spec = self.load_paths(
            &self.configuration.includes,
            FileType::Vendored,
            &extensions_set,
            &glob_excludes,
            &dir_prune_globs,
            &path_excludes,
        )?;

        let mut all_files: HashMap<FileId, File> = HashMap::default();
        let mut file_decisions: HashMap<FileId, (FileType, usize)> = HashMap::default();

        // Process host files (from paths)
        for file_with_spec in host_files_with_spec {
            let file_id = file_with_spec.file.id;
            let specificity = file_with_spec.specificity;

            all_files.insert(file_id, file_with_spec.file);
            file_decisions.insert(file_id, (FileType::Host, specificity));
        }

        // When stdin override is set, ensure that the file is in the database
        // (covers new/unsaved files, not on disk)
        if let Some((ref name, ref content)) = self.stdin_override {
            let file = File::ephemeral(Cow::Owned(name.as_ref().to_string()), Cow::Owned(content.clone()));
            let file_id = file.id;
            if let Entry::Vacant(e) = all_files.entry(file_id) {
                e.insert(file);

                file_decisions.insert(file_id, (FileType::Host, usize::MAX));
            }
        }

        for file_with_spec in vendored_files_with_spec {
            let file_id = file_with_spec.file.id;
            let vendored_specificity = file_with_spec.specificity;

            all_files.entry(file_id).or_insert(file_with_spec.file);

            match file_decisions.get(&file_id) {
                Some((FileType::Host, host_specificity)) if vendored_specificity < *host_specificity => {
                    // Keep Host
                }
                _ => {
                    file_decisions.insert(file_id, (FileType::Vendored, vendored_specificity));
                }
            }
        }

        db.reserve(file_decisions.len() + self.memory_sources.len());

        for (file_id, (final_type, _)) in file_decisions {
            if let Some(mut file) = all_files.remove(&file_id) {
                file.file_type = final_type;
                db.add(file);
            }
        }

        for (name, contents, file_type) in self.memory_sources {
            let file = File::new(Cow::Borrowed(name), file_type, None, Cow::Borrowed(contents));

            db.add(file);
        }

        Ok(db)
    }

    /// Discovers and reads all files from a set of root paths or glob patterns in parallel.
    ///
    /// Supports both:
    /// - Directory paths (e.g., "src", "tests") - recursively walks all files
    /// - Glob patterns (e.g., "src/**/*.php", "tests/Unit/*Test.php") - matches files using glob syntax
    ///
    /// Returns files along with their pattern specificity for conflict resolution.
    fn load_paths(
        &self,
        roots: &[Cow<'a, str>],
        file_type: FileType,
        extensions: &HashSet<OsString>,
        glob_excludes: &GlobSet,
        dir_prune_globs: &GlobSet,
        path_excludes: &HashSet<&Cow<'a, Path>>,
    ) -> Result<Vec<FileWithSpecificity>, DatabaseError> {
        // Canonicalize the workspace once.  All WalkDir roots are canonicalized
        // before traversal so their paths inherit the canonical prefix without
        // any per-file syscalls.
        let canonical_workspace =
            self.configuration.workspace.canonicalize().unwrap_or_else(|_| self.configuration.workspace.to_path_buf());

        // Pre-canonicalize path excludes once as strings.  A plain byte-string
        // prefix check is then sufficient in the parallel section, replacing the
        // per-file canonicalize() + Path::starts_with (Components iteration).
        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 workspace_relative_str = |path: &Path| -> String {
            let rel = path.strip_prefix(canonical_workspace.as_path()).unwrap_or(path);
            let s = rel.to_string_lossy();
            #[cfg(windows)]
            {
                s.replace('\\', "/")
            }
            #[cfg(not(windows))]
            {
                s.into_owned()
            }
        };

        let mut paths_to_process: Vec<(std::path::PathBuf, usize)> = Vec::new();

        for root in roots {
            // Check if this is a glob pattern (contains glob metacharacters).
            // First check if it's an actual file/directory on disk. if so, treat it
            // as a literal path even if the name contains glob metacharacters like `[]`.
            let resolved_path = if Path::new(root.as_ref()).is_absolute() {
                Path::new(root.as_ref()).to_path_buf()
            } else {
                self.configuration.workspace.join(root.as_ref())
            };

            let is_glob_pattern = !resolved_path.exists()
                && (root.contains('*') || root.contains('?') || root.contains('[') || root.contains('{'));

            let specificity = Self::calculate_pattern_specificity(root.as_ref());
            if is_glob_pattern {
                // Handle as glob pattern
                let pattern = if Path::new(root.as_ref()).is_absolute() {
                    root.to_string()
                } else {
                    // Make relative patterns absolute by prepending workspace
                    self.configuration.workspace.join(root.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() {
                                        // Canonicalize so the path shares the same prefix as
                                        // `canonical_workspace` (important on macOS where
                                        // TempDir / glob return /var/… but canonicalize gives
                                        // /private/var/…).  Fall back to the original on error.
                                        let canonical = path.canonicalize().unwrap_or(path);
                                        paths_to_process.push((canonical, specificity));
                                    }
                                }
                                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);
                let has_dir_prunes = !dir_prune_globs.is_empty();
                let has_path_prunes = !canonical_excludes.is_empty();
                let walker = WalkDir::new(&canonical_root).into_iter().filter_entry(|entry| {
                    if entry.depth() == 0 || !entry.file_type().is_dir() {
                        return true;
                    }

                    let path = entry.path();

                    if has_path_prunes
                        && let Some(p) = path.to_str()
                        && canonical_excludes.iter().any(|excl| {
                            p.starts_with(excl.as_str())
                                && matches!(p.as_bytes().get(excl.len()), None | Some(&b'/' | &b'\\'))
                        })
                    {
                        return false;
                    }

                    if has_dir_prunes
                        && (dir_prune_globs.is_match(path) || dir_prune_globs.is_match(workspace_relative_str(path)))
                    {
                        return false;
                    }

                    true
                });

                for entry in walker.filter_map(Result::ok) {
                    if entry.file_type().is_file() {
                        paths_to_process.push((entry.into_path(), specificity));
                    }
                }
            }
        }

        let has_path_excludes = !canonical_excludes.is_empty();
        let has_glob_excludes = !glob_excludes.is_empty();
        let files: Vec<FileWithSpecificity> = paths_to_process
            .into_par_iter()
            .filter_map(|(path, specificity)| {
                if has_glob_excludes
                    && (glob_excludes.is_match(&path) || glob_excludes.is_match(workspace_relative_str(&path)))
                {
                    return None;
                }

                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();
                #[cfg(windows)]
                let logical_name = path
                    .strip_prefix(workspace)
                    .unwrap_or_else(|_| 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 let Some((ref override_name, ref override_content)) = self.stdin_override
                    && override_name.as_ref() == logical_name
                {
                    let file = File::new(
                        Cow::Owned(logical_name),
                        file_type,
                        Some(path.clone()),
                        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)),
                }
            })
            .collect::<Result<Vec<FileWithSpecificity>, _>>()?;

        Ok(files)
    }

    /// Calculates how specific a pattern is for a given file path.
    ///
    /// Examples:
    ///
    /// - "src/b.php" matching src/b.php: ~2000 (exact file, 2 components)
    /// - "src/" matching src/b.php: ~100 (directory, 1 component)
    /// - "src" matching src/b.php: ~100 (directory, 1 component)
    fn calculate_pattern_specificity(pattern: &str) -> usize {
        let pattern_path = Path::new(pattern);

        let component_count = pattern_path.components().count();
        let is_glob = pattern.contains('*') || pattern.contains('?') || pattern.contains('[') || pattern.contains('{');

        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.ends_with(".php") {
            component_count * 1000
        } else {
            component_count * 100
        }
    }
}

#[cfg(test)]
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> {
        // Normalize path separators to platform-specific separators
        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))).collect(),
            includes: includes.into_iter().map(|s| Cow::Owned(normalize(s))).collect(),
            excludes: vec![],
            extensions: vec![Cow::Borrowed("php")],
            glob: GlobSettings::default(),
        }
    }

    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_specificity_calculation_exact_file() {
        let spec = DatabaseLoader::calculate_pattern_specificity("src/b.php");
        assert!(spec >= 2000, "Exact file should have high specificity, got {spec}");
    }

    #[test]
    fn test_specificity_calculation_directory() {
        let spec = DatabaseLoader::calculate_pattern_specificity("src/");
        assert!((100..1000).contains(&spec), "Directory should have moderate specificity, got {spec}");
    }

    #[test]
    fn test_specificity_calculation_glob() {
        let spec = DatabaseLoader::calculate_pattern_specificity("src/*.php");
        assert!(spec < 100, "Glob pattern should have low specificity, got {spec}");
    }

    #[test]
    fn test_specificity_calculation_deeper_path() {
        let shallow_spec = DatabaseLoader::calculate_pattern_specificity("src/");
        let deep_spec = DatabaseLoader::calculate_pattern_specificity("src/foo/bar/");
        assert!(deep_spec > shallow_spec, "Deeper path should have higher specificity");
    }

    #[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| 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| 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| 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| 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| 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| f.name.contains("src/b.php") || 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| 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| 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| 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| 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", "<?php\n// from stdin".to_string());
        let db = loader.load().unwrap();

        let file = db.files().find(|f| f.name.contains("foo.php")).unwrap();
        assert_eq!(
            file.contents.as_ref(),
            "<?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| f.name.to_string()).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| f.name.to_string()).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| f.name.to_string()).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", "<?php\n// unsaved buffer".to_string());
        let db = loader.load().unwrap();

        let file = db.files().find(|f| f.name.contains("unsaved.php")).unwrap();
        assert_eq!(file.file_type, FileType::Host);
        assert_eq!(file.contents.as_ref(), "<?php\n// unsaved buffer");
    }
}