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::{AggregatedPluginResult, PluginRegexValidationError, PluginRegexValidationErrorInput};
18
19#[must_use]
28pub fn is_source_ext_root_pattern(pat: &str) -> bool {
29 if pat.is_empty() || pat.contains('/') {
30 return false;
31 }
32 for expanded in expand_brace_pattern(pat) {
33 if expanded.starts_with('.') {
34 return false;
35 }
36 let Some(ext) = std::path::Path::new(&expanded).extension() else {
37 return false;
38 };
39 let Some(ext_str) = ext.to_str() else {
40 return false;
41 };
42 if !SOURCE_EXTENSIONS.contains(&ext_str) {
43 return false;
44 }
45 }
46 true
47}
48
49#[must_use]
51pub fn prepare_config_pattern(pat: &str) -> Cow<'_, str> {
52 if is_source_ext_root_pattern(pat) {
53 Cow::Owned(format!("**/{pat}"))
54 } else {
55 Cow::Borrowed(pat)
56 }
57}
58
59fn push_config_default_exports<'a>(
66 pname: &str,
67 patterns: impl Iterator<Item = &'a str>,
68 result: &mut AggregatedPluginResult,
69) {
70 for pat in patterns {
71 result.config_export_credits.push(PluginUsedExportRule::new(
72 pname,
73 UsedExportRule::new(prepare_config_pattern(pat), ["default"]),
74 ));
75 }
76}
77
78pub fn process_static_patterns(
80 plugin: &dyn Plugin,
81 root: &Path,
82 result: &mut AggregatedPluginResult,
83) {
84 let pname = plugin.name().to_string();
85 result.active_plugins.push(pname.clone());
86 result
87 .entry_point_roles
88 .insert(pname.clone(), plugin.entry_point_role());
89
90 collect_static_plugin_rules(plugin, &pname, result);
91 collect_static_plugin_metadata(plugin, root, result);
92}
93
94fn collect_static_plugin_rules(
97 plugin: &dyn Plugin,
98 pname: &str,
99 result: &mut AggregatedPluginResult,
100) {
101 for rule in plugin.entry_pattern_rules() {
102 result.entry_patterns.push((rule, pname.to_string()));
103 }
104 for pat in plugin.config_patterns() {
105 result.config_patterns.push((*pat).to_string());
106 }
107 let opt_out = plugin.config_default_export_opt_out();
108 push_config_default_exports(
109 pname,
110 plugin
111 .config_patterns()
112 .iter()
113 .copied()
114 .filter(|pat| !opt_out.contains(pat)),
115 result,
116 );
117 for (pat, exports) in plugin.config_file_exports() {
118 result.config_export_credits.push(PluginUsedExportRule::new(
119 pname,
120 UsedExportRule::from_static(pat, exports),
121 ));
122 }
123 for pat in plugin.always_used() {
124 result
125 .always_used
126 .push(((*pat).to_string(), pname.to_string()));
127 }
128 for rule in plugin.used_export_rules() {
129 result
130 .used_exports
131 .push(PluginUsedExportRule::new(pname.to_string(), rule));
132 }
133 for member in plugin.used_class_members() {
134 result
135 .used_class_members
136 .push(UsedClassMemberRule::from(*member));
137 }
138 for rule in plugin.used_class_member_rules() {
139 result.used_class_members.push(rule);
140 }
141 result
142 .framework_class_member_contracts
143 .extend(plugin.framework_class_member_contracts());
144 for pat in plugin.fixture_glob_patterns() {
145 result
146 .fixture_patterns
147 .push(((*pat).to_string(), pname.to_string()));
148 }
149}
150
151fn collect_static_plugin_metadata(
154 plugin: &dyn Plugin,
155 root: &Path,
156 result: &mut AggregatedPluginResult,
157) {
158 for dep in plugin.tooling_dependencies() {
159 result.tooling_dependencies.push((*dep).to_string());
160 }
161 for prefix in plugin.virtual_module_prefixes() {
162 result.virtual_module_prefixes.push((*prefix).to_string());
163 }
164 for suffix in plugin.virtual_package_suffixes() {
165 result.virtual_package_suffixes.push((*suffix).to_string());
166 }
167 for pattern in plugin.generated_import_patterns() {
168 result
169 .generated_import_patterns
170 .push((*pattern).to_string());
171 }
172 for prefix in plugin.generated_type_import_prefixes() {
173 result
174 .generated_type_import_prefixes
175 .push((*prefix).to_string());
176 }
177 for (prefix, replacement) in plugin.path_aliases(root) {
178 result.path_aliases.push((prefix.to_string(), replacement));
179 }
180 result
181 .framework_static_dir_mappings
182 .extend(plugin.static_dir_mappings(root));
183 result
184 .auto_imports
185 .extend(plugin.auto_imports(root).into_iter().map(|mut rule| {
186 if rule.scope.is_empty() {
187 rule.scope.push(root.to_path_buf());
188 }
189 rule
190 }));
191 result
192 .provided_dependencies
193 .extend(plugin.provided_dependencies());
194}
195
196pub fn process_package_json_metadata(
198 active: &[&dyn Plugin],
199 pkg: &PackageJson,
200 root: &Path,
201 result: &mut AggregatedPluginResult,
202 regex_errors: &mut Vec<PluginRegexValidationError>,
203) {
204 for plugin in active {
205 let package_referenced = plugin.package_json_referenced_dependencies(pkg, root);
206 if !package_referenced.is_empty() {
207 let pkg_path = root.join("package.json");
208 result.package_referenced_dependencies.extend(
209 package_referenced
210 .into_iter()
211 .map(|dep| (pkg_path.clone(), dep)),
212 );
213 }
214 let plugin_result = plugin.resolve_package_json(pkg, root);
215 if plugin_result.is_empty() {
216 continue;
217 }
218 tracing::debug!(
219 plugin = plugin.name(),
220 deps = plugin_result.referenced_dependencies.len(),
221 "resolved package.json metadata"
222 );
223 if let Err(mut errors) = process_config_result(plugin.name(), plugin_result, result, None) {
224 regex_errors.append(&mut errors);
225 }
226 }
227}
228
229pub fn is_external_plugin_active(
234 ext: &ExternalPluginDef,
235 all_deps: &[String],
236 root: &Path,
237 discovered_files: &[PathBuf],
238) -> bool {
239 if !ext.has_activation_condition() {
240 return false;
241 }
242 if let Some(detection) = &ext.detection {
243 let all_dep_refs: Vec<&str> = all_deps.iter().map(String::as_str).collect();
244 return check_plugin_detection(detection, &all_dep_refs, root, discovered_files);
245 }
246 ext.enablers.iter().any(|enabler| {
247 if enabler.ends_with('/') {
248 all_deps.iter().any(|d| d.starts_with(enabler))
249 } else {
250 all_deps.iter().any(|d| d == enabler)
251 }
252 })
253}
254
255pub fn process_external_plugins(
257 external_plugins: &[ExternalPluginDef],
258 all_deps: &[String],
259 root: &Path,
260 discovered_files: &[PathBuf],
261 result: &mut AggregatedPluginResult,
262) {
263 for ext in external_plugins {
264 let is_active = is_external_plugin_active(ext, all_deps, root, discovered_files);
265 if is_active {
266 result.active_plugins.push(ext.name.clone());
267 result
268 .entry_point_roles
269 .insert(ext.name.clone(), ext.effective_entry_point_role());
270 result.entry_patterns.extend(
271 ext.entry_points
272 .iter()
273 .map(|p| (PathRule::new(p.clone()), ext.name.clone())),
274 );
275 if !ext.manifest_entries.is_empty() {
276 result.entry_patterns.extend(
277 crate::plugins::manifest_entries::evaluate_manifest_entries(ext, root)
278 .into_iter()
279 .map(|rule| (rule, ext.name.clone())),
280 );
281 }
282 result.config_patterns.extend(ext.config_patterns.clone());
283 push_config_default_exports(
284 &ext.name,
285 ext.config_patterns
286 .iter()
287 .filter(|pat| !ext.config_default_export_opt_out.contains(pat))
288 .map(String::as_str),
289 result,
290 );
291 result.always_used.extend(
292 ext.config_patterns
293 .iter()
294 .chain(ext.always_used.iter())
295 .map(|p| (p.clone(), ext.name.clone())),
296 );
297 result
298 .tooling_dependencies
299 .extend(ext.tooling_dependencies.clone());
300 for ue in &ext.used_exports {
301 result.used_exports.push(PluginUsedExportRule::new(
302 ext.name.clone(),
303 UsedExportRule::new(ue.pattern.clone(), ue.exports.clone()),
304 ));
305 }
306 result
307 .used_class_members
308 .extend(ext.used_class_members.iter().cloned());
309 }
310 }
311}
312
313pub struct ConfigCandidateIndex {
325 dirs: FxHashMap<PathBuf, FxHashSet<OsString>>,
326}
327
328impl ConfigCandidateIndex {
329 #[must_use]
333 pub(crate) fn build<'a>(paths: impl IntoIterator<Item = &'a Path>) -> Self {
334 let mut dirs: FxHashMap<PathBuf, FxHashSet<OsString>> = FxHashMap::default();
335 for path in paths {
336 if let (Some(parent), Some(name)) = (path.parent(), path.file_name()) {
337 dirs.entry(parent.to_path_buf())
338 .or_default()
339 .insert(name.to_os_string());
340 }
341 }
342 Self { dirs }
343 }
344
345 #[must_use]
347 pub(crate) fn contains_file(&self, path: &Path) -> bool {
348 match (path.parent(), path.file_name()) {
349 (Some(dir), Some(name)) => self.dir_contains(dir, name),
350 _ => false,
351 }
352 }
353
354 #[must_use]
358 pub(crate) fn dir_contains(&self, dir: &Path, name: &OsStr) -> bool {
359 self.dirs.get(dir).is_some_and(|names| names.contains(name))
360 }
361
362 #[must_use]
367 pub(crate) fn any_descendant_contains(&self, root: &Path, name: &OsStr) -> bool {
368 self.dirs
369 .iter()
370 .any(|(dir, names)| dir.starts_with(root) && names.contains(name))
371 }
372
373 #[must_use]
379 pub(crate) fn any_descendant_matches(
380 &self,
381 root: &Path,
382 matcher: &globset::GlobMatcher,
383 ) -> bool {
384 self.dirs.iter().any(|(dir, names)| {
385 dir.starts_with(root) && names.iter().any(|name| matcher.is_match(Path::new(name)))
386 })
387 }
388
389 pub(super) fn names_in_dir(&self, dir: &Path) -> Option<&FxHashSet<OsString>> {
391 self.dirs.get(dir)
392 }
393
394 pub(super) fn glob_matches_in_dir(
395 &self,
396 dir: &Path,
397 matcher: &globset::GlobMatcher,
398 ) -> Vec<PathBuf> {
399 self.dirs.get(dir).map_or_else(Vec::new, |names| {
400 names
401 .iter()
402 .filter(|name| matcher.is_match(Path::new(name)))
403 .map(|name| dir.join(name))
404 .collect()
405 })
406 }
407}
408
409pub fn discover_config_files<'a>(
429 config_matchers: &[(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
430 resolved_plugins: &FxHashSet<&str>,
431 roots: &[&Path],
432 production_mode: bool,
433 candidate_index: Option<&ConfigCandidateIndex>,
434) -> Vec<(PathBuf, &'a dyn Plugin)> {
435 use rayon::prelude::*;
436 let mut pending: Vec<(&'a dyn Plugin, &Path, String, bool)> = Vec::new();
437 for (plugin, _) in config_matchers {
438 let resolved = resolved_plugins.contains(plugin.name());
444 for root in roots {
445 for pat in plugin.config_patterns() {
446 if !production_mode && is_source_ext_root_pattern(pat) {
447 continue;
448 }
449 if resolved
450 && !pattern_needs_filesystem(pat)
451 && pattern_names_only_source_files(pat)
452 {
453 continue;
454 }
455 pending.push((*plugin, *root, pat.to_string(), resolved));
456 }
457 }
458 }
459
460 let hits: Vec<(PathBuf, &'a dyn Plugin)> = pending
461 .par_iter()
462 .flat_map_iter(|(plugin, root, pat, resolved)| {
463 expand_brace_pattern(pat)
464 .into_iter()
465 .flat_map(|expanded| {
466 let needs_fs = pattern_needs_filesystem(&expanded);
467 let paths = match candidate_index {
468 Some(index) if !needs_fs => match_pattern_in_index(root, &expanded, index),
474 _ => discover_pattern_matches(root, &expanded),
475 };
476 paths
477 .into_iter()
478 .filter(move |path| {
479 !*resolved || !phase_3a_read_file(path, needs_fs, candidate_index)
480 })
481 .map(move |path| (path, *plugin))
482 })
483 .collect::<Vec<_>>()
484 })
485 .collect();
486
487 let mut seen: FxHashSet<(PathBuf, &'a str)> = FxHashSet::default();
488 let mut config_files: Vec<(PathBuf, &'a dyn Plugin)> = Vec::with_capacity(hits.len());
489 for (path, plugin) in hits {
490 if seen.insert((path.clone(), plugin.name())) {
491 config_files.push((path, plugin));
492 }
493 }
494 config_files
495}
496
497fn pattern_names_only_source_files(pattern: &str) -> bool {
502 expand_brace_pattern(pattern)
503 .iter()
504 .all(|expanded| has_source_extension(Path::new(expanded)))
505}
506
507fn has_source_extension(path: &Path) -> bool {
508 path.extension()
509 .and_then(|ext| ext.to_str())
510 .is_some_and(|ext| SOURCE_EXTENSIONS.contains(&ext))
511}
512
513fn phase_3a_read_file(
518 path: &Path,
519 needs_fs: bool,
520 candidate_index: Option<&ConfigCandidateIndex>,
521) -> bool {
522 if needs_fs {
523 return candidate_index.is_some_and(|index| index.contains_file(path));
524 }
525 has_source_extension(path)
526}
527
528fn pattern_has_glob(pattern: &str) -> bool {
529 pattern.contains('*') || pattern.contains('?') || pattern.contains('[')
530}
531
532pub(super) fn pattern_needs_filesystem(pattern: &str) -> bool {
539 let mut components = pattern.split('/').peekable();
540 let mut needs_fs = false;
541 while let Some(component) = components.next() {
542 if components.peek().is_none() {
543 break; }
545 if component.starts_with('.')
546 && component != "."
547 && component != ".."
548 && !crate::discover::is_allowed_hidden_dir(OsStr::new(component))
549 {
550 needs_fs = true;
551 break;
552 }
553 if is_default_ignored_directory(component) {
554 needs_fs = true;
555 break;
556 }
557 }
558 needs_fs
559}
560
561fn is_default_ignored_directory(name: &str) -> bool {
564 fallow_config::DEFAULT_IGNORE_PATTERNS
565 .iter()
566 .any(|pattern| {
567 pattern
568 .strip_prefix("**/")
569 .and_then(|rest| rest.strip_suffix("/**"))
570 .is_some_and(|directory| directory == name)
571 })
572}
573
574fn match_pattern_in_index(
579 root: &Path,
580 pattern: &str,
581 index: &ConfigCandidateIndex,
582) -> Vec<PathBuf> {
583 if !pattern_has_glob(pattern) {
584 let path = root.join(pattern);
585 return match (path.parent(), path.file_name()) {
586 (Some(dir), Some(name)) if index.dir_contains(dir, name) => vec![path],
587 _ => Vec::new(),
588 };
589 }
590
591 if let Some(stripped) = pattern.strip_prefix("**/") {
592 return match_pattern_in_index(root, stripped, index);
593 }
594
595 let (dir, file_pattern) = match pattern.rsplit_once('/') {
596 Some((parent, file_pattern)) if !pattern_has_glob(parent) => {
597 (root.join(parent), file_pattern)
598 }
599 Some(_) => return Vec::new(),
600 None => (root.to_path_buf(), pattern),
601 };
602
603 let Ok(matcher) = globset::Glob::new(file_pattern).map(|g| g.compile_matcher()) else {
604 return Vec::new();
605 };
606 index.glob_matches_in_dir(&dir, &matcher)
607}
608
609fn discover_pattern_matches(root: &Path, pattern: &str) -> Vec<PathBuf> {
610 if !pattern_has_glob(pattern) {
611 let path = root.join(pattern);
612 return if path.is_file() {
613 vec![path]
614 } else {
615 Vec::new()
616 };
617 }
618
619 if let Some(stripped) = pattern.strip_prefix("**/") {
620 return discover_pattern_matches(root, stripped);
621 }
622
623 let (dir, file_pattern) = match pattern.rsplit_once('/') {
624 Some((parent, file_pattern)) if !pattern_has_glob(parent) => {
625 (root.join(parent), file_pattern)
626 }
627 Some(_) => return Vec::new(),
628 None => (root.to_path_buf(), pattern),
629 };
630
631 scan_dir_for_pattern(&dir, file_pattern)
632}
633
634fn scan_dir_for_pattern(dir: &Path, file_pattern: &str) -> Vec<PathBuf> {
635 let Ok(matcher) = globset::Glob::new(file_pattern).map(|g| g.compile_matcher()) else {
636 return Vec::new();
637 };
638 let Ok(entries) = std::fs::read_dir(dir) else {
639 return Vec::new();
640 };
641
642 entries
643 .filter_map(Result::ok)
644 .map(|entry| entry.path())
645 .filter(|path| path.is_file())
646 .filter(|path| {
647 path.file_name()
648 .is_some_and(|name| matcher.is_match(std::path::Path::new(name)))
649 })
650 .collect()
651}
652
653pub(super) fn expand_brace_pattern(pattern: &str) -> Vec<String> {
654 let Some(open) = pattern.find('{') else {
655 return vec![pattern.to_string()];
656 };
657 let Some(close_rel) = pattern[open + 1..].find('}') else {
658 return vec![pattern.to_string()];
659 };
660 let close = open + 1 + close_rel;
661
662 let prefix = &pattern[..open];
663 let suffix = &pattern[close + 1..];
664 let inner = &pattern[open + 1..close];
665 let mut expanded = Vec::new();
666 for option in inner.split(',') {
667 for tail in expand_brace_pattern(suffix) {
668 expanded.push(format!("{prefix}{option}{tail}"));
669 }
670 }
671 expanded
672}
673
674fn collect_path_rule_regex_errors(
679 rule: &crate::plugins::PathRule,
680 plugin_name: &str,
681 config_path: Option<&Path>,
682 rule_kind: &'static str,
683 errors: &mut Vec<PluginRegexValidationError>,
684) {
685 for pattern in &rule.exclude_regexes {
686 if let Err(source) = regex::Regex::new(pattern) {
687 errors.push(PluginRegexValidationError::new(
688 PluginRegexValidationErrorInput {
689 plugin_name,
690 config_path,
691 rule_kind,
692 field: "exclude_regexes",
693 rule_pattern: &rule.pattern,
694 regex_pattern: pattern,
695 source: &source,
696 },
697 ));
698 }
699 }
700 for pattern in &rule.exclude_segment_regexes {
701 if let Err(source) = regex::Regex::new(pattern) {
702 errors.push(PluginRegexValidationError::new(
703 PluginRegexValidationErrorInput {
704 plugin_name,
705 config_path,
706 rule_kind,
707 field: "exclude_segment_regexes",
708 rule_pattern: &rule.pattern,
709 regex_pattern: pattern,
710 source: &source,
711 },
712 ));
713 }
714 }
715}
716
717pub fn process_config_result(
723 plugin_name: &str,
724 plugin_result: PluginResult,
725 result: &mut AggregatedPluginResult,
726 config_path: Option<&Path>,
727) -> Result<(), Vec<PluginRegexValidationError>> {
728 let mut regex_errors = Vec::new();
729
730 for rule in &plugin_result.entry_patterns {
731 collect_path_rule_regex_errors(
732 rule,
733 plugin_name,
734 config_path,
735 "entry_patterns[]",
736 &mut regex_errors,
737 );
738 }
739 for rule in &plugin_result.used_exports {
740 collect_path_rule_regex_errors(
741 &rule.path,
742 plugin_name,
743 config_path,
744 "used_exports[].path",
745 &mut regex_errors,
746 );
747 }
748 if !regex_errors.is_empty() {
749 return Err(regex_errors);
750 }
751 merge_plugin_result_fields(plugin_name, plugin_result, result);
752 Ok(())
753}
754
755fn merge_entry_patterns(
758 pname: &str,
759 plugin_result: &mut PluginResult,
760 result: &mut AggregatedPluginResult,
761) {
762 if plugin_result.replace_entry_patterns && !plugin_result.entry_patterns.is_empty() {
763 let first_replacement = result.replaced_entry_plugins.insert(pname.to_string());
764 if !plugin_result.accumulate_config_entry_patterns {
765 result.entry_patterns.retain(|(_, name)| name != pname);
766 } else if first_replacement {
767 let config_patterns = &result.config_entry_patterns;
771 result.entry_patterns.retain(|(rule, name)| {
772 name != pname || config_patterns.contains(&(name.clone(), rule.pattern.clone()))
773 });
774 }
775 }
776 if plugin_result.accumulate_config_entry_patterns {
777 result.config_entry_patterns.extend(
778 plugin_result
779 .entry_patterns
780 .iter()
781 .map(|rule| (pname.to_string(), rule.pattern.clone())),
782 );
783 }
784 result.entry_patterns.extend(
785 std::mem::take(&mut plugin_result.entry_patterns)
786 .into_iter()
787 .map(|rule| (rule, pname.to_string())),
788 );
789}
790
791fn merge_path_aliases(
795 path_aliases: Vec<(String, String)>,
796 checked_alias_prefixes: Vec<String>,
797 result: &mut AggregatedPluginResult,
798) {
799 for (prefix, replacement) in path_aliases {
800 result
801 .path_aliases
802 .retain(|(existing_prefix, _)| existing_prefix != &prefix);
803 result
804 .checked_alias_prefixes
805 .retain(|checked| checked.prefix != prefix);
806 result.path_aliases.push((prefix, replacement));
807 }
808 result
809 .checked_alias_prefixes
810 .extend(
811 checked_alias_prefixes
812 .into_iter()
813 .map(|prefix| super::CheckedAliasPrefix {
814 scope: String::new(),
815 prefix,
816 }),
817 );
818}
819
820fn merge_plugin_result_fields(
824 pname: &str,
825 mut plugin_result: PluginResult,
826 result: &mut AggregatedPluginResult,
827) {
828 merge_entry_patterns(pname, &mut plugin_result, result);
829 if plugin_result.replace_used_export_rules && !plugin_result.used_exports.is_empty() {
830 result.used_exports.retain(|rule| rule.plugin_name != pname);
831 }
832 result.used_exports.extend(
833 plugin_result
834 .used_exports
835 .into_iter()
836 .map(|rule| PluginUsedExportRule::new(pname.to_string(), rule)),
837 );
838 result.config_export_credits.extend(
839 plugin_result
840 .entry_export_credits
841 .into_iter()
842 .map(|rule| PluginUsedExportRule::new(pname.to_string(), rule)),
843 );
844 result
845 .used_class_members
846 .extend(plugin_result.used_class_members);
847 result
848 .referenced_dependencies
849 .extend(plugin_result.referenced_dependencies);
850 result
851 .package_referenced_dependencies
852 .extend(plugin_result.package_referenced_dependencies);
853 super::push_missing(
854 &mut result.required_dependencies,
855 plugin_result.required_dependencies,
856 );
857 result.discovered_always_used.extend(
858 plugin_result
859 .always_used_files
860 .into_iter()
861 .map(|p| (p, pname.to_string())),
862 );
863 merge_path_aliases(
864 plugin_result.path_aliases,
865 plugin_result.checked_alias_prefixes,
866 result,
867 );
868 result.setup_files.extend(
869 plugin_result
870 .setup_files
871 .into_iter()
872 .map(|p| (p, pname.to_string())),
873 );
874 result.fixture_patterns.extend(
875 plugin_result
876 .fixture_patterns
877 .into_iter()
878 .map(|p| (p, pname.to_string())),
879 );
880 result
881 .scss_include_paths
882 .extend(plugin_result.scss_include_paths);
883 result
884 .static_dir_mappings
885 .extend(plugin_result.static_dir_mappings);
886 result
887 .framework_static_dir_mappings
888 .extend(plugin_result.framework_static_dir_mappings);
889 result
890 .provided_dependencies
891 .extend(plugin_result.provided_dependencies);
892 result
893 .federation_sources
894 .extend(plugin_result.federation_sources);
895 for rule in plugin_result.jsx_import_sources {
896 if !result.jsx_import_sources.contains(&rule) {
897 result.jsx_import_sources.push(rule);
898 }
899 }
900 for rule in plugin_result.jsx_package_credits {
901 if !result.jsx_package_credits.contains(&rule) {
902 result.jsx_package_credits.push(rule);
903 }
904 }
905 for dir in plugin_result.tsconfig_jsx_dirs {
906 if !result.tsconfig_jsx_dirs.contains(&dir) {
907 result.tsconfig_jsx_dirs.push(dir);
908 }
909 }
910 for diagnostic in plugin_result.config_diagnostics {
911 if !result.config_diagnostics.contains(&diagnostic) {
912 result.config_diagnostics.push(diagnostic);
913 }
914 }
915}
916
917pub fn check_has_config_file(
919 plugin: &dyn Plugin,
920 config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
921 relative_files: &[(PathBuf, String)],
922) -> bool {
923 !plugin.config_patterns().is_empty()
924 && config_matchers.iter().any(|(p, matchers)| {
925 p.name() == plugin.name()
926 && relative_files
927 .iter()
928 .any(|(_, rel)| matchers.iter().any(|m| m.is_match(rel.as_str())))
929 })
930}
931
932pub fn check_plugin_detection(
934 detection: &PluginDetection,
935 all_deps: &[&str],
936 root: &Path,
937 discovered_files: &[PathBuf],
938) -> bool {
939 match detection {
940 PluginDetection::Dependency { package } => all_deps.iter().any(|d| *d == package),
941 PluginDetection::FileExists { pattern } => {
942 if let Ok(matcher) =
943 fallow_config::compile_path_glob(pattern).map(|g| g.compile_matcher())
944 {
945 for file in discovered_files {
946 let relative = file.strip_prefix(root).unwrap_or(file);
947 if matcher.is_match(relative) {
948 return true;
949 }
950 }
951 }
952 fallow_config::glob_validation::expand_disk_glob(root, pattern)
953 .is_some_and(|mut paths| paths.next().is_some())
954 }
955 PluginDetection::All { conditions } => conditions
956 .iter()
957 .all(|c| check_plugin_detection(c, all_deps, root, discovered_files)),
958 PluginDetection::Any { conditions } => conditions
959 .iter()
960 .any(|c| check_plugin_detection(c, all_deps, root, discovered_files)),
961 }
962}
963
964#[cfg(test)]
965mod tests {
966 use super::*;
967
968 #[test]
969 fn pattern_needs_filesystem_only_for_non_allowlisted_hidden_dirs() {
970 assert!(pattern_needs_filesystem(".config/prisma.ts"));
973 assert!(!pattern_needs_filesystem("tsconfig.json"));
976 assert!(!pattern_needs_filesystem("prisma/schema.prisma"));
977 assert!(!pattern_needs_filesystem(".eslintrc.json"));
978 assert!(!pattern_needs_filesystem("**/project.json"));
979 assert!(!pattern_needs_filesystem(".storybook/main.ts"));
980 assert!(!pattern_needs_filesystem("a/b/c.json"));
981 assert!(pattern_needs_filesystem("build/webpack.prod.js"));
983 assert!(!pattern_needs_filesystem("config/webpack.prod.js"));
984 }
985
986 #[test]
987 fn config_candidate_index_matches_plain_nested_and_glob_shapes() {
988 let root = Path::new("/project");
989 let index = ConfigCandidateIndex::build([
990 Path::new("/project/tsconfig.json"),
991 Path::new("/project/packages/a/tsconfig.json"),
992 Path::new("/project/prisma/schema.prisma"),
993 Path::new("/project/src/main.ts"),
994 ]);
995
996 assert_eq!(
998 match_pattern_in_index(root, "tsconfig.json", &index),
999 vec![PathBuf::from("/project/tsconfig.json")]
1000 );
1001 assert_eq!(
1002 match_pattern_in_index(Path::new("/project/packages/a"), "tsconfig.json", &index),
1003 vec![PathBuf::from("/project/packages/a/tsconfig.json")]
1004 );
1005 assert_eq!(
1007 match_pattern_in_index(root, "prisma/schema.prisma", &index),
1008 vec![PathBuf::from("/project/prisma/schema.prisma")]
1009 );
1010 assert_eq!(
1011 match_pattern_in_index(root, "**/tsconfig.json", &index),
1012 vec![PathBuf::from("/project/tsconfig.json")]
1013 );
1014 assert_eq!(
1015 match_pattern_in_index(Path::new("/project/prisma"), "*.prisma", &index),
1016 vec![PathBuf::from("/project/prisma/schema.prisma")]
1017 );
1018 assert!(match_pattern_in_index(root, "missing.json", &index).is_empty());
1020 }
1021
1022 #[test]
1023 fn file_exists_detection_never_matches_outside_root() {
1024 let base = tempfile::tempdir().expect("create temp dir");
1025 let root = base.path().join("project");
1026 std::fs::create_dir_all(root.join(".config")).expect("create project dirs");
1027 std::fs::write(base.path().join("outside-marker.json"), "{}").expect("write marker");
1028
1029 for pattern in [".*/outside-marker.json", "..*/outside-marker.json"] {
1032 let detection = PluginDetection::FileExists {
1033 pattern: pattern.to_string(),
1034 };
1035 assert!(
1036 !check_plugin_detection(&detection, &[], &root, &[]),
1037 "{pattern} matched a file outside the project root"
1038 );
1039 }
1040
1041 std::fs::write(root.join(".config").join("outside-marker.json"), "{}")
1042 .expect("write marker inside root");
1043 let detection = PluginDetection::FileExists {
1044 pattern: ".*/outside-marker.json".to_string(),
1045 };
1046 assert!(check_plugin_detection(&detection, &[], &root, &[]));
1047 }
1048
1049 #[test]
1050 fn file_exists_detection_works_under_a_root_with_glob_characters() {
1051 let base = tempfile::tempdir().expect("create temp dir");
1052 let root = base.path().join("app [1]");
1053 std::fs::create_dir_all(root.join(".config")).expect("create project dirs");
1054 std::fs::write(root.join(".config").join("tool.json"), "{}").expect("write config");
1055
1056 let detection = PluginDetection::FileExists {
1057 pattern: ".config/*.json".to_string(),
1058 };
1059 assert!(check_plugin_detection(&detection, &[], &root, &[]));
1060 }
1061}