crap4rust/analysis/
test_module_registry.rs1use std::collections::HashSet;
6use std::path::{Path, PathBuf};
7
8use syn::{File, Item, ItemMod};
9
10use crate::analysis::impl_collector::is_test_attrs;
11use crate::analysis::normalize_path::normalize_path;
12
13pub struct TestModuleRegistry {
14 excluded_files: HashSet<String>,
15}
16
17impl TestModuleRegistry {
18 #[must_use]
19 pub fn build(files: &[(PathBuf, File)]) -> Self {
20 let mut excluded_files = HashSet::new();
21 for (file_path, syntax) in files {
22 let base_dir = Self::own_base_dir(file_path);
23 excluded_files.extend(Self::collect_excluded_mods(&syntax.items, &base_dir));
24 }
25 Self { excluded_files }
26 }
27
28 #[must_use]
29 pub fn is_excluded(&self, file_path: &Path) -> bool {
30 self.excluded_files.contains(&normalize_path(file_path))
31 }
32
33 fn own_base_dir(file_path: &Path) -> PathBuf {
34 let parent = file_path
35 .parent()
36 .map(Path::to_path_buf)
37 .unwrap_or_default();
38 let stem = file_path
39 .file_stem()
40 .and_then(|stem| stem.to_str())
41 .unwrap_or_default();
42 if matches!(stem, "lib" | "main" | "mod") {
43 parent
44 } else {
45 parent.join(stem)
46 }
47 }
48
49 fn collect_excluded_mods(items: &[Item], base_dir: &Path) -> HashSet<String> {
50 let mut excluded_files = HashSet::new();
51 for item in items {
52 let Item::Mod(item_mod) = item else {
53 continue;
54 };
55 match &item_mod.content {
56 Some((_, nested_items)) => {
57 let nested_dir = base_dir.join(item_mod.ident.to_string());
58 excluded_files.extend(Self::collect_excluded_mods(nested_items, &nested_dir));
59 }
60 None => excluded_files.extend(Self::register_if_test_gated(item_mod, base_dir)),
61 }
62 }
63 excluded_files
64 }
65
66 fn register_if_test_gated(item_mod: &ItemMod, base_dir: &Path) -> Option<String> {
67 if !is_test_attrs(&item_mod.attrs) {
68 return None;
69 }
70 Self::resolve_file_module(base_dir, item_mod).map(|target| normalize_path(&target))
71 }
72
73 fn resolve_file_module(base_dir: &Path, item_mod: &ItemMod) -> Option<PathBuf> {
74 let name = item_mod.ident.to_string();
75
76 let sibling_file = base_dir.join(format!("{name}.rs"));
77 if sibling_file.exists() {
78 return Some(sibling_file);
79 }
80
81 let directory_file = base_dir.join(&name).join("mod.rs");
82 if directory_file.exists() {
83 return Some(directory_file);
84 }
85
86 None
87 }
88}