Skip to main content

fallow_core/plugins/registry/
helpers.rs

1//! Helper functions for plugin registry orchestration.
2//!
3//! Contains pattern aggregation, external plugin processing, config file discovery,
4//! config result merging, and plugin detection logic.
5
6use 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/// True when a config pattern names a source-extension config file living
23/// directly in some directory (no path separator, no leading dot, all expanded
24/// extensions are in `SOURCE_EXTENSIONS`).
25///
26/// Such patterns describe files that are already in the discovered file set, so
27/// Phase 3a's in-memory matchers can find them after a `**/` prefix is added.
28/// Callers use this to skip the corresponding filesystem fallback walk in
29/// `discover_config_files`, which is the dominant cost on large monorepos.
30#[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/// Prepare a config pattern for `globset::Glob`.
53#[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
62/// Credit the `default` export of each config file that `patterns` match.
63///
64/// The tool loads its config file and reads the default export, so the export
65/// counts as used under `includeEntryExports`. The patterns get the same
66/// `**/` prefix that config discovery adds, so a config file in a nested
67/// directory gets the credit too.
68fn 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
81/// Collect static patterns from a single plugin into the aggregated result.
82pub 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
100/// Collect a plugin's entry/used-export/class-member/config/always-used rules
101/// into the aggregate, all scoped under `pname`.
102fn 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
157/// Collect a plugin's dependency/virtual-module/alias/auto-import metadata into
158/// the aggregate.
159fn 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
223/// Resolve package.json metadata hooks for active plugins.
224pub 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
256/// Determine whether an external plugin activates against the given project.
257///
258/// Shared between `process_external_plugins` and the collision-warning
259/// helper in `registry::mod` so both paths agree on activation semantics.
260pub 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
282/// Process external plugin definitions, checking activation and aggregating patterns.
283pub 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
340/// In-memory directory listing of config-candidate files (and discovered source
341/// files), keyed by absolute directory, used to resolve plugin config patterns
342/// without re-walking the filesystem.
343///
344/// The index uses the source walk's results, so it respects `.gitignore`,
345/// `ignorePatterns`, and the hidden-directory allowlist. The filesystem lookup
346/// in production mode does not use this index or the walk's traversal rules.
347pub struct ConfigCandidateIndex {
348    dirs: FxHashMap<PathBuf, FxHashSet<OsString>>,
349}
350
351impl ConfigCandidateIndex {
352    /// Build the index from absolute file paths (discovered source files unioned
353    /// with non-source config candidates). Files with no parent or no file name
354    /// are skipped.
355    #[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    /// Whether the discovery walk collected the file at `path`.
369    #[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    /// Whether the directory `dir` contains a file named `name`, per the files
378    /// the discovery walk collected. Used by file-based plugin activation to
379    /// avoid a per-directory filesystem `read` probe.
380    #[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    /// Whether any directory at or below `root` contains a file named `name`,
386    /// per the files the discovery walk collected. Lets a plugin activate from
387    /// a sentinel file nested anywhere under `root` (e.g. a `.env.schema` in a
388    /// workspace subdirectory) without a recursive filesystem walk.
389    #[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    /// Whether any directory at or below `root` contains a file whose name
397    /// matches `matcher`, per the files the discovery walk collected. The glob
398    /// analogue of [`Self::any_descendant_contains`], used to activate a plugin
399    /// from a wildcard config filename (e.g. `tsconfig.*.json`) nested anywhere
400    /// under `root` without a recursive filesystem walk.
401    #[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    /// The file names that the discovery walk collected in the directory `dir`.
413    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
432/// Discover config files for plugins that were not matched against the
433/// discovered source set.
434///
435/// This intentionally probes only known search roots instead of recursively
436/// globbing the whole repository tree. Large monorepos often contain enormous
437/// `node_modules` directories, and a full `**/project.json` walk becomes
438/// pathological there. Callers should therefore pass a focused root list such
439/// as the repo root, workspace roots, and ancestors of discovered source files.
440///
441/// When `candidate_index` is `Some` (the non-production fast path), patterns are
442/// resolved against the in-memory directory index the discovery walk already
443/// built, avoiding one filesystem stat per `(plugin, root, pattern)`. When it is
444/// `None` (production mode), the filesystem is probed directly.
445///
446/// When `production_mode` is `false`, source-extension root-anchored patterns
447/// (e.g., `webpack.config.{ts,js,mjs,cjs}`) are skipped because Phase 3a's
448/// `**/`-prefixed matcher already finds them in the discovered source file
449/// set. In production mode, the file walker excludes `*.config.*` and dotfile
450/// configs, so the FS walk is still required to keep the discovery correct.
451pub 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        // A resolved plugin still probes the patterns that Phase 3a cannot
462        // read: files under a directory that source discovery does not index,
463        // such as `build/webpack.prod.js`, and non-source files, such as a
464        // root `.eslintrc.json` next to a workspace `eslint.config.mjs`. A
465        // source config that Phase 3a read does not cover those files.
466        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                        // A pattern under a non-allowlisted hidden directory
492                        // (e.g. `.config/prisma.ts`) is never descended by the
493                        // discovery walk, so it cannot be in the in-memory
494                        // index; probe the filesystem for those few patterns
495                        // even on the fast path so they stay discoverable.
496                        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
520/// True when every brace alternative of `pattern` names a file with a source
521/// extension. Phase 3a reads only discovered source files, so a resolved plugin
522/// still needs the filesystem fallback for a pattern such as
523/// `.eslintrc.{js,json}`.
524fn 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
536/// True when Phase 3a already read `path` for a resolved plugin. Phase 3a
537/// reads discovered source files only. A file that only a filesystem probe
538/// finds (`needs_fs`) was read when the discovery walk indexed it, for example
539/// a config in an allowlisted hidden directory.
540fn 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
555/// True when `pattern` has a directory component (any component before the
556/// basename) that the discovery walk does not index: a hidden directory NOT on
557/// the walk's traversal allowlist, or a directory that a built-in ignore
558/// pattern excludes, such as `build`. The in-memory candidate index cannot
559/// contain files under them, so the filesystem probe is required to keep those
560/// configs (e.g. `.config/prisma.ts`, `build/webpack.prod.js`) discoverable.
561pub(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; // the basename is not a directory component
567        }
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
584/// Whether a built-in ignore pattern of the form `**/<name>/**` excludes a
585/// directory of this name from source discovery.
586fn 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
597/// In-memory equivalent of [`discover_pattern_matches`], resolving `pattern`
598/// against `index` instead of the filesystem. Mirrors that function's structure
599/// arm-for-arm (plain path, `**/` strip, parent/glob split) so the two produce
600/// identical hits for any file the index contains.
601fn 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
676/// The `{a,b}` expansions of `pattern` that a disk probe may join to a
677/// root. An expansion that is absolute or has a `..` segment is dropped, so
678/// no probe of a config pattern reads outside the root that it joins.
679pub(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
708/// Validate the user-supplied exclude regexes attached to a `PathRule`.
709///
710/// The originating plugin and source config file are surfaced so users can
711/// locate every typo in one config-load error.
712fn 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
751/// Merge a `PluginResult` from config parsing into the aggregated result.
752///
753/// `config_path` is the source config file the plugin parsed (when known).
754/// It is only used to enrich config-load errors so users can find their typo.
755/// Tests and inline package.json fallbacks may pass `None`.
756pub 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
789/// Merge the entry patterns of one config result, with the replace and
790/// accumulate semantics of the plugin.
791fn 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            // An earlier config of the plugin that did not replace (a Vitest
802            // config below the root) keeps its patterns. Only the static
803            // defaults go.
804            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
825/// Merge the path aliases of one plugin result. An alias replaces an earlier
826/// alias with the same prefix, and it also decides whether that prefix is
827/// checked.
828fn 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
854/// Merge a validated `PluginResult`'s payload fields into the aggregate, applying
855/// the per-plugin `replace_*` semantics for entry patterns, used-export rules,
856/// and path aliases.
857fn 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
951/// Check if a plugin already has a config file matched against discovered files.
952pub 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
966/// Check if a `PluginDetection` condition is satisfied.
967pub 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        // `.config` is a hidden directory not on the walk's allowlist, so a
1030        // config under it is never in the in-memory index and must be probed.
1031        assert!(pattern_needs_filesystem(".config/prisma.ts"));
1032        // Plain, nested-non-hidden, dotfile-basename, `**/`, and allowlisted
1033        // hidden-dir (`.storybook`) patterns all resolve from the index.
1034        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        // A directory that a built-in ignore pattern excludes is not indexed.
1041        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        // Plain basename resolved at the project root and at a nested root.
1056        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        // Nested non-glob, `**/` strip, and a basename glob.
1065        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        // A pattern present in no indexed directory yields nothing.
1078        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        // `.*` names hidden directories. The `glob` crate also lets it match
1089        // `..`, so this pattern found the marker in the parent directory.
1090        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}