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