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