1use std::borrow::Cow;
7use std::ffi::{OsStr, OsString};
8use std::path::{Path, PathBuf};
9
10use rustc_hash::{FxHashMap, FxHashSet};
11
12use fallow_config::{ExternalPluginDef, PackageJson, PluginDetection, UsedClassMemberRule};
13
14use crate::discover::SOURCE_EXTENSIONS;
15
16use super::super::{PathRule, Plugin, PluginResult, PluginUsedExportRule, UsedExportRule};
17use super::{
18 AggregatedPluginResult, PluginRegexValidationError, PluginRegexValidationErrorInput,
19 VirtualModuleMatch, VirtualModuleProviderRule,
20};
21
22#[must_use]
31pub fn is_source_ext_root_pattern(pat: &str) -> bool {
32 if pat.is_empty() || pat.contains('/') {
33 return false;
34 }
35 for expanded in expand_brace_pattern(pat) {
36 if expanded.starts_with('.') {
37 return false;
38 }
39 let Some(ext) = std::path::Path::new(&expanded).extension() else {
40 return false;
41 };
42 let Some(ext_str) = ext.to_str() else {
43 return false;
44 };
45 if !SOURCE_EXTENSIONS.contains(&ext_str) {
46 return false;
47 }
48 }
49 true
50}
51
52#[must_use]
54pub fn prepare_config_pattern(pat: &str) -> Cow<'_, str> {
55 if is_source_ext_root_pattern(pat) {
56 Cow::Owned(format!("**/{pat}"))
57 } else {
58 Cow::Borrowed(pat)
59 }
60}
61
62fn push_config_default_exports<'a>(
69 pname: &str,
70 patterns: impl Iterator<Item = &'a str>,
71 result: &mut AggregatedPluginResult,
72) {
73 for pat in patterns {
74 result.config_export_credits.push(PluginUsedExportRule::new(
75 pname,
76 UsedExportRule::new(prepare_config_pattern(pat), ["default"]),
77 ));
78 }
79}
80
81pub fn process_static_patterns(
83 plugin: &dyn Plugin,
84 root: &Path,
85 result: &mut AggregatedPluginResult,
86) {
87 let pname = plugin.name().to_string();
88 result.active_plugins.push(pname.clone());
89 result
90 .active_plugin_scopes
91 .push((pname.clone(), String::new()));
92 result
93 .entry_point_roles
94 .insert(pname.clone(), plugin.entry_point_role());
95
96 collect_static_plugin_rules(plugin, &pname, result);
97 collect_static_plugin_metadata(plugin, root, result);
98}
99
100fn collect_static_plugin_rules(
103 plugin: &dyn Plugin,
104 pname: &str,
105 result: &mut AggregatedPluginResult,
106) {
107 for rule in plugin.entry_pattern_rules() {
108 result.entry_patterns.push((rule, pname.to_string()));
109 }
110 for pat in plugin.config_patterns() {
111 result.config_patterns.push((*pat).to_string());
112 }
113 let opt_out = plugin.config_default_export_opt_out();
114 push_config_default_exports(
115 pname,
116 plugin
117 .config_patterns()
118 .iter()
119 .copied()
120 .filter(|pat| !opt_out.contains(pat)),
121 result,
122 );
123 for (pat, exports) in plugin.config_file_exports() {
124 result.config_export_credits.push(PluginUsedExportRule::new(
125 pname,
126 UsedExportRule::from_static(pat, exports),
127 ));
128 }
129 for pat in plugin.always_used() {
130 result
131 .always_used
132 .push(((*pat).to_string(), pname.to_string()));
133 }
134 for rule in plugin.used_export_rules() {
135 result
136 .used_exports
137 .push(PluginUsedExportRule::new(pname.to_string(), rule));
138 }
139 for member in plugin.used_class_members() {
140 result
141 .used_class_members
142 .push(UsedClassMemberRule::from(*member));
143 }
144 for rule in plugin.used_class_member_rules() {
145 result.used_class_members.push(rule);
146 }
147 result
148 .framework_class_member_contracts
149 .extend(plugin.framework_class_member_contracts());
150 for pat in plugin.fixture_glob_patterns() {
151 result
152 .fixture_patterns
153 .push(((*pat).to_string(), pname.to_string()));
154 }
155}
156
157fn collect_static_plugin_metadata(
160 plugin: &dyn Plugin,
161 root: &Path,
162 result: &mut AggregatedPluginResult,
163) {
164 for dep in plugin.tooling_dependencies() {
165 result.tooling_dependencies.push((*dep).to_string());
166 }
167 for prefix in plugin.virtual_module_prefixes() {
168 result.virtual_module_prefixes.push((*prefix).to_string());
169 }
170 for suffix in plugin.virtual_package_suffixes() {
171 result.virtual_package_suffixes.push((*suffix).to_string());
172 }
173 for pattern in plugin.generated_import_patterns() {
174 result
175 .generated_import_patterns
176 .push((*pattern).to_string());
177 }
178 for prefix in plugin.generated_type_import_prefixes() {
179 result
180 .generated_type_import_prefixes
181 .push((*prefix).to_string());
182 }
183 if let Some(package) = plugin.virtual_module_package() {
184 result.virtual_module_providers.extend(
185 plugin
186 .virtual_module_prefixes()
187 .iter()
188 .map(|prefix| VirtualModuleProviderRule {
189 plugin: plugin.name().to_string(),
190 scope: String::new(),
191 matcher: VirtualModuleMatch::Prefix((*prefix).to_string()),
192 package: package.to_string(),
193 })
194 .chain(plugin.generated_import_patterns().iter().map(|pattern| {
195 VirtualModuleProviderRule {
196 plugin: plugin.name().to_string(),
197 scope: String::new(),
198 matcher: VirtualModuleMatch::Generated((*pattern).to_string()),
199 package: package.to_string(),
200 }
201 })),
202 );
203 }
204 for (prefix, replacement) in plugin.path_aliases(root) {
205 result.path_aliases.push((prefix.to_string(), replacement));
206 }
207 result
208 .framework_static_dir_mappings
209 .extend(plugin.static_dir_mappings(root));
210 result
211 .auto_imports
212 .extend(plugin.auto_imports(root).into_iter().map(|mut rule| {
213 if rule.scope.is_empty() {
214 rule.scope.push(root.to_path_buf());
215 }
216 rule
217 }));
218 result
219 .provided_dependencies
220 .extend(plugin.provided_dependencies());
221}
222
223pub fn process_package_json_metadata(
225 active: &[&dyn Plugin],
226 pkg: &PackageJson,
227 root: &Path,
228 result: &mut AggregatedPluginResult,
229 regex_errors: &mut Vec<PluginRegexValidationError>,
230) {
231 for plugin in active {
232 let package_referenced = plugin.package_json_referenced_dependencies(pkg, root);
233 if !package_referenced.is_empty() {
234 let pkg_path = root.join("package.json");
235 result.package_referenced_dependencies.extend(
236 package_referenced
237 .into_iter()
238 .map(|dep| (pkg_path.clone(), dep)),
239 );
240 }
241 let plugin_result = plugin.resolve_package_json(pkg, root);
242 if plugin_result.is_empty() {
243 continue;
244 }
245 tracing::debug!(
246 plugin = plugin.name(),
247 deps = plugin_result.referenced_dependencies.len(),
248 "resolved package.json metadata"
249 );
250 if let Err(mut errors) = process_config_result(plugin.name(), plugin_result, result, None) {
251 regex_errors.append(&mut errors);
252 }
253 }
254}
255
256pub fn is_external_plugin_active(
261 ext: &ExternalPluginDef,
262 all_deps: &[String],
263 root: &Path,
264 discovered_files: &[PathBuf],
265) -> bool {
266 if !ext.has_activation_condition() {
267 return false;
268 }
269 if let Some(detection) = &ext.detection {
270 let all_dep_refs: Vec<&str> = all_deps.iter().map(String::as_str).collect();
271 return check_plugin_detection(detection, &all_dep_refs, root, discovered_files);
272 }
273 ext.enablers.iter().any(|enabler| {
274 if enabler.ends_with('/') {
275 all_deps.iter().any(|d| d.starts_with(enabler))
276 } else {
277 all_deps.iter().any(|d| d == enabler)
278 }
279 })
280}
281
282pub fn process_external_plugins(
284 external_plugins: &[ExternalPluginDef],
285 all_deps: &[String],
286 root: &Path,
287 discovered_files: &[PathBuf],
288 result: &mut AggregatedPluginResult,
289) {
290 for ext in external_plugins {
291 let is_active = is_external_plugin_active(ext, all_deps, root, discovered_files);
292 if is_active {
293 result.active_plugins.push(ext.name.clone());
294 result
295 .entry_point_roles
296 .insert(ext.name.clone(), ext.effective_entry_point_role());
297 result.entry_patterns.extend(
298 ext.entry_points
299 .iter()
300 .map(|p| (PathRule::new(p.clone()), ext.name.clone())),
301 );
302 if !ext.manifest_entries.is_empty() {
303 result.entry_patterns.extend(
304 crate::plugins::manifest_entries::evaluate_manifest_entries(ext, root)
305 .into_iter()
306 .map(|rule| (rule, ext.name.clone())),
307 );
308 }
309 result.config_patterns.extend(ext.config_patterns.clone());
310 push_config_default_exports(
311 &ext.name,
312 ext.config_patterns
313 .iter()
314 .filter(|pat| !ext.config_default_export_opt_out.contains(pat))
315 .map(String::as_str),
316 result,
317 );
318 result.always_used.extend(
319 ext.config_patterns
320 .iter()
321 .chain(ext.always_used.iter())
322 .map(|p| (p.clone(), ext.name.clone())),
323 );
324 result
325 .tooling_dependencies
326 .extend(ext.tooling_dependencies.clone());
327 for ue in &ext.used_exports {
328 result.used_exports.push(PluginUsedExportRule::new(
329 ext.name.clone(),
330 UsedExportRule::new(ue.pattern.clone(), ue.exports.clone()),
331 ));
332 }
333 result
334 .used_class_members
335 .extend(ext.used_class_members.iter().cloned());
336 }
337 }
338}
339
340pub struct ConfigCandidateIndex {
348 dirs: FxHashMap<PathBuf, FxHashSet<OsString>>,
349 sorted_dirs: std::sync::OnceLock<Vec<PathBuf>>,
354}
355
356impl ConfigCandidateIndex {
357 #[must_use]
361 pub(crate) fn build<'a>(paths: impl IntoIterator<Item = &'a Path>) -> Self {
362 let mut dirs: FxHashMap<PathBuf, FxHashSet<OsString>> = FxHashMap::default();
363 for path in paths {
364 if let (Some(parent), Some(name)) = (path.parent(), path.file_name()) {
365 dirs.entry(parent.to_path_buf())
366 .or_default()
367 .insert(name.to_os_string());
368 }
369 }
370 Self {
371 dirs,
372 sorted_dirs: std::sync::OnceLock::new(),
373 }
374 }
375
376 fn dirs_under<'a>(
378 &'a self,
379 root: &'a Path,
380 ) -> impl Iterator<Item = &'a FxHashSet<OsString>> + 'a {
381 let sorted = self.sorted_dirs.get_or_init(|| {
382 let mut sorted: Vec<PathBuf> = self.dirs.keys().cloned().collect();
383 sorted.sort_unstable();
384 sorted
385 });
386 let start = sorted.partition_point(|dir| dir.as_path() < root);
387 sorted[start..]
388 .iter()
389 .take_while(move |dir| {
390 count_dir_check();
391 dir.starts_with(root)
392 })
393 .filter_map(|dir| self.dirs.get(dir))
394 }
395
396 #[must_use]
398 pub(crate) fn contains_file(&self, path: &Path) -> bool {
399 match (path.parent(), path.file_name()) {
400 (Some(dir), Some(name)) => self.dir_contains(dir, name),
401 _ => false,
402 }
403 }
404
405 #[must_use]
409 pub(crate) fn dir_contains(&self, dir: &Path, name: &OsStr) -> bool {
410 self.dirs.get(dir).is_some_and(|names| names.contains(name))
411 }
412
413 #[must_use]
418 pub(crate) fn any_descendant_contains(&self, root: &Path, name: &OsStr) -> bool {
419 self.dirs_under(root).any(|names| names.contains(name))
420 }
421
422 #[must_use]
428 pub(crate) fn any_descendant_matches(
429 &self,
430 root: &Path,
431 matcher: &globset::GlobMatcher,
432 ) -> bool {
433 self.dirs_under(root)
434 .any(|names| names.iter().any(|name| matcher.is_match(Path::new(name))))
435 }
436
437 pub(super) fn names_in_dir(&self, dir: &Path) -> Option<&FxHashSet<OsString>> {
439 self.dirs.get(dir)
440 }
441
442 pub(super) fn glob_matches_in_dir(
443 &self,
444 dir: &Path,
445 matcher: &globset::GlobMatcher,
446 ) -> Vec<PathBuf> {
447 self.dirs.get(dir).map_or_else(Vec::new, |names| {
448 names
449 .iter()
450 .filter(|name| matcher.is_match(Path::new(name)))
451 .map(|name| dir.join(name))
452 .collect()
453 })
454 }
455}
456
457#[cfg(test)]
458std::thread_local! {
459 static DIR_CHECKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
460}
461
462#[cfg_attr(not(test), inline(always))]
465fn count_dir_check() {
466 #[cfg(test)]
467 DIR_CHECKS.with(|checks| checks.set(checks.get() + 1));
468}
469
470pub fn discover_config_files<'a>(
490 config_matchers: &[(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
491 resolved_plugins: &FxHashSet<&str>,
492 roots: &[&Path],
493 production_mode: bool,
494 candidate_index: Option<&ConfigCandidateIndex>,
495) -> Vec<(PathBuf, &'a dyn Plugin)> {
496 use rayon::prelude::*;
497 let mut pending: Vec<(&'a dyn Plugin, &Path, String, bool)> = Vec::new();
498 for (plugin, _) in config_matchers {
499 let resolved = resolved_plugins.contains(plugin.name());
505 for root in roots {
506 for pat in plugin.config_patterns() {
507 if !production_mode && is_source_ext_root_pattern(pat) {
508 continue;
509 }
510 if resolved
511 && !pattern_needs_filesystem(pat)
512 && pattern_names_only_source_files(pat)
513 {
514 continue;
515 }
516 pending.push((*plugin, *root, pat.to_string(), resolved));
517 }
518 }
519 }
520
521 let hits: Vec<(PathBuf, &'a dyn Plugin)> = pending
522 .par_iter()
523 .flat_map_iter(|(plugin, root, pat, resolved)| {
524 expand_brace_pattern(pat)
525 .into_iter()
526 .flat_map(|expanded| {
527 let needs_fs = pattern_needs_filesystem(&expanded);
528 let paths = match candidate_index {
529 Some(index) if !needs_fs => match_pattern_in_index(root, &expanded, index),
535 _ => discover_pattern_matches(root, &expanded),
536 };
537 paths
538 .into_iter()
539 .filter(move |path| {
540 !*resolved || !phase_3a_read_file(path, needs_fs, candidate_index)
541 })
542 .map(move |path| (path, *plugin))
543 })
544 .collect::<Vec<_>>()
545 })
546 .collect();
547
548 let mut seen: FxHashSet<(PathBuf, &'a str)> = FxHashSet::default();
549 let mut config_files: Vec<(PathBuf, &'a dyn Plugin)> = Vec::with_capacity(hits.len());
550 for (path, plugin) in hits {
551 if seen.insert((path.clone(), plugin.name())) {
552 config_files.push((path, plugin));
553 }
554 }
555 config_files
556}
557
558fn pattern_names_only_source_files(pattern: &str) -> bool {
563 expand_brace_pattern(pattern)
564 .iter()
565 .all(|expanded| has_source_extension(Path::new(expanded)))
566}
567
568fn has_source_extension(path: &Path) -> bool {
569 path.extension()
570 .and_then(|ext| ext.to_str())
571 .is_some_and(|ext| SOURCE_EXTENSIONS.contains(&ext))
572}
573
574fn phase_3a_read_file(
579 path: &Path,
580 needs_fs: bool,
581 candidate_index: Option<&ConfigCandidateIndex>,
582) -> bool {
583 if needs_fs {
584 return candidate_index.is_some_and(|index| index.contains_file(path));
585 }
586 has_source_extension(path)
587}
588
589fn pattern_has_glob(pattern: &str) -> bool {
590 pattern.contains('*') || pattern.contains('?') || pattern.contains('[')
591}
592
593pub(super) fn pattern_needs_filesystem(pattern: &str) -> bool {
600 let mut components = pattern.split('/').peekable();
601 let mut needs_fs = false;
602 while let Some(component) = components.next() {
603 if components.peek().is_none() {
604 break; }
606 if component.starts_with('.')
607 && component != "."
608 && component != ".."
609 && !crate::discover::is_allowed_hidden_dir(OsStr::new(component))
610 {
611 needs_fs = true;
612 break;
613 }
614 if is_default_ignored_directory(component) {
615 needs_fs = true;
616 break;
617 }
618 }
619 needs_fs
620}
621
622fn is_default_ignored_directory(name: &str) -> bool {
625 fallow_config::DEFAULT_IGNORE_PATTERNS
626 .iter()
627 .any(|pattern| {
628 pattern
629 .strip_prefix("**/")
630 .and_then(|rest| rest.strip_suffix("/**"))
631 .is_some_and(|directory| directory == name)
632 })
633}
634
635fn match_pattern_in_index(
640 root: &Path,
641 pattern: &str,
642 index: &ConfigCandidateIndex,
643) -> Vec<PathBuf> {
644 if !pattern_has_glob(pattern) {
645 let path = root.join(pattern);
646 return match (path.parent(), path.file_name()) {
647 (Some(dir), Some(name)) if index.dir_contains(dir, name) => vec![path],
648 _ => Vec::new(),
649 };
650 }
651
652 if let Some(stripped) = pattern.strip_prefix("**/") {
653 return match_pattern_in_index(root, stripped, index);
654 }
655
656 let (dir, file_pattern) = match pattern.rsplit_once('/') {
657 Some((parent, file_pattern)) if !pattern_has_glob(parent) => {
658 (root.join(parent), file_pattern)
659 }
660 Some(_) => return Vec::new(),
661 None => (root.to_path_buf(), pattern),
662 };
663
664 let Ok(matcher) = globset::Glob::new(file_pattern).map(|g| g.compile_matcher()) else {
665 return Vec::new();
666 };
667 index.glob_matches_in_dir(&dir, &matcher)
668}
669
670fn discover_pattern_matches(root: &Path, pattern: &str) -> Vec<PathBuf> {
671 if !pattern_has_glob(pattern) {
672 let path = root.join(pattern);
673 return if crate::discover::project_read::is_project_file(root, &path) {
674 vec![path]
675 } else {
676 Vec::new()
677 };
678 }
679
680 if let Some(stripped) = pattern.strip_prefix("**/") {
681 return discover_pattern_matches(root, stripped);
682 }
683
684 let (dir, file_pattern) = match pattern.rsplit_once('/') {
685 Some((parent, file_pattern)) if !pattern_has_glob(parent) => {
686 (root.join(parent), file_pattern)
687 }
688 Some(_) => return Vec::new(),
689 None => (root.to_path_buf(), pattern),
690 };
691
692 scan_dir_for_pattern(root, &dir, file_pattern)
693}
694
695fn scan_dir_for_pattern(root: &Path, dir: &Path, file_pattern: &str) -> Vec<PathBuf> {
696 if !dir.is_dir() {
701 return Vec::new();
702 }
703 let Ok(matcher) = globset::Glob::new(file_pattern).map(|g| g.compile_matcher()) else {
704 return Vec::new();
705 };
706 let Some(entries) = crate::discover::project_read::read_project_dir(root, dir) else {
707 return Vec::new();
708 };
709
710 entries
711 .filter_map(Result::ok)
712 .map(|entry| entry.path())
713 .filter(|path| crate::discover::project_read::is_project_file(root, path))
714 .filter(|path| {
715 path.file_name()
716 .is_some_and(|name| matcher.is_match(std::path::Path::new(name)))
717 })
718 .collect()
719}
720
721pub(super) fn expand_brace_pattern(pattern: &str) -> Vec<String> {
725 let mut expanded = expand_brace_groups(pattern);
726 expanded.retain(|text| {
727 fallow_config::glob_validation::validate_user_path(text, "configPatterns").is_ok()
728 });
729 expanded
730}
731
732fn expand_brace_groups(pattern: &str) -> Vec<String> {
733 let Some(open) = pattern.find('{') else {
734 return vec![pattern.to_string()];
735 };
736 let Some(close_rel) = pattern[open + 1..].find('}') else {
737 return vec![pattern.to_string()];
738 };
739 let close = open + 1 + close_rel;
740
741 let prefix = &pattern[..open];
742 let suffix = &pattern[close + 1..];
743 let inner = &pattern[open + 1..close];
744 let mut expanded = Vec::new();
745 for option in inner.split(',') {
746 for tail in expand_brace_groups(suffix) {
747 expanded.push(format!("{prefix}{option}{tail}"));
748 }
749 }
750 expanded
751}
752
753fn collect_path_rule_regex_errors(
758 rule: &crate::plugins::PathRule,
759 plugin_name: &str,
760 config_path: Option<&Path>,
761 rule_kind: &'static str,
762 errors: &mut Vec<PluginRegexValidationError>,
763) {
764 for pattern in &rule.exclude_regexes {
765 if let Err(source) = regex::Regex::new(pattern) {
766 errors.push(PluginRegexValidationError::new(
767 PluginRegexValidationErrorInput {
768 plugin_name,
769 config_path,
770 rule_kind,
771 field: "exclude_regexes",
772 rule_pattern: &rule.pattern,
773 regex_pattern: pattern,
774 source: &source,
775 },
776 ));
777 }
778 }
779 for pattern in &rule.exclude_segment_regexes {
780 if let Err(source) = regex::Regex::new(pattern) {
781 errors.push(PluginRegexValidationError::new(
782 PluginRegexValidationErrorInput {
783 plugin_name,
784 config_path,
785 rule_kind,
786 field: "exclude_segment_regexes",
787 rule_pattern: &rule.pattern,
788 regex_pattern: pattern,
789 source: &source,
790 },
791 ));
792 }
793 }
794}
795
796pub fn process_config_result(
802 plugin_name: &str,
803 plugin_result: PluginResult,
804 result: &mut AggregatedPluginResult,
805 config_path: Option<&Path>,
806) -> Result<(), Vec<PluginRegexValidationError>> {
807 let mut regex_errors = Vec::new();
808
809 for rule in &plugin_result.entry_patterns {
810 collect_path_rule_regex_errors(
811 rule,
812 plugin_name,
813 config_path,
814 "entry_patterns[]",
815 &mut regex_errors,
816 );
817 }
818 for rule in &plugin_result.used_exports {
819 collect_path_rule_regex_errors(
820 &rule.path,
821 plugin_name,
822 config_path,
823 "used_exports[].path",
824 &mut regex_errors,
825 );
826 }
827 if !regex_errors.is_empty() {
828 return Err(regex_errors);
829 }
830 merge_plugin_result_fields(plugin_name, plugin_result, result);
831 Ok(())
832}
833
834fn merge_entry_patterns(
837 pname: &str,
838 plugin_result: &mut PluginResult,
839 result: &mut AggregatedPluginResult,
840) {
841 if plugin_result.replace_entry_patterns && !plugin_result.entry_patterns.is_empty() {
842 let first_replacement = result.replaced_entry_plugins.insert(pname.to_string());
843 if !plugin_result.accumulate_config_entry_patterns {
844 result.entry_patterns.retain(|(_, name)| name != pname);
845 } else if first_replacement {
846 let config_patterns = &result.config_entry_patterns;
850 result.entry_patterns.retain(|(rule, name)| {
851 name != pname || config_patterns.contains(&(name.clone(), rule.pattern.clone()))
852 });
853 }
854 }
855 if plugin_result.accumulate_config_entry_patterns {
856 result.config_entry_patterns.extend(
857 plugin_result
858 .entry_patterns
859 .iter()
860 .map(|rule| (pname.to_string(), rule.pattern.clone())),
861 );
862 }
863 result.entry_patterns.extend(
864 std::mem::take(&mut plugin_result.entry_patterns)
865 .into_iter()
866 .map(|rule| (rule, pname.to_string())),
867 );
868}
869
870fn merge_path_aliases(
874 path_aliases: Vec<(String, String)>,
875 checked_alias_prefixes: Vec<String>,
876 result: &mut AggregatedPluginResult,
877) {
878 for (prefix, replacement) in path_aliases {
879 result
880 .path_aliases
881 .retain(|(existing_prefix, _)| existing_prefix != &prefix);
882 result
883 .checked_alias_prefixes
884 .retain(|checked| checked.prefix != prefix);
885 result.path_aliases.push((prefix, replacement));
886 }
887 result
888 .checked_alias_prefixes
889 .extend(
890 checked_alias_prefixes
891 .into_iter()
892 .map(|prefix| super::CheckedAliasPrefix {
893 scope: String::new(),
894 prefix,
895 }),
896 );
897}
898
899fn merge_plugin_result_fields(
903 pname: &str,
904 mut plugin_result: PluginResult,
905 result: &mut AggregatedPluginResult,
906) {
907 merge_entry_patterns(pname, &mut plugin_result, result);
908 if plugin_result.replace_used_export_rules && !plugin_result.used_exports.is_empty() {
909 result.used_exports.retain(|rule| rule.plugin_name != pname);
910 }
911 result.used_exports.extend(
912 plugin_result
913 .used_exports
914 .into_iter()
915 .map(|rule| PluginUsedExportRule::new(pname.to_string(), rule)),
916 );
917 result.config_export_credits.extend(
918 plugin_result
919 .entry_export_credits
920 .into_iter()
921 .map(|rule| PluginUsedExportRule::new(pname.to_string(), rule)),
922 );
923 result
924 .used_class_members
925 .extend(plugin_result.used_class_members);
926 result
927 .referenced_dependencies
928 .extend(plugin_result.referenced_dependencies);
929 result
930 .package_referenced_dependencies
931 .extend(plugin_result.package_referenced_dependencies);
932 super::push_missing(
933 &mut result.required_dependencies,
934 plugin_result.required_dependencies,
935 );
936 result.discovered_always_used.extend(
937 plugin_result
938 .always_used_files
939 .into_iter()
940 .map(|p| (p, pname.to_string())),
941 );
942 merge_path_aliases(
943 plugin_result.path_aliases,
944 plugin_result.checked_alias_prefixes,
945 result,
946 );
947 result.setup_files.extend(
948 plugin_result
949 .setup_files
950 .into_iter()
951 .map(|p| (p, pname.to_string())),
952 );
953 result.fixture_patterns.extend(
954 plugin_result
955 .fixture_patterns
956 .into_iter()
957 .map(|p| (p, pname.to_string())),
958 );
959 result
960 .scss_include_paths
961 .extend(plugin_result.scss_include_paths);
962 result
963 .static_dir_mappings
964 .extend(plugin_result.static_dir_mappings);
965 result
966 .framework_static_dir_mappings
967 .extend(plugin_result.framework_static_dir_mappings);
968 result
969 .provided_dependencies
970 .extend(plugin_result.provided_dependencies);
971 result
972 .federation_sources
973 .extend(plugin_result.federation_sources);
974 for rule in plugin_result.jsx_import_sources {
975 if !result.jsx_import_sources.contains(&rule) {
976 result.jsx_import_sources.push(rule);
977 }
978 }
979 for rule in plugin_result.jsx_package_credits {
980 if !result.jsx_package_credits.contains(&rule) {
981 result.jsx_package_credits.push(rule);
982 }
983 }
984 super::push_missing(
985 &mut result.web_server_app_dirs,
986 plugin_result.web_server_app_dirs,
987 );
988 for dir in plugin_result.tsconfig_jsx_dirs {
989 if !result.tsconfig_jsx_dirs.contains(&dir) {
990 result.tsconfig_jsx_dirs.push(dir);
991 }
992 }
993 for diagnostic in plugin_result.config_diagnostics {
994 if !result.config_diagnostics.contains(&diagnostic) {
995 result.config_diagnostics.push(diagnostic);
996 }
997 }
998}
999
1000pub fn check_has_config_file(
1002 plugin: &dyn Plugin,
1003 config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
1004 relative_files: &[(PathBuf, String)],
1005) -> bool {
1006 !plugin.config_patterns().is_empty()
1007 && config_matchers.iter().any(|(p, matchers)| {
1008 p.name() == plugin.name()
1009 && relative_files
1010 .iter()
1011 .any(|(_, rel)| matchers.iter().any(|m| m.is_match(rel.as_str())))
1012 })
1013}
1014
1015pub fn check_plugin_detection(
1017 detection: &PluginDetection,
1018 all_deps: &[&str],
1019 root: &Path,
1020 discovered_files: &[PathBuf],
1021) -> bool {
1022 match detection {
1023 PluginDetection::Dependency { package } => all_deps.iter().any(|d| *d == package),
1024 PluginDetection::FileExists { pattern } => {
1025 if let Ok(matcher) =
1026 fallow_config::compile_path_glob(pattern).map(|g| g.compile_matcher())
1027 {
1028 for file in discovered_files {
1029 let relative = file.strip_prefix(root).unwrap_or(file);
1030 if matcher.is_match(relative) {
1031 return true;
1032 }
1033 }
1034 }
1035 !fallow_config::glob_validation::escapes_project_root(pattern)
1039 && fallow_config::glob_validation::expand_disk_glob(root, pattern).is_some_and(
1040 |paths| {
1041 paths
1042 .filter_map(Result::ok)
1043 .any(|path| crate::discover::project_read::is_inside_scope(root, &path))
1044 },
1045 )
1046 }
1047 PluginDetection::All { conditions } => conditions
1048 .iter()
1049 .all(|c| check_plugin_detection(c, all_deps, root, discovered_files)),
1050 PluginDetection::Any { conditions } => conditions
1051 .iter()
1052 .any(|c| check_plugin_detection(c, all_deps, root, discovered_files)),
1053 }
1054}
1055
1056#[cfg(test)]
1057mod tests {
1058 use super::*;
1059
1060 #[test]
1061 fn brace_expansions_that_leave_the_root_are_dropped() {
1062 assert_eq!(expand_brace_pattern("{..,x}/a.json"), vec!["x/a.json"]);
1063 assert_eq!(expand_brace_pattern("{/abs/name,b}"), vec!["b"]);
1064 assert!(expand_brace_pattern("../a.json").is_empty());
1065 assert_eq!(
1066 expand_brace_pattern("{vite,vitest}.config.ts"),
1067 vec!["vite.config.ts", "vitest.config.ts"]
1068 );
1069 }
1070
1071 #[test]
1072 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1073 fn config_file_probes_stay_inside_the_root() {
1074 let dir = tempfile::tempdir().unwrap();
1075 let root = dir.path().join("project");
1076 std::fs::create_dir(&root).unwrap();
1077 std::fs::write(dir.path().join("outside.json"), "{}").unwrap();
1078 let hits: Vec<PathBuf> = expand_brace_pattern("{..,x}/outside.json")
1079 .iter()
1080 .flat_map(|pattern| discover_pattern_matches(&root, pattern))
1081 .collect();
1082 assert!(hits.is_empty(), "{hits:?}");
1083 }
1084
1085 #[test]
1086 #[cfg(unix)]
1087 fn file_exists_detection_skips_a_match_through_a_link_out_of_the_root() {
1088 let dir = tempfile::tempdir().expect("temp dir");
1089 let root = dir.path().join("project");
1090 let outside = dir.path().join("elsewhere");
1091 std::fs::create_dir_all(&root).expect("mkdir");
1092 std::fs::create_dir_all(&outside).expect("mkdir");
1093 std::fs::write(outside.join("found.txt"), "").expect("write");
1094 std::os::unix::fs::symlink(&outside, root.join("linked")).expect("link");
1095 let detection = PluginDetection::FileExists {
1096 pattern: "linked/f*".to_owned(),
1097 };
1098 assert!(!check_plugin_detection(&detection, &[], &root, &[]));
1099 }
1100
1101 #[test]
1104 #[cfg(unix)]
1105 fn file_exists_detection_follows_a_link_into_the_work_tree() {
1106 let dir = tempfile::tempdir().expect("temp dir");
1107 let top = dir.path().join("repo");
1108 let root = top.join("packages/app");
1109 std::fs::create_dir_all(&root).expect("mkdir");
1110 std::fs::create_dir(top.join(".git")).expect("mkdir");
1111 std::fs::write(top.join("jest.base.js"), "").expect("write");
1112 std::os::unix::fs::symlink("../../jest.base.js", root.join("jest.config.js"))
1113 .expect("link");
1114 let detection = PluginDetection::FileExists {
1115 pattern: "jest.config.*".to_owned(),
1116 };
1117 assert!(check_plugin_detection(&detection, &[], &root, &[]));
1118 }
1119
1120 #[test]
1121 fn file_exists_detection_never_matches_above_the_root() {
1122 let dir = tempfile::tempdir().expect("temp dir");
1123 let root = dir.path().join("project");
1124 std::fs::create_dir_all(&root).expect("mkdir");
1125 std::fs::write(dir.path().join("found.txt"), "").expect("write");
1126 let detection = PluginDetection::FileExists {
1127 pattern: "../f*".to_owned(),
1128 };
1129 assert!(!check_plugin_detection(&detection, &[], &root, &[]));
1130 }
1131
1132 #[test]
1133 fn pattern_needs_filesystem_only_for_non_allowlisted_hidden_dirs() {
1134 assert!(pattern_needs_filesystem(".config/prisma.ts"));
1137 assert!(!pattern_needs_filesystem("tsconfig.json"));
1140 assert!(!pattern_needs_filesystem("prisma/schema.prisma"));
1141 assert!(!pattern_needs_filesystem(".eslintrc.json"));
1142 assert!(!pattern_needs_filesystem("**/project.json"));
1143 assert!(!pattern_needs_filesystem(".storybook/main.ts"));
1144 assert!(!pattern_needs_filesystem("a/b/c.json"));
1145 assert!(pattern_needs_filesystem("build/webpack.prod.js"));
1147 assert!(!pattern_needs_filesystem("config/webpack.prod.js"));
1148 }
1149
1150 #[test]
1151 fn config_candidate_index_matches_plain_nested_and_glob_shapes() {
1152 let root = Path::new("/project");
1153 let index = ConfigCandidateIndex::build([
1154 Path::new("/project/tsconfig.json"),
1155 Path::new("/project/packages/a/tsconfig.json"),
1156 Path::new("/project/prisma/schema.prisma"),
1157 Path::new("/project/src/main.ts"),
1158 ]);
1159
1160 assert_eq!(
1162 match_pattern_in_index(root, "tsconfig.json", &index),
1163 vec![PathBuf::from("/project/tsconfig.json")]
1164 );
1165 assert_eq!(
1166 match_pattern_in_index(Path::new("/project/packages/a"), "tsconfig.json", &index),
1167 vec![PathBuf::from("/project/packages/a/tsconfig.json")]
1168 );
1169 assert_eq!(
1171 match_pattern_in_index(root, "prisma/schema.prisma", &index),
1172 vec![PathBuf::from("/project/prisma/schema.prisma")]
1173 );
1174 assert_eq!(
1175 match_pattern_in_index(root, "**/tsconfig.json", &index),
1176 vec![PathBuf::from("/project/tsconfig.json")]
1177 );
1178 assert_eq!(
1179 match_pattern_in_index(Path::new("/project/prisma"), "*.prisma", &index),
1180 vec![PathBuf::from("/project/prisma/schema.prisma")]
1181 );
1182 assert!(match_pattern_in_index(root, "missing.json", &index).is_empty());
1184 }
1185
1186 #[test]
1187 fn descendant_queries_visit_only_folders_under_the_root() {
1188 let mut paths: Vec<PathBuf> = (0..200)
1189 .map(|i| PathBuf::from(format!("/project/packages/p{i}/src/index.ts")))
1190 .collect();
1191 paths.push(PathBuf::from("/project/packages/p7/mkdocs.yml"));
1192 paths.push(PathBuf::from("/project/packages/p9/tsconfig.app.json"));
1193 paths.push(PathBuf::from("/project/packages/p1-docs/mkdocs.yml"));
1194 let index = ConfigCandidateIndex::build(paths.iter().map(PathBuf::as_path));
1195 let matcher = globset::Glob::new("tsconfig.*.json")
1196 .expect("valid glob")
1197 .compile_matcher();
1198
1199 let p7 = Path::new("/project/packages/p7");
1200 let p8 = Path::new("/project/packages/p8");
1201 let p9 = Path::new("/project/packages/p9");
1202 let before = DIR_CHECKS.with(std::cell::Cell::get);
1203 assert!(index.any_descendant_contains(p7, OsStr::new("mkdocs.yml")));
1204 assert!(!index.any_descendant_contains(p8, OsStr::new("mkdocs.yml")));
1205 assert!(index.any_descendant_matches(p9, &matcher));
1206 assert!(!index.any_descendant_matches(p7, &matcher));
1207 let checks = DIR_CHECKS.with(std::cell::Cell::get) - before;
1208 assert!(
1209 checks <= 12,
1210 "four workspace queries compared {checks} folders; each workspace has two"
1211 );
1212
1213 assert!(index.any_descendant_contains(Path::new("/project"), OsStr::new("mkdocs.yml")));
1214 assert!(!index.any_descendant_contains(Path::new("/project"), OsStr::new("missing.yml")));
1215 assert!(index.any_descendant_matches(Path::new("/project"), &matcher));
1216 let p1 = Path::new("/project/packages/p1");
1218 assert!(index.any_descendant_contains(p1, OsStr::new("index.ts")));
1219 assert!(!index.any_descendant_contains(p1, OsStr::new("mkdocs.yml")));
1220 }
1221
1222 #[test]
1223 fn descendant_queries_match_a_scan_of_all_folders() {
1224 let paths: Vec<PathBuf> = [
1225 "/project/mkdocs.yml",
1226 "/project/a/src/index.ts",
1227 "/project/a b/mkdocs.yml",
1228 "/project/a-b/tsconfig.app.json",
1229 "/project/a.b/.env.schema",
1230 "/project/a/b/c/tsconfig.base.json",
1231 "/project/ab/mkdocs.yml",
1232 "/project/a1/.env.schema",
1233 "/project/a10/src/index.ts",
1234 "/other/mkdocs.yml",
1235 ]
1236 .iter()
1237 .map(PathBuf::from)
1238 .collect();
1239 let index = ConfigCandidateIndex::build(paths.iter().map(PathBuf::as_path));
1240 let matcher = globset::Glob::new("tsconfig.*.json")
1241 .expect("valid glob")
1242 .compile_matcher();
1243 let scan = |root: &Path, hit: &dyn Fn(&OsStr) -> bool| {
1244 paths.iter().any(|path| {
1245 path.parent().is_some_and(|dir| dir.starts_with(root))
1246 && path.file_name().is_some_and(hit)
1247 })
1248 };
1249 let names = ["mkdocs.yml", ".env.schema", "index.ts", "missing"];
1250 for root in [
1251 "/",
1252 "/project",
1253 "/project/",
1254 "/project/./a",
1255 "/project/a",
1256 "/project/a/",
1257 "/project/a b",
1258 "/project/a-b",
1259 "/project/a.b",
1260 "/project/a1",
1261 "/project/a/b",
1262 "/project/absent",
1263 "/proj",
1264 "project",
1265 "",
1266 "/other",
1267 ] {
1268 let root = Path::new(root);
1269 for name in names {
1270 assert_eq!(
1271 index.any_descendant_contains(root, OsStr::new(name)),
1272 scan(root, &|file| file == name),
1273 "contains {name} under {}",
1274 root.display()
1275 );
1276 }
1277 assert_eq!(
1278 index.any_descendant_matches(root, &matcher),
1279 scan(root, &|file| matcher.is_match(Path::new(file))),
1280 "matches under {}",
1281 root.display()
1282 );
1283 }
1284 }
1285
1286 #[test]
1287 fn glob_probe_skips_the_scope_check_for_a_missing_directory() {
1288 let base = tempfile::tempdir().expect("create temp dir");
1289 let root = base.path().join("project");
1290 std::fs::create_dir_all(root.join("src")).expect("create project dirs");
1291
1292 let before = crate::discover::project_read::guarded_dir_reads_for_test();
1293 assert!(discover_pattern_matches(&root.join("src"), ".config/*.ts").is_empty());
1294 assert_eq!(
1295 crate::discover::project_read::guarded_dir_reads_for_test(),
1296 before,
1297 "a probe of a missing directory listed the directory"
1298 );
1299
1300 std::fs::create_dir_all(root.join("src/.config")).expect("create config dir");
1301 std::fs::write(root.join("src/.config/tool.ts"), "").expect("write config");
1302 assert_eq!(
1303 discover_pattern_matches(&root.join("src"), ".config/*.ts"),
1304 vec![root.join("src/.config/tool.ts")]
1305 );
1306 }
1307
1308 #[test]
1309 fn file_exists_detection_never_matches_outside_root() {
1310 let base = tempfile::tempdir().expect("create temp dir");
1311 let root = base.path().join("project");
1312 std::fs::create_dir_all(root.join(".config")).expect("create project dirs");
1313 std::fs::write(base.path().join("outside-marker.json"), "{}").expect("write marker");
1314
1315 for pattern in [".*/outside-marker.json", "..*/outside-marker.json"] {
1318 let detection = PluginDetection::FileExists {
1319 pattern: pattern.to_string(),
1320 };
1321 assert!(
1322 !check_plugin_detection(&detection, &[], &root, &[]),
1323 "{pattern} matched a file outside the project root"
1324 );
1325 }
1326
1327 std::fs::write(root.join(".config").join("outside-marker.json"), "{}")
1328 .expect("write marker inside root");
1329 let detection = PluginDetection::FileExists {
1330 pattern: ".*/outside-marker.json".to_string(),
1331 };
1332 assert!(check_plugin_detection(&detection, &[], &root, &[]));
1333 }
1334
1335 #[test]
1336 fn file_exists_detection_works_under_a_root_with_glob_characters() {
1337 let base = tempfile::tempdir().expect("create temp dir");
1338 let root = base.path().join("app [1]");
1339 std::fs::create_dir_all(root.join(".config")).expect("create project dirs");
1340 std::fs::write(root.join(".config").join("tool.json"), "{}").expect("write config");
1341
1342 let detection = PluginDetection::FileExists {
1343 pattern: ".config/*.json".to_string(),
1344 };
1345 assert!(check_plugin_detection(&detection, &[], &root, &[]));
1346 }
1347}