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}
350
351impl ConfigCandidateIndex {
352 #[must_use]
356 pub(crate) fn build<'a>(paths: impl IntoIterator<Item = &'a Path>) -> Self {
357 let mut dirs: FxHashMap<PathBuf, FxHashSet<OsString>> = FxHashMap::default();
358 for path in paths {
359 if let (Some(parent), Some(name)) = (path.parent(), path.file_name()) {
360 dirs.entry(parent.to_path_buf())
361 .or_default()
362 .insert(name.to_os_string());
363 }
364 }
365 Self { dirs }
366 }
367
368 #[must_use]
370 pub(crate) fn contains_file(&self, path: &Path) -> bool {
371 match (path.parent(), path.file_name()) {
372 (Some(dir), Some(name)) => self.dir_contains(dir, name),
373 _ => false,
374 }
375 }
376
377 #[must_use]
381 pub(crate) fn dir_contains(&self, dir: &Path, name: &OsStr) -> bool {
382 self.dirs.get(dir).is_some_and(|names| names.contains(name))
383 }
384
385 #[must_use]
390 pub(crate) fn any_descendant_contains(&self, root: &Path, name: &OsStr) -> bool {
391 self.dirs
392 .iter()
393 .any(|(dir, names)| dir.starts_with(root) && names.contains(name))
394 }
395
396 #[must_use]
402 pub(crate) fn any_descendant_matches(
403 &self,
404 root: &Path,
405 matcher: &globset::GlobMatcher,
406 ) -> bool {
407 self.dirs.iter().any(|(dir, names)| {
408 dir.starts_with(root) && names.iter().any(|name| matcher.is_match(Path::new(name)))
409 })
410 }
411
412 pub(super) fn names_in_dir(&self, dir: &Path) -> Option<&FxHashSet<OsString>> {
414 self.dirs.get(dir)
415 }
416
417 pub(super) fn glob_matches_in_dir(
418 &self,
419 dir: &Path,
420 matcher: &globset::GlobMatcher,
421 ) -> Vec<PathBuf> {
422 self.dirs.get(dir).map_or_else(Vec::new, |names| {
423 names
424 .iter()
425 .filter(|name| matcher.is_match(Path::new(name)))
426 .map(|name| dir.join(name))
427 .collect()
428 })
429 }
430}
431
432pub fn discover_config_files<'a>(
452 config_matchers: &[(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
453 resolved_plugins: &FxHashSet<&str>,
454 roots: &[&Path],
455 production_mode: bool,
456 candidate_index: Option<&ConfigCandidateIndex>,
457) -> Vec<(PathBuf, &'a dyn Plugin)> {
458 use rayon::prelude::*;
459 let mut pending: Vec<(&'a dyn Plugin, &Path, String, bool)> = Vec::new();
460 for (plugin, _) in config_matchers {
461 let resolved = resolved_plugins.contains(plugin.name());
467 for root in roots {
468 for pat in plugin.config_patterns() {
469 if !production_mode && is_source_ext_root_pattern(pat) {
470 continue;
471 }
472 if resolved
473 && !pattern_needs_filesystem(pat)
474 && pattern_names_only_source_files(pat)
475 {
476 continue;
477 }
478 pending.push((*plugin, *root, pat.to_string(), resolved));
479 }
480 }
481 }
482
483 let hits: Vec<(PathBuf, &'a dyn Plugin)> = pending
484 .par_iter()
485 .flat_map_iter(|(plugin, root, pat, resolved)| {
486 expand_brace_pattern(pat)
487 .into_iter()
488 .flat_map(|expanded| {
489 let needs_fs = pattern_needs_filesystem(&expanded);
490 let paths = match candidate_index {
491 Some(index) if !needs_fs => match_pattern_in_index(root, &expanded, index),
497 _ => discover_pattern_matches(root, &expanded),
498 };
499 paths
500 .into_iter()
501 .filter(move |path| {
502 !*resolved || !phase_3a_read_file(path, needs_fs, candidate_index)
503 })
504 .map(move |path| (path, *plugin))
505 })
506 .collect::<Vec<_>>()
507 })
508 .collect();
509
510 let mut seen: FxHashSet<(PathBuf, &'a str)> = FxHashSet::default();
511 let mut config_files: Vec<(PathBuf, &'a dyn Plugin)> = Vec::with_capacity(hits.len());
512 for (path, plugin) in hits {
513 if seen.insert((path.clone(), plugin.name())) {
514 config_files.push((path, plugin));
515 }
516 }
517 config_files
518}
519
520fn pattern_names_only_source_files(pattern: &str) -> bool {
525 expand_brace_pattern(pattern)
526 .iter()
527 .all(|expanded| has_source_extension(Path::new(expanded)))
528}
529
530fn has_source_extension(path: &Path) -> bool {
531 path.extension()
532 .and_then(|ext| ext.to_str())
533 .is_some_and(|ext| SOURCE_EXTENSIONS.contains(&ext))
534}
535
536fn phase_3a_read_file(
541 path: &Path,
542 needs_fs: bool,
543 candidate_index: Option<&ConfigCandidateIndex>,
544) -> bool {
545 if needs_fs {
546 return candidate_index.is_some_and(|index| index.contains_file(path));
547 }
548 has_source_extension(path)
549}
550
551fn pattern_has_glob(pattern: &str) -> bool {
552 pattern.contains('*') || pattern.contains('?') || pattern.contains('[')
553}
554
555pub(super) fn pattern_needs_filesystem(pattern: &str) -> bool {
562 let mut components = pattern.split('/').peekable();
563 let mut needs_fs = false;
564 while let Some(component) = components.next() {
565 if components.peek().is_none() {
566 break; }
568 if component.starts_with('.')
569 && component != "."
570 && component != ".."
571 && !crate::discover::is_allowed_hidden_dir(OsStr::new(component))
572 {
573 needs_fs = true;
574 break;
575 }
576 if is_default_ignored_directory(component) {
577 needs_fs = true;
578 break;
579 }
580 }
581 needs_fs
582}
583
584fn is_default_ignored_directory(name: &str) -> bool {
587 fallow_config::DEFAULT_IGNORE_PATTERNS
588 .iter()
589 .any(|pattern| {
590 pattern
591 .strip_prefix("**/")
592 .and_then(|rest| rest.strip_suffix("/**"))
593 .is_some_and(|directory| directory == name)
594 })
595}
596
597fn match_pattern_in_index(
602 root: &Path,
603 pattern: &str,
604 index: &ConfigCandidateIndex,
605) -> Vec<PathBuf> {
606 if !pattern_has_glob(pattern) {
607 let path = root.join(pattern);
608 return match (path.parent(), path.file_name()) {
609 (Some(dir), Some(name)) if index.dir_contains(dir, name) => vec![path],
610 _ => Vec::new(),
611 };
612 }
613
614 if let Some(stripped) = pattern.strip_prefix("**/") {
615 return match_pattern_in_index(root, stripped, index);
616 }
617
618 let (dir, file_pattern) = match pattern.rsplit_once('/') {
619 Some((parent, file_pattern)) if !pattern_has_glob(parent) => {
620 (root.join(parent), file_pattern)
621 }
622 Some(_) => return Vec::new(),
623 None => (root.to_path_buf(), pattern),
624 };
625
626 let Ok(matcher) = globset::Glob::new(file_pattern).map(|g| g.compile_matcher()) else {
627 return Vec::new();
628 };
629 index.glob_matches_in_dir(&dir, &matcher)
630}
631
632fn discover_pattern_matches(root: &Path, pattern: &str) -> Vec<PathBuf> {
633 if !pattern_has_glob(pattern) {
634 let path = root.join(pattern);
635 return if path.is_file() {
636 vec![path]
637 } else {
638 Vec::new()
639 };
640 }
641
642 if let Some(stripped) = pattern.strip_prefix("**/") {
643 return discover_pattern_matches(root, stripped);
644 }
645
646 let (dir, file_pattern) = match pattern.rsplit_once('/') {
647 Some((parent, file_pattern)) if !pattern_has_glob(parent) => {
648 (root.join(parent), file_pattern)
649 }
650 Some(_) => return Vec::new(),
651 None => (root.to_path_buf(), pattern),
652 };
653
654 scan_dir_for_pattern(&dir, file_pattern)
655}
656
657fn scan_dir_for_pattern(dir: &Path, file_pattern: &str) -> Vec<PathBuf> {
658 let Ok(matcher) = globset::Glob::new(file_pattern).map(|g| g.compile_matcher()) else {
659 return Vec::new();
660 };
661 let Ok(entries) = std::fs::read_dir(dir) else {
662 return Vec::new();
663 };
664
665 entries
666 .filter_map(Result::ok)
667 .map(|entry| entry.path())
668 .filter(|path| path.is_file())
669 .filter(|path| {
670 path.file_name()
671 .is_some_and(|name| matcher.is_match(std::path::Path::new(name)))
672 })
673 .collect()
674}
675
676pub(super) fn expand_brace_pattern(pattern: &str) -> Vec<String> {
680 let mut expanded = expand_brace_groups(pattern);
681 expanded.retain(|text| {
682 fallow_config::glob_validation::validate_user_path(text, "configPatterns").is_ok()
683 });
684 expanded
685}
686
687fn expand_brace_groups(pattern: &str) -> Vec<String> {
688 let Some(open) = pattern.find('{') else {
689 return vec![pattern.to_string()];
690 };
691 let Some(close_rel) = pattern[open + 1..].find('}') else {
692 return vec![pattern.to_string()];
693 };
694 let close = open + 1 + close_rel;
695
696 let prefix = &pattern[..open];
697 let suffix = &pattern[close + 1..];
698 let inner = &pattern[open + 1..close];
699 let mut expanded = Vec::new();
700 for option in inner.split(',') {
701 for tail in expand_brace_groups(suffix) {
702 expanded.push(format!("{prefix}{option}{tail}"));
703 }
704 }
705 expanded
706}
707
708fn collect_path_rule_regex_errors(
713 rule: &crate::plugins::PathRule,
714 plugin_name: &str,
715 config_path: Option<&Path>,
716 rule_kind: &'static str,
717 errors: &mut Vec<PluginRegexValidationError>,
718) {
719 for pattern in &rule.exclude_regexes {
720 if let Err(source) = regex::Regex::new(pattern) {
721 errors.push(PluginRegexValidationError::new(
722 PluginRegexValidationErrorInput {
723 plugin_name,
724 config_path,
725 rule_kind,
726 field: "exclude_regexes",
727 rule_pattern: &rule.pattern,
728 regex_pattern: pattern,
729 source: &source,
730 },
731 ));
732 }
733 }
734 for pattern in &rule.exclude_segment_regexes {
735 if let Err(source) = regex::Regex::new(pattern) {
736 errors.push(PluginRegexValidationError::new(
737 PluginRegexValidationErrorInput {
738 plugin_name,
739 config_path,
740 rule_kind,
741 field: "exclude_segment_regexes",
742 rule_pattern: &rule.pattern,
743 regex_pattern: pattern,
744 source: &source,
745 },
746 ));
747 }
748 }
749}
750
751pub fn process_config_result(
757 plugin_name: &str,
758 plugin_result: PluginResult,
759 result: &mut AggregatedPluginResult,
760 config_path: Option<&Path>,
761) -> Result<(), Vec<PluginRegexValidationError>> {
762 let mut regex_errors = Vec::new();
763
764 for rule in &plugin_result.entry_patterns {
765 collect_path_rule_regex_errors(
766 rule,
767 plugin_name,
768 config_path,
769 "entry_patterns[]",
770 &mut regex_errors,
771 );
772 }
773 for rule in &plugin_result.used_exports {
774 collect_path_rule_regex_errors(
775 &rule.path,
776 plugin_name,
777 config_path,
778 "used_exports[].path",
779 &mut regex_errors,
780 );
781 }
782 if !regex_errors.is_empty() {
783 return Err(regex_errors);
784 }
785 merge_plugin_result_fields(plugin_name, plugin_result, result);
786 Ok(())
787}
788
789fn merge_entry_patterns(
792 pname: &str,
793 plugin_result: &mut PluginResult,
794 result: &mut AggregatedPluginResult,
795) {
796 if plugin_result.replace_entry_patterns && !plugin_result.entry_patterns.is_empty() {
797 let first_replacement = result.replaced_entry_plugins.insert(pname.to_string());
798 if !plugin_result.accumulate_config_entry_patterns {
799 result.entry_patterns.retain(|(_, name)| name != pname);
800 } else if first_replacement {
801 let config_patterns = &result.config_entry_patterns;
805 result.entry_patterns.retain(|(rule, name)| {
806 name != pname || config_patterns.contains(&(name.clone(), rule.pattern.clone()))
807 });
808 }
809 }
810 if plugin_result.accumulate_config_entry_patterns {
811 result.config_entry_patterns.extend(
812 plugin_result
813 .entry_patterns
814 .iter()
815 .map(|rule| (pname.to_string(), rule.pattern.clone())),
816 );
817 }
818 result.entry_patterns.extend(
819 std::mem::take(&mut plugin_result.entry_patterns)
820 .into_iter()
821 .map(|rule| (rule, pname.to_string())),
822 );
823}
824
825fn merge_path_aliases(
829 path_aliases: Vec<(String, String)>,
830 checked_alias_prefixes: Vec<String>,
831 result: &mut AggregatedPluginResult,
832) {
833 for (prefix, replacement) in path_aliases {
834 result
835 .path_aliases
836 .retain(|(existing_prefix, _)| existing_prefix != &prefix);
837 result
838 .checked_alias_prefixes
839 .retain(|checked| checked.prefix != prefix);
840 result.path_aliases.push((prefix, replacement));
841 }
842 result
843 .checked_alias_prefixes
844 .extend(
845 checked_alias_prefixes
846 .into_iter()
847 .map(|prefix| super::CheckedAliasPrefix {
848 scope: String::new(),
849 prefix,
850 }),
851 );
852}
853
854fn merge_plugin_result_fields(
858 pname: &str,
859 mut plugin_result: PluginResult,
860 result: &mut AggregatedPluginResult,
861) {
862 merge_entry_patterns(pname, &mut plugin_result, result);
863 if plugin_result.replace_used_export_rules && !plugin_result.used_exports.is_empty() {
864 result.used_exports.retain(|rule| rule.plugin_name != pname);
865 }
866 result.used_exports.extend(
867 plugin_result
868 .used_exports
869 .into_iter()
870 .map(|rule| PluginUsedExportRule::new(pname.to_string(), rule)),
871 );
872 result.config_export_credits.extend(
873 plugin_result
874 .entry_export_credits
875 .into_iter()
876 .map(|rule| PluginUsedExportRule::new(pname.to_string(), rule)),
877 );
878 result
879 .used_class_members
880 .extend(plugin_result.used_class_members);
881 result
882 .referenced_dependencies
883 .extend(plugin_result.referenced_dependencies);
884 result
885 .package_referenced_dependencies
886 .extend(plugin_result.package_referenced_dependencies);
887 super::push_missing(
888 &mut result.required_dependencies,
889 plugin_result.required_dependencies,
890 );
891 result.discovered_always_used.extend(
892 plugin_result
893 .always_used_files
894 .into_iter()
895 .map(|p| (p, pname.to_string())),
896 );
897 merge_path_aliases(
898 plugin_result.path_aliases,
899 plugin_result.checked_alias_prefixes,
900 result,
901 );
902 result.setup_files.extend(
903 plugin_result
904 .setup_files
905 .into_iter()
906 .map(|p| (p, pname.to_string())),
907 );
908 result.fixture_patterns.extend(
909 plugin_result
910 .fixture_patterns
911 .into_iter()
912 .map(|p| (p, pname.to_string())),
913 );
914 result
915 .scss_include_paths
916 .extend(plugin_result.scss_include_paths);
917 result
918 .static_dir_mappings
919 .extend(plugin_result.static_dir_mappings);
920 result
921 .framework_static_dir_mappings
922 .extend(plugin_result.framework_static_dir_mappings);
923 result
924 .provided_dependencies
925 .extend(plugin_result.provided_dependencies);
926 result
927 .federation_sources
928 .extend(plugin_result.federation_sources);
929 for rule in plugin_result.jsx_import_sources {
930 if !result.jsx_import_sources.contains(&rule) {
931 result.jsx_import_sources.push(rule);
932 }
933 }
934 for rule in plugin_result.jsx_package_credits {
935 if !result.jsx_package_credits.contains(&rule) {
936 result.jsx_package_credits.push(rule);
937 }
938 }
939 for dir in plugin_result.tsconfig_jsx_dirs {
940 if !result.tsconfig_jsx_dirs.contains(&dir) {
941 result.tsconfig_jsx_dirs.push(dir);
942 }
943 }
944 for diagnostic in plugin_result.config_diagnostics {
945 if !result.config_diagnostics.contains(&diagnostic) {
946 result.config_diagnostics.push(diagnostic);
947 }
948 }
949}
950
951pub fn check_has_config_file(
953 plugin: &dyn Plugin,
954 config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
955 relative_files: &[(PathBuf, String)],
956) -> bool {
957 !plugin.config_patterns().is_empty()
958 && config_matchers.iter().any(|(p, matchers)| {
959 p.name() == plugin.name()
960 && relative_files
961 .iter()
962 .any(|(_, rel)| matchers.iter().any(|m| m.is_match(rel.as_str())))
963 })
964}
965
966pub fn check_plugin_detection(
968 detection: &PluginDetection,
969 all_deps: &[&str],
970 root: &Path,
971 discovered_files: &[PathBuf],
972) -> bool {
973 match detection {
974 PluginDetection::Dependency { package } => all_deps.iter().any(|d| *d == package),
975 PluginDetection::FileExists { pattern } => {
976 if let Ok(matcher) =
977 fallow_config::compile_path_glob(pattern).map(|g| g.compile_matcher())
978 {
979 for file in discovered_files {
980 let relative = file.strip_prefix(root).unwrap_or(file);
981 if matcher.is_match(relative) {
982 return true;
983 }
984 }
985 }
986 fallow_config::glob_validation::expand_disk_glob(root, pattern)
987 .is_some_and(|mut paths| paths.next().is_some())
988 }
989 PluginDetection::All { conditions } => conditions
990 .iter()
991 .all(|c| check_plugin_detection(c, all_deps, root, discovered_files)),
992 PluginDetection::Any { conditions } => conditions
993 .iter()
994 .any(|c| check_plugin_detection(c, all_deps, root, discovered_files)),
995 }
996}
997
998#[cfg(test)]
999mod tests {
1000 use super::*;
1001
1002 #[test]
1003 fn brace_expansions_that_leave_the_root_are_dropped() {
1004 assert_eq!(expand_brace_pattern("{..,x}/a.json"), vec!["x/a.json"]);
1005 assert_eq!(expand_brace_pattern("{/abs/name,b}"), vec!["b"]);
1006 assert!(expand_brace_pattern("../a.json").is_empty());
1007 assert_eq!(
1008 expand_brace_pattern("{vite,vitest}.config.ts"),
1009 vec!["vite.config.ts", "vitest.config.ts"]
1010 );
1011 }
1012
1013 #[test]
1014 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1015 fn config_file_probes_stay_inside_the_root() {
1016 let dir = tempfile::tempdir().unwrap();
1017 let root = dir.path().join("project");
1018 std::fs::create_dir(&root).unwrap();
1019 std::fs::write(dir.path().join("outside.json"), "{}").unwrap();
1020 let hits: Vec<PathBuf> = expand_brace_pattern("{..,x}/outside.json")
1021 .iter()
1022 .flat_map(|pattern| discover_pattern_matches(&root, pattern))
1023 .collect();
1024 assert!(hits.is_empty(), "{hits:?}");
1025 }
1026
1027 #[test]
1028 fn pattern_needs_filesystem_only_for_non_allowlisted_hidden_dirs() {
1029 assert!(pattern_needs_filesystem(".config/prisma.ts"));
1032 assert!(!pattern_needs_filesystem("tsconfig.json"));
1035 assert!(!pattern_needs_filesystem("prisma/schema.prisma"));
1036 assert!(!pattern_needs_filesystem(".eslintrc.json"));
1037 assert!(!pattern_needs_filesystem("**/project.json"));
1038 assert!(!pattern_needs_filesystem(".storybook/main.ts"));
1039 assert!(!pattern_needs_filesystem("a/b/c.json"));
1040 assert!(pattern_needs_filesystem("build/webpack.prod.js"));
1042 assert!(!pattern_needs_filesystem("config/webpack.prod.js"));
1043 }
1044
1045 #[test]
1046 fn config_candidate_index_matches_plain_nested_and_glob_shapes() {
1047 let root = Path::new("/project");
1048 let index = ConfigCandidateIndex::build([
1049 Path::new("/project/tsconfig.json"),
1050 Path::new("/project/packages/a/tsconfig.json"),
1051 Path::new("/project/prisma/schema.prisma"),
1052 Path::new("/project/src/main.ts"),
1053 ]);
1054
1055 assert_eq!(
1057 match_pattern_in_index(root, "tsconfig.json", &index),
1058 vec![PathBuf::from("/project/tsconfig.json")]
1059 );
1060 assert_eq!(
1061 match_pattern_in_index(Path::new("/project/packages/a"), "tsconfig.json", &index),
1062 vec![PathBuf::from("/project/packages/a/tsconfig.json")]
1063 );
1064 assert_eq!(
1066 match_pattern_in_index(root, "prisma/schema.prisma", &index),
1067 vec![PathBuf::from("/project/prisma/schema.prisma")]
1068 );
1069 assert_eq!(
1070 match_pattern_in_index(root, "**/tsconfig.json", &index),
1071 vec![PathBuf::from("/project/tsconfig.json")]
1072 );
1073 assert_eq!(
1074 match_pattern_in_index(Path::new("/project/prisma"), "*.prisma", &index),
1075 vec![PathBuf::from("/project/prisma/schema.prisma")]
1076 );
1077 assert!(match_pattern_in_index(root, "missing.json", &index).is_empty());
1079 }
1080
1081 #[test]
1082 fn file_exists_detection_never_matches_outside_root() {
1083 let base = tempfile::tempdir().expect("create temp dir");
1084 let root = base.path().join("project");
1085 std::fs::create_dir_all(root.join(".config")).expect("create project dirs");
1086 std::fs::write(base.path().join("outside-marker.json"), "{}").expect("write marker");
1087
1088 for pattern in [".*/outside-marker.json", "..*/outside-marker.json"] {
1091 let detection = PluginDetection::FileExists {
1092 pattern: pattern.to_string(),
1093 };
1094 assert!(
1095 !check_plugin_detection(&detection, &[], &root, &[]),
1096 "{pattern} matched a file outside the project root"
1097 );
1098 }
1099
1100 std::fs::write(root.join(".config").join("outside-marker.json"), "{}")
1101 .expect("write marker inside root");
1102 let detection = PluginDetection::FileExists {
1103 pattern: ".*/outside-marker.json".to_string(),
1104 };
1105 assert!(check_plugin_detection(&detection, &[], &root, &[]));
1106 }
1107
1108 #[test]
1109 fn file_exists_detection_works_under_a_root_with_glob_characters() {
1110 let base = tempfile::tempdir().expect("create temp dir");
1111 let root = base.path().join("app [1]");
1112 std::fs::create_dir_all(root.join(".config")).expect("create project dirs");
1113 std::fs::write(root.join(".config").join("tool.json"), "{}").expect("write config");
1114
1115 let detection = PluginDetection::FileExists {
1116 pattern: ".config/*.json".to_string(),
1117 };
1118 assert!(check_plugin_detection(&detection, &[], &root, &[]));
1119 }
1120}