Skip to main content

fallow_engine/mutation/
mod.rs

1//! The static half of mutation testing: select, map, prune and rank mutants.
2//!
3//! The plan reads only facts that the dead-code analysis already has: the
4//! module graph with its test reachability (including the `vi.mock`
5//! replacement masks), the dead-code results, the function complexity of each
6//! module, and the captured security sink sites. It reads the source text of
7//! each selected file one time to instrument it, and it holds the
8//! instrumented code in memory. It never writes a file and never runs user
9//! code.
10//!
11//! Each mutant gets one disposition:
12//!
13//! - `planned`: a test file reaches the file, and no static rule prunes the
14//!   mutant. The runner executes these mutants in rank order.
15//! - `pending`: a planned mutant after the `max_mutants` limit.
16//! - `no-coverage`: no test file reaches the file in the graph. A test that
17//!   replaces the module with `vi.mock` does not reach it.
18//! - `pruned`: a static rule removes the mutant (see [`PruneReason`](crate::mutation::PruneReason)).
19
20mod build_tool;
21mod constant_condition;
22mod database_write;
23mod function_scope;
24mod layout;
25mod plan;
26mod reach;
27mod sampling;
28mod skipped_tests;
29#[cfg(test)]
30mod tests;
31
32use std::collections::{BTreeMap, BTreeSet};
33use std::path::{Path, PathBuf};
34
35use serde::Serialize;
36
37pub use fallow_mutation::{
38    FunctionRef, Mutant, MutantChange, MutantId, MutationError, MutationOptions, Operator,
39    RESERVED_PREFIX, SourceKind,
40};
41pub use fallow_output::DiffIndex;
42pub use layout::{export_containing, instrument_source, is_component_file};
43pub use skipped_tests::{SkipKind, SkippedTest};
44
45use crate::EngineError;
46use crate::module_graph::{ExportTestReach, RetainedModuleGraph};
47use crate::session::AnalysisSession;
48use crate::source::ModuleInfo;
49use fallow_types::results::AnalysisResults;
50
51/// The runner config modules at the project root. Each test run loads them,
52/// so they and the files that they reach through static imports are in
53/// [`MutationPlan::support_files`].
54pub const RUNNER_CONFIG_MODULES: [&str; 18] = [
55    "vitest.config.ts",
56    "vitest.config.mts",
57    "vitest.config.cts",
58    "vitest.config.js",
59    "vitest.config.mjs",
60    "vitest.config.cjs",
61    "vite.config.ts",
62    "vite.config.mts",
63    "vite.config.cts",
64    "vite.config.js",
65    "vite.config.mjs",
66    "vite.config.cjs",
67    "vitest.workspace.ts",
68    "vitest.workspace.mts",
69    "vitest.workspace.cts",
70    "vitest.workspace.js",
71    "vitest.workspace.mjs",
72    "vitest.workspace.cjs",
73];
74
75/// The files and lines that a plan mutates.
76#[derive(Debug, Clone)]
77pub enum MutationScope {
78    /// The added lines of a diff against the base ref. Build the index with
79    /// the mutation diff machinery (`changed_files::try_get_mutation_diff`,
80    /// `DiffIndex::from_unified_diff` and `diff_source::place_diff`). Only
81    /// mutants that overlap an added line are kept.
82    ChangedSinceBase(DiffIndex),
83    /// Each source file of the project.
84    All,
85    /// The files at these paths, or below these directories. A relative path
86    /// is relative to the project root.
87    Paths(Vec<PathBuf>),
88}
89
90/// What to plan.
91#[derive(Debug, Clone)]
92pub struct MutationPlanRequest {
93    /// The files and lines to mutate.
94    pub scope: MutationScope,
95    /// The operators to use. `None` uses the default set
96    /// (`Operator::DEFAULT`).
97    pub operators: Option<Vec<Operator>>,
98    /// Keep the mutants in functions that call a file system, child process,
99    /// network or database sink. The default prunes them, because a mutant
100    /// can turn a guarded side effect into an unguarded one.
101    pub allow_side_effects: bool,
102    /// The maximum number of planned mutants. The mutants after this limit,
103    /// in rank order, become `pending`.
104    pub max_mutants: Option<usize>,
105    /// The maximum number of planned mutants on one source line. The plan
106    /// keeps the most productive mutants of the line and marks the others
107    /// [`MutantDisposition::SampledOut`]. `None` keeps each mutant.
108    pub mutants_per_line: Option<usize>,
109    /// Widen each changed line of [`MutationScope::ChangedSinceBase`] to the
110    /// whole innermost function that holds it, so that a change to a
111    /// parameter or a signature selects the mutants of the function. The
112    /// other scopes ignore it.
113    pub function_scope: bool,
114    /// Leave each Vue, Svelte and Astro component file out of the plan,
115    /// with the skip reason [`SkipReason::RunnerCannotLoad`]. Set it when
116    /// the test runner has no loader for a component file.
117    pub skip_component_files: bool,
118    /// Run only the mutants with these ids. Each other mutant is pruned with
119    /// [`PruneReason::NotSelected`]. It stays in the plan, because the
120    /// instrumented file still holds its switch. `None` selects each mutant.
121    pub mutant_ids: Option<BTreeSet<String>>,
122    /// Wrap each exported function that holds a planned mutant, so that a
123    /// recording dry run can record its arguments.
124    pub record_exports: bool,
125}
126
127impl MutationPlanRequest {
128    /// A request with the default options for `scope`.
129    #[must_use]
130    pub const fn new(scope: MutationScope) -> Self {
131        Self {
132            scope,
133            operators: None,
134            allow_side_effects: false,
135            max_mutants: None,
136            mutants_per_line: None,
137            function_scope: false,
138            skip_component_files: false,
139            mutant_ids: None,
140            record_exports: false,
141        }
142    }
143}
144
145/// Framework config exports, by root-relative file path.
146///
147/// A framework plugin marks some exports as used by the framework, for
148/// example `export const revalidate = 60` in a Next.js page. A mutant in such
149/// an export changes framework config, not tested logic, so the plan prunes
150/// it. Mutants inside a function in the export are not pruned.
151#[derive(Debug, Clone, Default, PartialEq, Eq)]
152pub struct FrameworkConfigExports {
153    files: BTreeMap<String, BTreeSet<String>>,
154    config_files: BTreeSet<String>,
155}
156
157impl FrameworkConfigExports {
158    /// Records that the framework uses `export` of the root-relative `file`.
159    pub fn insert(&mut self, file: impl Into<String>, export: impl Into<String>) {
160        self.files
161            .entry(file.into())
162            .or_default()
163            .insert(export.into());
164    }
165
166    /// Records that the root-relative `file` is a tool config file. The tool
167    /// reads its default export, and a top-level `module.exports = ...`
168    /// statement counts as that default export.
169    fn insert_config_file(&mut self, file: impl Into<String>) {
170        let file = file.into();
171        self.insert(file.clone(), DEFAULT_EXPORT);
172        self.config_files.insert(file);
173    }
174
175    /// True when [`Self::insert_config_file`] recorded the root-relative
176    /// `file`.
177    #[must_use]
178    fn is_config_file(&self, file: &str) -> bool {
179        self.config_files.contains(file)
180    }
181
182    /// The framework config export names of one root-relative file.
183    #[must_use]
184    fn exports_for(&self, file: &str) -> Option<&BTreeSet<String>> {
185        self.files.get(file)
186    }
187}
188
189/// The analysis facts that a plan reads.
190#[derive(Clone, Copy)]
191pub struct MutationPlanInputs<'a> {
192    /// The project root.
193    pub root: &'a Path,
194    /// The module graph of the analysis.
195    pub graph: &'a RetainedModuleGraph,
196    /// The parsed modules, with complexity.
197    pub modules: &'a [ModuleInfo],
198    /// The dead-code results of the analysis.
199    pub results: &'a AnalysisResults,
200    /// The framework config exports. `None` when the caller has no plugin
201    /// facts. The plan then prunes no `framework-config` and no
202    /// `build-tool-only` mutants and sets
203    /// [`MutationPlan::framework_config_checked`] to false.
204    pub framework_config_exports: Option<&'a FrameworkConfigExports>,
205    /// The setup files of the test runner config, absolute or relative to
206    /// the root, with or without an extension. They fill
207    /// [`MutationPlan::support_files`], with the runner config modules at the
208    /// root.
209    pub setup_files: &'a [PathBuf],
210}
211
212/// Why a static rule removes a mutant.
213#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
214#[serde(rename_all = "kebab-case")]
215pub enum PruneReason {
216    /// The file is unused: no entry point reaches it.
217    DeadCode,
218    /// The file is generated code.
219    Generated,
220    /// The enclosing function calls a file system, child process, network or
221    /// database sink of the security catalogue. A mutant outside each
222    /// function gets this reason when the module calls such a sink outside
223    /// each function, because that sink runs on each import of the module.
224    /// A sink that only shapes a response or a navigation (a redirect, a
225    /// header, a cookie, a CORS policy) does not count.
226    SideEffectSink,
227    /// The mutant is in an export that a framework reads as config.
228    FrameworkConfig,
229    /// Only tool config files reach the file, for example a Vite plugin
230    /// module that only `vite.config.ts` imports. The code runs in the dev
231    /// server or the build, and no test or application entry reaches it.
232    BuildToolOnly,
233    /// The request selects other mutants by id
234    /// ([`MutationPlanRequest::mutant_ids`]).
235    NotSelected,
236}
237
238/// The status of a mutant in a plan.
239#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
240#[serde(tag = "status", content = "reason", rename_all = "kebab-case")]
241pub enum MutantDisposition {
242    /// The runner executes the mutant.
243    Planned,
244    /// A planned mutant after the `max_mutants` limit.
245    Pending,
246    /// A planned mutant that the `mutants_per_line` limit left out. It has
247    /// no rank, and the scheduler never runs it.
248    SampledOut,
249    /// No test file reaches the file of the mutant.
250    NoCoverage,
251    /// A static rule removes the mutant.
252    Pruned(PruneReason),
253}
254
255/// The facts of the function that contains a mutant.
256#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
257pub struct FunctionFacts {
258    /// The function name. The complexity name wins over the syntax name, so
259    /// that the name is the same as in `health` output.
260    pub name: Option<String>,
261    /// The byte span of the function.
262    pub span: (u32, u32),
263    /// The 1-based first line of the function.
264    pub line: u32,
265    /// The 1-based last line of the function.
266    pub end_line: u32,
267    /// The cyclomatic complexity, when the analysis measured the function.
268    pub cyclomatic: Option<u16>,
269    /// True when an added line of the diff is in the function.
270    pub in_diff: bool,
271}
272
273/// One mutant of the plan.
274#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
275pub struct PlannedMutant {
276    /// The mutant.
277    pub mutant: Mutant,
278    /// The root-relative path of the file, with forward slashes.
279    pub file: String,
280    /// The 1-based execution rank of a planned or pending mutant.
281    pub rank: Option<u32>,
282    /// The status of the mutant.
283    pub disposition: MutantDisposition,
284    /// The function that contains the mutant.
285    pub function: Option<FunctionFacts>,
286    /// How tests reach the code of the mutant in the module graph. `None`
287    /// for a pruned mutant.
288    pub test_reach: Option<MutantTestReach>,
289    /// True for a `negate-condition` mutant that sets a parameter test to
290    /// the value that each visible call gives it. A survivor gets the
291    /// `constant-parameter` hint. The plan document does not hold it.
292    #[serde(skip)]
293    pub constant_parameter: bool,
294}
295
296/// How tests reach the code of one mutant, from the module graph.
297///
298/// A mutant in the top-level statement that declares a value export gets the
299/// class of that export. A mutant outside each such statement gets the class
300/// of its file: `none-file` when no test loads the file, `mocked-only` when no
301/// test loads the file and a mock explains an export of the file, and `none`
302/// when a test loads the file.
303#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
304pub struct MutantTestReach {
305    /// The reach class.
306    pub reach: ExportTestReach,
307    /// The export whose declaration holds the mutant. `None` for a mutant
308    /// outside each value export declaration.
309    pub export_name: Option<String>,
310    /// For `mocked-only`: the test files whose references a mock removed,
311    /// sorted.
312    pub tests: Vec<String>,
313    /// Static test-file reach for this exported declaration. Internal plan
314    /// evidence only. This is not per-test runtime export coverage.
315    #[serde(skip)]
316    pub export_test_files: Vec<String>,
317    /// For `mocked-only`: the mocked modules on the reference paths, sorted.
318    pub mocked_targets: Vec<String>,
319}
320
321/// One file that the runner loads in its instrumented form.
322#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
323pub struct PlannedFile {
324    /// The root-relative path, with forward slashes.
325    pub path: String,
326    /// The SHA-256 digest of the file bytes, as lowercase hex.
327    pub source_sha256: String,
328    /// The instrumented source text.
329    pub instrumented_code: String,
330    /// The test files that reach the file through imports, sorted. A test
331    /// that replaces the file, or a module on each import path to it, with
332    /// `vi.mock` is not in the list.
333    pub static_test_files: Vec<String>,
334}
335
336/// Why the plan did not instrument a selected file.
337#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
338#[serde(rename_all = "kebab-case")]
339pub enum SkipReason {
340    /// The file could not be read.
341    Unreadable,
342    /// The file changed after the analysis parsed it.
343    Stale,
344    /// The file does not parse.
345    Parse,
346    /// The file declares a name that the instrumentation reserves.
347    ReservedName,
348    /// The file is larger than 4 GiB.
349    TooLarge,
350    /// The module graph has the file, but the analysis kept no module facts
351    /// for it, for example because extraction could not read it.
352    NotAnalyzed,
353    /// The test runner cannot load the file: a component file under a runner
354    /// with no component loader.
355    RunnerCannotLoad,
356}
357
358/// A selected file that the plan did not instrument.
359#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
360pub struct SkippedFile {
361    /// The root-relative path, with forward slashes.
362    pub path: String,
363    /// Why the plan skipped the file.
364    pub reason: SkipReason,
365}
366
367/// The number of pruned mutants for each reason.
368#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
369pub struct PruneCounts {
370    /// Mutants in unused files.
371    pub dead_code: usize,
372    /// Mutants in generated files.
373    pub generated: usize,
374    /// Mutants in functions that call a side-effect sink, and top-level
375    /// mutants of a module with a top-level side-effect sink.
376    pub side_effect_sink: usize,
377    /// Mutants in framework config exports.
378    pub framework_config: usize,
379    /// Mutants in files that only tool config files reach.
380    pub build_tool_only: usize,
381    /// Mutants that the request did not select by id. A plan document never
382    /// selects by id, so its output has no such count.
383    #[serde(skip)]
384    pub not_selected: usize,
385}
386
387/// The number of mutants for each disposition.
388#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
389pub struct MutationPlanCounts {
390    /// Each mutant of the plan.
391    pub total: usize,
392    /// Planned mutants.
393    pub planned: usize,
394    /// Planned mutants after the `max_mutants` limit.
395    pub pending: usize,
396    /// Planned mutants that the `mutants_per_line` limit left out. They are
397    /// not part of `pending`.
398    pub sampled_out: usize,
399    /// Mutants that no test file reaches.
400    pub no_coverage: usize,
401    /// Pruned mutants, by reason.
402    pub pruned: PruneCounts,
403}
404
405/// The static mutation plan.
406#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
407pub struct MutationPlan {
408    /// The files with a planned or pending mutant, sorted by path.
409    pub files: Vec<PlannedFile>,
410    /// Each mutant. Ranked mutants come first in rank order, then the other
411    /// mutants by file, span and id.
412    pub mutants: Vec<PlannedMutant>,
413    /// The union of the static test files of `files`, sorted.
414    pub test_files: Vec<String>,
415    /// The skipped and todo tests in the runner test files that the diff of a
416    /// changed-code scope changes, sorted by file and line. A test file
417    /// counts when the diff adds, removes or changes a line in it, also when
418    /// it reaches no changed source. A scan of the syntax tree finds the
419    /// tests, so no runner starts. Empty for the other scopes.
420    #[serde(skip)]
421    pub skipped_tests: Vec<SkippedTest>,
422    /// The files that the test files reach through static imports, sorted.
423    /// [`MutationPlan::test_file_reach`] indexes into this list.
424    #[serde(skip)]
425    pub reach_files: Vec<String>,
426    /// The files that each test file of `test_files` reaches through static
427    /// imports, as sorted indices into `reach_files`. The list leaves out the
428    /// test file itself and ignores `vi.mock`, so it is a superset of the
429    /// files that the test loads. The result cache of a run keys on the
430    /// content of these files.
431    #[serde(skip)]
432    pub test_file_reach: BTreeMap<String, Vec<u32>>,
433    /// The setup files of the test runner, the runner config modules at the
434    /// root ([`RUNNER_CONFIG_MODULES`]), and the files that they reach through
435    /// static imports, sorted. Each test loads them, so the result cache keys
436    /// on their content for each mutant.
437    #[serde(skip)]
438    pub support_files: Vec<String>,
439    /// The number of mutants for each disposition.
440    pub counts: MutationPlanCounts,
441    /// True when the project has no test files. Each mutant is then
442    /// `no-coverage`, and a report shows this one fact instead of one line
443    /// for each mutant.
444    pub no_test_files: bool,
445    /// True when the plan applied the `framework-config` and
446    /// `build-tool-only` prune rules. False when the caller gave no framework
447    /// config exports, so that a mutant in such an export or in a module that
448    /// only a tool config file imports can be `planned`.
449    pub framework_config_checked: bool,
450    /// The selected files that the plan did not instrument, sorted by path.
451    pub skipped_files: Vec<SkippedFile>,
452    /// The paths of a `Paths` scope that select no source file, as given and
453    /// with forward slashes, sorted. A path can select no file because it
454    /// does not exist, or because it names only test code, declaration files
455    /// or files outside the module graph.
456    pub unmatched_paths: Vec<String>,
457}
458
459#[cfg(test)]
460impl MutationPlan {
461    /// The files that `test_file` reaches through static imports, sorted.
462    /// Empty for a file that is not a test file of the plan.
463    fn test_file_reach_paths<'a>(&'a self, test_file: &str) -> impl Iterator<Item = &'a str> {
464        self.test_file_reach
465            .get(test_file)
466            .into_iter()
467            .flatten()
468            .filter_map(|&index| self.reach_files.get(index as usize))
469            .map(String::as_str)
470    }
471}
472
473/// An error from [`plan_mutations_for_session`].
474#[derive(Debug, Clone, PartialEq, Eq)]
475pub enum MutationPlanError {
476    /// The analysis failed.
477    Analysis(EngineError),
478    /// The analysis did not keep an artifact that the plan reads.
479    MissingArtifact(&'static str),
480    /// The plugin stage failed, so the plan cannot read the framework config
481    /// exports.
482    Plugins(String),
483}
484
485impl std::fmt::Display for MutationPlanError {
486    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
487        match self {
488            Self::Analysis(error) => write!(f, "the analysis failed: {error}"),
489            Self::MissingArtifact(name) => {
490                write!(
491                    f,
492                    "the analysis did not keep the {name} for the mutation plan"
493                )
494            }
495            Self::Plugins(message) => write!(f, "the plugin stage failed: {message}"),
496        }
497    }
498}
499
500impl std::error::Error for MutationPlanError {}
501
502impl From<EngineError> for MutationPlanError {
503    fn from(error: EngineError) -> Self {
504        Self::Analysis(error)
505    }
506}
507
508/// Builds the mutation plan from the facts of one analysis.
509#[must_use]
510fn plan_mutations(inputs: &MutationPlanInputs<'_>, request: &MutationPlanRequest) -> MutationPlan {
511    plan::build(inputs, request)
512}
513
514/// Runs the dead-code analysis of `session` with complexity and the graph,
515/// then builds the mutation plan.
516///
517/// The framework config exports come from the plugin used-export rules of
518/// the session, the same rules that the unused-export analysis reads. The
519/// plugin stage runs one more time for them.
520///
521/// # Errors
522///
523/// Returns an error when the analysis or the plugin stage fails.
524pub fn plan_mutations_for_session(
525    session: &AnalysisSession,
526    request: &MutationPlanRequest,
527) -> Result<MutationPlan, MutationPlanError> {
528    plan_mutations_for_session_with(session, request, |_| false)
529}
530
531/// Like [`plan_mutations_for_session`], but `skip_components` reads the
532/// first plan and decides if the component files leave the plan. The test
533/// runner can depend on the test files of the plan, so the caller decides
534/// after the first plan. When the first plan has a component mutant and
535/// `skip_components` returns true, the plan is built again from the same
536/// analysis with [`MutationPlanRequest::skip_component_files`] set.
537///
538/// # Errors
539///
540/// Returns an error when the analysis or the plugin stage fails.
541pub fn plan_mutations_for_session_with(
542    session: &AnalysisSession,
543    request: &MutationPlanRequest,
544    skip_components: impl FnOnce(&MutationPlan) -> bool,
545) -> Result<MutationPlan, MutationPlanError> {
546    let artifacts = session.analyze_dead_code_with_artifacts(true, true)?;
547    let graph = artifacts
548        .graph
549        .as_ref()
550        .ok_or(MutationPlanError::MissingArtifact("module graph"))?;
551    let modules = artifacts
552        .modules
553        .as_deref()
554        .ok_or(MutationPlanError::MissingArtifact("parsed modules"))?;
555    let inventory = crate::list_inventory::collect_listing_inventory(session, false)
556        .map_err(|error| MutationPlanError::Plugins(error.message().to_owned()))?;
557    let framework_config_exports = framework_config_exports(session, graph, &inventory);
558    let mut setup_files = inventory.plugins.backend().setup_files();
559    setup_files.extend(crate::core_backend::bun_preload_files(session.root()));
560    let inputs = MutationPlanInputs {
561        root: session.root(),
562        graph,
563        modules,
564        results: &artifacts.results,
565        framework_config_exports: Some(&framework_config_exports),
566        setup_files: &setup_files,
567    };
568    let plan = plan_mutations(&inputs, request);
569    let has_component = plan
570        .mutants
571        .iter()
572        .any(|mutant| is_component_file(&mutant.file));
573    if request.skip_component_files || !has_component || !skip_components(&plan) {
574        return Ok(plan);
575    }
576    let request = MutationPlanRequest {
577        skip_component_files: true,
578        ..request.clone()
579    };
580    Ok(plan_mutations(&inputs, &request))
581}
582
583/// The plugin used-export names of each module of the graph. A tool reads
584/// the default export of its config file, so the default export of each file
585/// that a tool config glob of an active plugin matches is framework config
586/// too.
587fn framework_config_exports(
588    session: &AnalysisSession,
589    graph: &RetainedModuleGraph,
590    inventory: &crate::list_inventory::ListingInventory,
591) -> FrameworkConfigExports {
592    let backend = inventory.plugins.backend();
593    let names = backend.used_export_names();
594    let active = backend.active_plugins();
595    let external = session
596        .config()
597        .external_plugins
598        .iter()
599        .filter(|plugin| active.contains(&plugin.name))
600        .flat_map(|plugin| {
601            plugin
602                .config_patterns
603                .iter()
604                .chain(&plugin.always_used)
605                .cloned()
606        });
607    // Some plugins list their config file as always used, not as a config
608    // glob. The tool config name filter keeps the other always-used files
609    // out.
610    let patterns: Vec<String> = backend
611        .config_patterns()
612        .into_iter()
613        .chain(backend.always_used_patterns())
614        .chain(external)
615        .collect();
616    let config_files = config_file_globs(&patterns);
617    let mut exports = FrameworkConfigExports::default();
618    for node in &graph.as_graph().modules {
619        let rel = crate::module_graph::relative_key_path(&node.path, session.root());
620        for name in names.names_for(&rel) {
621            exports.insert(rel.clone(), name);
622        }
623        if config_files.is_match(&rel) {
624            exports.insert_config_file(rel);
625        }
626    }
627    exports
628}
629
630/// The export name of `export default` and of `module.exports = ...`.
631const DEFAULT_EXPORT: &str = "default";
632
633/// The word in a file name that marks a tool config file, as in
634/// `vite.config.ts`, `stryker.conf.js` or `tsconfig.json`.
635const CONFIG_NAME_MARKERS: [&str; 2] = ["config", ".conf."];
636
637/// True when the file name part of a plugin config glob names a tool config
638/// file: it holds `config` or `.conf.`, or an `rc` suffix as in
639/// `.eslintrc.js`. Some plugins also list application files as config, for
640/// example `codegen*.ts`, `src/module.ts` or `app/routes.ts`. Tests can load
641/// those files, so their default export stays in the plan.
642fn is_tool_config_glob(pattern: &str) -> bool {
643    let name = pattern
644        .rsplit('/')
645        .next()
646        .unwrap_or(pattern)
647        .to_ascii_lowercase();
648    if CONFIG_NAME_MARKERS
649        .iter()
650        .any(|marker| name.contains(marker))
651    {
652        return true;
653    }
654    let stem = name.split(['.', '{']).find(|part| !part.is_empty());
655    stem.is_some_and(|stem| stem.ends_with("rc"))
656}
657
658/// The tool config globs, each also tried under `**/`, because a glob is
659/// relative to the directory that the plugin searches, for example a
660/// workspace package.
661fn config_file_globs(patterns: &[String]) -> globset::GlobSet {
662    let mut builder = globset::GlobSetBuilder::new();
663    for pattern in patterns
664        .iter()
665        .filter(|pattern| is_tool_config_glob(pattern))
666    {
667        let anywhere = if pattern.starts_with("**/") {
668            pattern.clone()
669        } else {
670            format!("**/{pattern}")
671        };
672        for candidate in [pattern.as_str(), anywhere.as_str()] {
673            if let Ok(glob) = globset::Glob::new(candidate) {
674                builder.add(glob);
675            }
676        }
677    }
678    builder
679        .build()
680        .unwrap_or_else(|_| globset::GlobSet::empty())
681}