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::{AggregatedPluginResult, PluginRegexValidationError, PluginRegexValidationErrorInput};
18
19/// True when a config pattern names a source-extension config file living
20/// directly in some directory (no path separator, no leading dot, all expanded
21/// extensions are in `SOURCE_EXTENSIONS`).
22///
23/// Such patterns describe files that are already in the discovered file set, so
24/// Phase 3a's in-memory matchers can find them after a `**/` prefix is added.
25/// Callers use this to skip the corresponding filesystem fallback walk in
26/// `discover_config_files`, which is the dominant cost on large monorepos.
27#[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/// Prepare a config pattern for `globset::Glob`.
50#[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
59/// Collect static patterns from a single plugin into the aggregated result.
60pub fn process_static_patterns(
61    plugin: &dyn Plugin,
62    root: &Path,
63    result: &mut AggregatedPluginResult,
64) {
65    let pname = plugin.name().to_string();
66    result.active_plugins.push(pname.clone());
67    result
68        .entry_point_roles
69        .insert(pname.clone(), plugin.entry_point_role());
70
71    collect_static_plugin_rules(plugin, &pname, result);
72    collect_static_plugin_metadata(plugin, root, result);
73}
74
75/// Collect a plugin's entry/used-export/class-member/config/always-used rules
76/// into the aggregate, all scoped under `pname`.
77fn collect_static_plugin_rules(
78    plugin: &dyn Plugin,
79    pname: &str,
80    result: &mut AggregatedPluginResult,
81) {
82    for rule in plugin.entry_pattern_rules() {
83        result.entry_patterns.push((rule, pname.to_string()));
84    }
85    for pat in plugin.config_patterns() {
86        result.config_patterns.push((*pat).to_string());
87    }
88    for pat in plugin.always_used() {
89        result
90            .always_used
91            .push(((*pat).to_string(), pname.to_string()));
92    }
93    for rule in plugin.used_export_rules() {
94        result
95            .used_exports
96            .push(PluginUsedExportRule::new(pname.to_string(), rule));
97    }
98    for member in plugin.used_class_members() {
99        result
100            .used_class_members
101            .push(UsedClassMemberRule::from(*member));
102    }
103    for rule in plugin.used_class_member_rules() {
104        result.used_class_members.push(rule);
105    }
106    for pat in plugin.fixture_glob_patterns() {
107        result
108            .fixture_patterns
109            .push(((*pat).to_string(), pname.to_string()));
110    }
111}
112
113/// Collect a plugin's dependency/virtual-module/alias/auto-import metadata into
114/// the aggregate.
115fn collect_static_plugin_metadata(
116    plugin: &dyn Plugin,
117    root: &Path,
118    result: &mut AggregatedPluginResult,
119) {
120    for dep in plugin.tooling_dependencies() {
121        result.tooling_dependencies.push((*dep).to_string());
122    }
123    for prefix in plugin.virtual_module_prefixes() {
124        result.virtual_module_prefixes.push((*prefix).to_string());
125    }
126    for suffix in plugin.virtual_package_suffixes() {
127        result.virtual_package_suffixes.push((*suffix).to_string());
128    }
129    for pattern in plugin.generated_import_patterns() {
130        result
131            .generated_import_patterns
132            .push((*pattern).to_string());
133    }
134    for prefix in plugin.generated_type_import_prefixes() {
135        result
136            .generated_type_import_prefixes
137            .push((*prefix).to_string());
138    }
139    for (prefix, replacement) in plugin.path_aliases(root) {
140        result.path_aliases.push((prefix.to_string(), replacement));
141    }
142    result.auto_imports.extend(plugin.auto_imports(root));
143    result
144        .provided_dependencies
145        .extend(plugin.provided_dependencies());
146}
147
148/// Resolve package.json metadata hooks for active plugins.
149pub fn process_package_json_metadata(
150    active: &[&dyn Plugin],
151    pkg: &PackageJson,
152    root: &Path,
153    result: &mut AggregatedPluginResult,
154    regex_errors: &mut Vec<PluginRegexValidationError>,
155) {
156    for plugin in active {
157        let package_referenced = plugin.package_json_referenced_dependencies(pkg, root);
158        if !package_referenced.is_empty() {
159            let pkg_path = root.join("package.json");
160            result.package_referenced_dependencies.extend(
161                package_referenced
162                    .into_iter()
163                    .map(|dep| (pkg_path.clone(), dep)),
164            );
165        }
166        let plugin_result = plugin.resolve_package_json(pkg, root);
167        if plugin_result.is_empty() {
168            continue;
169        }
170        tracing::debug!(
171            plugin = plugin.name(),
172            deps = plugin_result.referenced_dependencies.len(),
173            "resolved package.json metadata"
174        );
175        if let Err(mut errors) = process_config_result(plugin.name(), plugin_result, result, None) {
176            regex_errors.append(&mut errors);
177        }
178    }
179}
180
181/// Determine whether an external plugin activates against the given project.
182///
183/// Shared between `process_external_plugins` and the collision-warning
184/// helper in `registry::mod` so both paths agree on activation semantics.
185pub fn is_external_plugin_active(
186    ext: &ExternalPluginDef,
187    all_deps: &[String],
188    root: &Path,
189    discovered_files: &[PathBuf],
190) -> bool {
191    if let Some(detection) = &ext.detection {
192        let all_dep_refs: Vec<&str> = all_deps.iter().map(String::as_str).collect();
193        check_plugin_detection(detection, &all_dep_refs, root, discovered_files)
194    } else if !ext.enablers.is_empty() {
195        ext.enablers.iter().any(|enabler| {
196            if enabler.ends_with('/') {
197                all_deps.iter().any(|d| d.starts_with(enabler))
198            } else {
199                all_deps.iter().any(|d| d == enabler)
200            }
201        })
202    } else {
203        false
204    }
205}
206
207/// Process external plugin definitions, checking activation and aggregating patterns.
208pub fn process_external_plugins(
209    external_plugins: &[ExternalPluginDef],
210    all_deps: &[String],
211    root: &Path,
212    discovered_files: &[PathBuf],
213    result: &mut AggregatedPluginResult,
214) {
215    for ext in external_plugins {
216        let is_active = is_external_plugin_active(ext, all_deps, root, discovered_files);
217        if is_active {
218            result.active_plugins.push(ext.name.clone());
219            result
220                .entry_point_roles
221                .insert(ext.name.clone(), ext.entry_point_role);
222            result.entry_patterns.extend(
223                ext.entry_points
224                    .iter()
225                    .map(|p| (PathRule::new(p.clone()), ext.name.clone())),
226            );
227            if !ext.manifest_entries.is_empty() {
228                result.entry_patterns.extend(
229                    crate::plugins::manifest_entries::evaluate_manifest_entries(ext, root)
230                        .into_iter()
231                        .map(|rule| (rule, ext.name.clone())),
232                );
233            }
234            result.config_patterns.extend(ext.config_patterns.clone());
235            result.always_used.extend(
236                ext.config_patterns
237                    .iter()
238                    .chain(ext.always_used.iter())
239                    .map(|p| (p.clone(), ext.name.clone())),
240            );
241            result
242                .tooling_dependencies
243                .extend(ext.tooling_dependencies.clone());
244            for ue in &ext.used_exports {
245                result.used_exports.push(PluginUsedExportRule::new(
246                    ext.name.clone(),
247                    UsedExportRule::new(ue.pattern.clone(), ue.exports.clone()),
248                ));
249            }
250            result
251                .used_class_members
252                .extend(ext.used_class_members.iter().cloned());
253        }
254    }
255}
256
257/// In-memory directory listing of config-candidate files (and discovered source
258/// files), keyed by absolute directory, used to resolve plugin config patterns
259/// without re-walking the filesystem.
260///
261/// Built once from the files the discovery walk already collected, so a
262/// `discover_config_files` lookup that previously cost one filesystem stat per
263/// `(plugin, ancestor-directory, pattern)` becomes an in-memory set lookup. The
264/// walk respects `.gitignore` / `ignorePatterns` / the hidden-directory
265/// allowlist, so config discovery via this index follows the same traversal
266/// rules as source discovery (the raw filesystem path used in production mode
267/// does not); see the crate docs / CHANGELOG for that deliberate refinement.
268pub struct ConfigCandidateIndex {
269    dirs: FxHashMap<PathBuf, FxHashSet<OsString>>,
270}
271
272impl ConfigCandidateIndex {
273    /// Build the index from absolute file paths (discovered source files unioned
274    /// with non-source config candidates). Files with no parent or no file name
275    /// are skipped.
276    #[must_use]
277    pub fn build<'a>(paths: impl IntoIterator<Item = &'a Path>) -> Self {
278        let mut dirs: FxHashMap<PathBuf, FxHashSet<OsString>> = FxHashMap::default();
279        for path in paths {
280            if let (Some(parent), Some(name)) = (path.parent(), path.file_name()) {
281                dirs.entry(parent.to_path_buf())
282                    .or_default()
283                    .insert(name.to_os_string());
284            }
285        }
286        Self { dirs }
287    }
288
289    /// Whether the directory `dir` contains a file named `name`, per the files
290    /// the discovery walk collected. Used by file-based plugin activation to
291    /// avoid a per-directory filesystem `read` probe.
292    #[must_use]
293    pub fn dir_contains(&self, dir: &Path, name: &OsStr) -> bool {
294        self.dirs.get(dir).is_some_and(|names| names.contains(name))
295    }
296
297    /// Whether any directory at or below `root` contains a file named `name`,
298    /// per the files the discovery walk collected. Lets a plugin activate from
299    /// a sentinel file nested anywhere under `root` (e.g. a `.env.schema` in a
300    /// workspace subdirectory) without a recursive filesystem walk.
301    #[must_use]
302    pub fn any_descendant_contains(&self, root: &Path, name: &OsStr) -> bool {
303        self.dirs
304            .iter()
305            .any(|(dir, names)| dir.starts_with(root) && names.contains(name))
306    }
307
308    /// Whether any directory at or below `root` contains a file whose name
309    /// matches `matcher`, per the files the discovery walk collected. The glob
310    /// analogue of [`Self::any_descendant_contains`], used to activate a plugin
311    /// from a wildcard config filename (e.g. `tsconfig.*.json`) nested anywhere
312    /// under `root` without a recursive filesystem walk.
313    #[must_use]
314    pub fn any_descendant_matches(&self, root: &Path, matcher: &globset::GlobMatcher) -> bool {
315        self.dirs.iter().any(|(dir, names)| {
316            dir.starts_with(root) && names.iter().any(|name| matcher.is_match(Path::new(name)))
317        })
318    }
319
320    fn glob_matches_in_dir(&self, dir: &Path, matcher: &globset::GlobMatcher) -> Vec<PathBuf> {
321        self.dirs.get(dir).map_or_else(Vec::new, |names| {
322            names
323                .iter()
324                .filter(|name| matcher.is_match(Path::new(name)))
325                .map(|name| dir.join(name))
326                .collect()
327        })
328    }
329}
330
331/// Discover config files for plugins that were not matched against the
332/// discovered source set.
333///
334/// This intentionally probes only known search roots instead of recursively
335/// globbing the whole repository tree. Large monorepos often contain enormous
336/// `node_modules` directories, and a full `**/project.json` walk becomes
337/// pathological there. Callers should therefore pass a focused root list such
338/// as the repo root, workspace roots, and ancestors of discovered source files.
339///
340/// When `candidate_index` is `Some` (the non-production fast path), patterns are
341/// resolved against the in-memory directory index the discovery walk already
342/// built, avoiding one filesystem stat per `(plugin, root, pattern)`. When it is
343/// `None` (production mode), the filesystem is probed directly.
344///
345/// When `production_mode` is `false`, source-extension root-anchored patterns
346/// (e.g., `webpack.config.{ts,js,mjs,cjs}`) are skipped because Phase 3a's
347/// `**/`-prefixed matcher already finds them in the discovered source file
348/// set. In production mode, the file walker excludes `*.config.*` and dotfile
349/// configs, so the FS walk is still required to keep the discovery correct.
350pub fn discover_config_files<'a>(
351    config_matchers: &[(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
352    resolved_plugins: &FxHashSet<&str>,
353    roots: &[&Path],
354    production_mode: bool,
355    candidate_index: Option<&ConfigCandidateIndex>,
356) -> Vec<(PathBuf, &'a dyn Plugin)> {
357    use rayon::prelude::*;
358    let mut pending: Vec<(&'a dyn Plugin, &Path, String)> = Vec::new();
359    for (plugin, _) in config_matchers {
360        if resolved_plugins.contains(plugin.name()) {
361            continue;
362        }
363        for root in roots {
364            for pat in plugin.config_patterns() {
365                if !production_mode && is_source_ext_root_pattern(pat) {
366                    continue;
367                }
368                pending.push((*plugin, *root, pat.to_string()));
369            }
370        }
371    }
372
373    let hits: Vec<(PathBuf, &'a dyn Plugin)> = pending
374        .par_iter()
375        .flat_map_iter(|(plugin, root, pat)| {
376            expand_brace_pattern(pat)
377                .into_iter()
378                .flat_map(|expanded| match candidate_index {
379                    // A pattern under a non-allowlisted hidden directory
380                    // (e.g. `.config/prisma.ts`) is never descended by the
381                    // discovery walk, so it cannot be in the in-memory index;
382                    // probe the filesystem for those few patterns even on the
383                    // fast path so they stay discoverable.
384                    Some(index) if !pattern_needs_filesystem(&expanded) => {
385                        match_pattern_in_index(root, &expanded, index)
386                    }
387                    _ => discover_pattern_matches(root, &expanded),
388                })
389                .map(move |path| (path, *plugin))
390                .collect::<Vec<_>>()
391        })
392        .collect();
393
394    let mut seen: FxHashSet<(PathBuf, &'a str)> = FxHashSet::default();
395    let mut config_files: Vec<(PathBuf, &'a dyn Plugin)> = Vec::with_capacity(hits.len());
396    for (path, plugin) in hits {
397        if seen.insert((path.clone(), plugin.name())) {
398            config_files.push((path, plugin));
399        }
400    }
401    config_files
402}
403
404fn pattern_has_glob(pattern: &str) -> bool {
405    pattern.contains('*') || pattern.contains('?') || pattern.contains('[')
406}
407
408/// True when `pattern` has a directory component (any component before the
409/// basename) that is a hidden directory NOT on the walk's traversal allowlist.
410/// The discovery walk never descends such directories, so the in-memory
411/// candidate index cannot contain files under them and the filesystem probe is
412/// required to keep those configs (e.g. `.config/prisma.ts`) discoverable.
413fn pattern_needs_filesystem(pattern: &str) -> bool {
414    let mut components = pattern.split('/').peekable();
415    let mut needs_fs = false;
416    while let Some(component) = components.next() {
417        if components.peek().is_none() {
418            break; // the basename is not a directory component
419        }
420        if component.starts_with('.')
421            && component != "."
422            && component != ".."
423            && !crate::discover::is_allowed_hidden_dir(OsStr::new(component))
424        {
425            needs_fs = true;
426            break;
427        }
428    }
429    needs_fs
430}
431
432/// In-memory equivalent of [`discover_pattern_matches`], resolving `pattern`
433/// against `index` instead of the filesystem. Mirrors that function's structure
434/// arm-for-arm (plain path, `**/` strip, parent/glob split) so the two produce
435/// identical hits for any file the index contains.
436fn match_pattern_in_index(
437    root: &Path,
438    pattern: &str,
439    index: &ConfigCandidateIndex,
440) -> Vec<PathBuf> {
441    if !pattern_has_glob(pattern) {
442        let path = root.join(pattern);
443        return match (path.parent(), path.file_name()) {
444            (Some(dir), Some(name)) if index.dir_contains(dir, name) => vec![path],
445            _ => Vec::new(),
446        };
447    }
448
449    if let Some(stripped) = pattern.strip_prefix("**/") {
450        return match_pattern_in_index(root, stripped, index);
451    }
452
453    let (dir, file_pattern) = match pattern.rsplit_once('/') {
454        Some((parent, file_pattern)) if !pattern_has_glob(parent) => {
455            (root.join(parent), file_pattern)
456        }
457        Some(_) => return Vec::new(),
458        None => (root.to_path_buf(), pattern),
459    };
460
461    let Ok(matcher) = globset::Glob::new(file_pattern).map(|g| g.compile_matcher()) else {
462        return Vec::new();
463    };
464    index.glob_matches_in_dir(&dir, &matcher)
465}
466
467fn discover_pattern_matches(root: &Path, pattern: &str) -> Vec<PathBuf> {
468    if !pattern_has_glob(pattern) {
469        let path = root.join(pattern);
470        return if path.is_file() {
471            vec![path]
472        } else {
473            Vec::new()
474        };
475    }
476
477    if let Some(stripped) = pattern.strip_prefix("**/") {
478        return discover_pattern_matches(root, stripped);
479    }
480
481    let (dir, file_pattern) = match pattern.rsplit_once('/') {
482        Some((parent, file_pattern)) if !pattern_has_glob(parent) => {
483            (root.join(parent), file_pattern)
484        }
485        Some(_) => return Vec::new(),
486        None => (root.to_path_buf(), pattern),
487    };
488
489    scan_dir_for_pattern(&dir, file_pattern)
490}
491
492fn scan_dir_for_pattern(dir: &Path, file_pattern: &str) -> Vec<PathBuf> {
493    let Ok(matcher) = globset::Glob::new(file_pattern).map(|g| g.compile_matcher()) else {
494        return Vec::new();
495    };
496    let Ok(entries) = std::fs::read_dir(dir) else {
497        return Vec::new();
498    };
499
500    entries
501        .filter_map(Result::ok)
502        .map(|entry| entry.path())
503        .filter(|path| path.is_file())
504        .filter(|path| {
505            path.file_name()
506                .is_some_and(|name| matcher.is_match(std::path::Path::new(name)))
507        })
508        .collect()
509}
510
511fn expand_brace_pattern(pattern: &str) -> Vec<String> {
512    let Some(open) = pattern.find('{') else {
513        return vec![pattern.to_string()];
514    };
515    let Some(close_rel) = pattern[open + 1..].find('}') else {
516        return vec![pattern.to_string()];
517    };
518    let close = open + 1 + close_rel;
519
520    let prefix = &pattern[..open];
521    let suffix = &pattern[close + 1..];
522    let inner = &pattern[open + 1..close];
523    let mut expanded = Vec::new();
524    for option in inner.split(',') {
525        for tail in expand_brace_pattern(suffix) {
526            expanded.push(format!("{prefix}{option}{tail}"));
527        }
528    }
529    expanded
530}
531
532/// Validate the user-supplied exclude regexes attached to a `PathRule`.
533///
534/// The originating plugin and source config file are surfaced so users can
535/// locate every typo in one config-load error.
536fn collect_path_rule_regex_errors(
537    rule: &crate::plugins::PathRule,
538    plugin_name: &str,
539    config_path: Option<&Path>,
540    rule_kind: &'static str,
541    errors: &mut Vec<PluginRegexValidationError>,
542) {
543    for pattern in &rule.exclude_regexes {
544        if let Err(source) = regex::Regex::new(pattern) {
545            errors.push(PluginRegexValidationError::new(
546                PluginRegexValidationErrorInput {
547                    plugin_name,
548                    config_path,
549                    rule_kind,
550                    field: "exclude_regexes",
551                    rule_pattern: &rule.pattern,
552                    regex_pattern: pattern,
553                    source: &source,
554                },
555            ));
556        }
557    }
558    for pattern in &rule.exclude_segment_regexes {
559        if let Err(source) = regex::Regex::new(pattern) {
560            errors.push(PluginRegexValidationError::new(
561                PluginRegexValidationErrorInput {
562                    plugin_name,
563                    config_path,
564                    rule_kind,
565                    field: "exclude_segment_regexes",
566                    rule_pattern: &rule.pattern,
567                    regex_pattern: pattern,
568                    source: &source,
569                },
570            ));
571        }
572    }
573}
574
575/// Merge a `PluginResult` from config parsing into the aggregated result.
576///
577/// `config_path` is the source config file the plugin parsed (when known).
578/// It is only used to enrich config-load errors so users can find their typo.
579/// Tests and inline package.json fallbacks may pass `None`.
580pub fn process_config_result(
581    plugin_name: &str,
582    plugin_result: PluginResult,
583    result: &mut AggregatedPluginResult,
584    config_path: Option<&Path>,
585) -> Result<(), Vec<PluginRegexValidationError>> {
586    let mut regex_errors = Vec::new();
587
588    for rule in &plugin_result.entry_patterns {
589        collect_path_rule_regex_errors(
590            rule,
591            plugin_name,
592            config_path,
593            "entry_patterns[]",
594            &mut regex_errors,
595        );
596    }
597    for rule in &plugin_result.used_exports {
598        collect_path_rule_regex_errors(
599            &rule.path,
600            plugin_name,
601            config_path,
602            "used_exports[].path",
603            &mut regex_errors,
604        );
605    }
606    if !regex_errors.is_empty() {
607        return Err(regex_errors);
608    }
609    merge_plugin_result_fields(plugin_name, plugin_result, result);
610    Ok(())
611}
612
613/// Merge a validated `PluginResult`'s payload fields into the aggregate, applying
614/// the per-plugin `replace_*` semantics for entry patterns, used-export rules,
615/// and path aliases.
616fn merge_plugin_result_fields(
617    pname: &str,
618    plugin_result: PluginResult,
619    result: &mut AggregatedPluginResult,
620) {
621    if plugin_result.replace_entry_patterns && !plugin_result.entry_patterns.is_empty() {
622        result.entry_patterns.retain(|(_, name)| name != pname);
623    }
624    if plugin_result.replace_used_export_rules && !plugin_result.used_exports.is_empty() {
625        result.used_exports.retain(|rule| rule.plugin_name != pname);
626    }
627    result.entry_patterns.extend(
628        plugin_result
629            .entry_patterns
630            .into_iter()
631            .map(|rule| (rule, pname.to_string())),
632    );
633    result.used_exports.extend(
634        plugin_result
635            .used_exports
636            .into_iter()
637            .map(|rule| PluginUsedExportRule::new(pname.to_string(), rule)),
638    );
639    result
640        .used_class_members
641        .extend(plugin_result.used_class_members);
642    result
643        .referenced_dependencies
644        .extend(plugin_result.referenced_dependencies);
645    result.discovered_always_used.extend(
646        plugin_result
647            .always_used_files
648            .into_iter()
649            .map(|p| (p, pname.to_string())),
650    );
651    for (prefix, replacement) in plugin_result.path_aliases {
652        result
653            .path_aliases
654            .retain(|(existing_prefix, _)| existing_prefix != &prefix);
655        result.path_aliases.push((prefix, replacement));
656    }
657    result.setup_files.extend(
658        plugin_result
659            .setup_files
660            .into_iter()
661            .map(|p| (p, pname.to_string())),
662    );
663    result.fixture_patterns.extend(
664        plugin_result
665            .fixture_patterns
666            .into_iter()
667            .map(|p| (p, pname.to_string())),
668    );
669    result
670        .scss_include_paths
671        .extend(plugin_result.scss_include_paths);
672    result
673        .static_dir_mappings
674        .extend(plugin_result.static_dir_mappings);
675    result
676        .provided_dependencies
677        .extend(plugin_result.provided_dependencies);
678}
679
680/// Check if a plugin already has a config file matched against discovered files.
681pub fn check_has_config_file(
682    plugin: &dyn Plugin,
683    config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
684    relative_files: &[(PathBuf, String)],
685) -> bool {
686    !plugin.config_patterns().is_empty()
687        && config_matchers.iter().any(|(p, matchers)| {
688            p.name() == plugin.name()
689                && relative_files
690                    .iter()
691                    .any(|(_, rel)| matchers.iter().any(|m| m.is_match(rel.as_str())))
692        })
693}
694
695/// Check if a `PluginDetection` condition is satisfied.
696pub fn check_plugin_detection(
697    detection: &PluginDetection,
698    all_deps: &[&str],
699    root: &Path,
700    discovered_files: &[PathBuf],
701) -> bool {
702    match detection {
703        PluginDetection::Dependency { package } => all_deps.iter().any(|d| *d == package),
704        PluginDetection::FileExists { pattern } => {
705            if let Ok(matcher) = globset::Glob::new(pattern).map(|g| g.compile_matcher()) {
706                for file in discovered_files {
707                    let relative = file.strip_prefix(root).unwrap_or(file);
708                    if matcher.is_match(relative) {
709                        return true;
710                    }
711                }
712            }
713            let full_pattern = root.join(pattern).to_string_lossy().to_string();
714            glob::glob(&full_pattern)
715                .ok()
716                .is_some_and(|mut g| g.next().is_some())
717        }
718        PluginDetection::All { conditions } => conditions
719            .iter()
720            .all(|c| check_plugin_detection(c, all_deps, root, discovered_files)),
721        PluginDetection::Any { conditions } => conditions
722            .iter()
723            .any(|c| check_plugin_detection(c, all_deps, root, discovered_files)),
724    }
725}
726
727#[cfg(test)]
728mod tests {
729    use super::*;
730
731    #[test]
732    fn pattern_needs_filesystem_only_for_non_allowlisted_hidden_dirs() {
733        // `.config` is a hidden directory not on the walk's allowlist, so a
734        // config under it is never in the in-memory index and must be probed.
735        assert!(pattern_needs_filesystem(".config/prisma.ts"));
736        // Plain, nested-non-hidden, dotfile-basename, `**/`, and allowlisted
737        // hidden-dir (`.storybook`) patterns all resolve from the index.
738        assert!(!pattern_needs_filesystem("tsconfig.json"));
739        assert!(!pattern_needs_filesystem("prisma/schema.prisma"));
740        assert!(!pattern_needs_filesystem(".eslintrc.json"));
741        assert!(!pattern_needs_filesystem("**/project.json"));
742        assert!(!pattern_needs_filesystem(".storybook/main.ts"));
743        assert!(!pattern_needs_filesystem("a/b/c.json"));
744    }
745
746    #[test]
747    fn config_candidate_index_matches_plain_nested_and_glob_shapes() {
748        let root = Path::new("/project");
749        let index = ConfigCandidateIndex::build([
750            Path::new("/project/tsconfig.json"),
751            Path::new("/project/packages/a/tsconfig.json"),
752            Path::new("/project/prisma/schema.prisma"),
753            Path::new("/project/src/main.ts"),
754        ]);
755
756        // Plain basename resolved at the project root and at a nested root.
757        assert_eq!(
758            match_pattern_in_index(root, "tsconfig.json", &index),
759            vec![PathBuf::from("/project/tsconfig.json")]
760        );
761        assert_eq!(
762            match_pattern_in_index(Path::new("/project/packages/a"), "tsconfig.json", &index),
763            vec![PathBuf::from("/project/packages/a/tsconfig.json")]
764        );
765        // Nested non-glob, `**/` strip, and a basename glob.
766        assert_eq!(
767            match_pattern_in_index(root, "prisma/schema.prisma", &index),
768            vec![PathBuf::from("/project/prisma/schema.prisma")]
769        );
770        assert_eq!(
771            match_pattern_in_index(root, "**/tsconfig.json", &index),
772            vec![PathBuf::from("/project/tsconfig.json")]
773        );
774        assert_eq!(
775            match_pattern_in_index(Path::new("/project/prisma"), "*.prisma", &index),
776            vec![PathBuf::from("/project/prisma/schema.prisma")]
777        );
778        // A pattern present in no indexed directory yields nothing.
779        assert!(match_pattern_in_index(root, "missing.json", &index).is_empty());
780    }
781}