1use std::collections::HashSet;
2
3use crate::{CodeModel, Package, RepoPath, SourceFile};
4
5#[cfg(test)]
6mod tests;
7
8const UNIVERSAL_TOOLING_DOT_DIRS: &[&str] = &[".github"];
9
10const UNIVERSAL_TOOLING_DIRS: &[&str] = &["scripts", "docs", "examples", "tools", "benches"];
11
12#[derive(Clone, Debug, Default)]
13pub struct UniversalToolingPaths {
14 package_roots: HashSet<String>,
15}
16
17impl UniversalToolingPaths {
18 pub fn from_model(model: &CodeModel) -> UniversalToolingPaths {
19 let workspace_roots = model
20 .workspace
21 .packages()
22 .filter_map(|package| match package {
23 Package::Root => None,
24 Package::Member(root) => Some(root.as_str()),
25 });
26 let manifest_roots = model
27 .dependency_manifests
28 .iter()
29 .map(|entry| entry.package_root.as_str());
30 let declared_roots = model
31 .declared_dependencies
32 .iter()
33 .map(|dep| dep.package_root.as_str());
34 UniversalToolingPaths::from_roots(
35 workspace_roots.chain(manifest_roots).chain(declared_roots),
36 )
37 }
38
39 pub fn from_roots<'a>(roots: impl IntoIterator<Item = &'a str>) -> UniversalToolingPaths {
40 let package_roots = roots
41 .into_iter()
42 .map(|root| root.trim_end_matches('/'))
43 .filter(|root| !root.is_empty())
44 .map(str::to_owned)
45 .collect();
46 UniversalToolingPaths { package_roots }
47 }
48
49 pub fn is_universal_tooling_path(&self, path: &RepoPath) -> bool {
50 let repo_rel = path.as_str();
51 let (repo_dir, file_name) = split_dir_and_file(repo_rel);
52 if file_name.is_empty() {
53 return false;
54 }
55 if has_universal_dot_dir(repo_dir) || starts_with_universal_tooling_dir(repo_rel) {
56 return true;
57 }
58
59 let mut folder = repo_rel;
60 while let Some((prefix, _)) = folder.rsplit_once('/') {
61 if self.package_roots.contains(prefix) {
62 let pkg_rel = &repo_rel[prefix.len() + 1..];
63 if starts_with_universal_tooling_dir(pkg_rel) {
64 return true;
65 }
66 }
67 folder = prefix;
68 }
69 false
70 }
71
72 pub fn is_tooling_file(&self, file: &SourceFile) -> bool {
73 file.model.is_tooling_file || self.is_universal_tooling_path(&file.path)
74 }
75}
76
77fn has_universal_dot_dir(dir_path: Option<&str>) -> bool {
78 dir_path.is_some_and(|dir| {
79 dir.split('/').any(|segment| {
80 UNIVERSAL_TOOLING_DOT_DIRS.contains(&segment.to_ascii_lowercase().as_str())
81 })
82 })
83}
84
85fn split_dir_and_file(path: &str) -> (Option<&str>, &str) {
86 match path.rsplit_once('/') {
87 Some((dir, file)) => (Some(dir), file),
88 None => (None, path),
89 }
90}
91
92fn starts_with_universal_tooling_dir(relative_path: &str) -> bool {
93 let Some((first_dir, _)) = relative_path.split_once('/') else {
94 return false;
95 };
96 UNIVERSAL_TOOLING_DIRS.contains(&first_dir.to_ascii_lowercase().as_str())
97}