Skip to main content

fallow_engine/project_config/
mod.rs

1//! Project config resolution owned by the engine boundary.
2
3use std::path::{Path, PathBuf};
4
5use fallow_config::{
6    ConfigLoadOptions, EnvSnapshot, FallowConfig, ProductionAnalysis, ResolvedConfig,
7    WorkspaceDiagnostic, WorkspaceInfo,
8};
9use fallow_types::output_format::OutputFormat;
10use fallow_types::sourced::{Given, Origin};
11
12use crate::EngineResult;
13use crate::resolved_run::steps::{
14    GivenSettings, ModeEntry, flatten_production, mode_entry, mode_entry_lossy,
15    validate_boundaries_and_rule_packs, validate_config,
16};
17pub(crate) use crate::resolved_run::steps::{collect_workspace_metadata, resolve_with_env_from};
18use crate::resolved_run::{PerAnalysis, ProductionInputs, decide_production};
19
20mod loader;
21
22#[cfg(any(test, feature = "testing"))]
23pub use loader::load_count;
24pub use loader::{
25    ConfigChainSnapshot, ConfigFile, ConfigFileOptions, ConfigLoadError, find_config_file,
26    load_config_file,
27};
28
29/// The production flags of one run: the global `--production` override and one
30/// override per analysis (`--production-dead-code`, `--production-health`,
31/// `--production-dupes`).
32///
33/// Every command and surface that runs more than one analysis reads the
34/// production mode of each analysis from here, so the precedence has one
35/// implementation: the flag of the analysis, then the global override, then
36/// the config.
37#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
38pub struct ProductionFlags {
39    /// The global override. The CLI sets `Some(true)` for `--production` and
40    /// `None` without it. The programmatic API can also pass `Some(false)`.
41    pub global: Option<bool>,
42    /// Override for the dead-code analysis.
43    pub dead_code: Option<bool>,
44    /// Override for the health analysis.
45    pub health: Option<bool>,
46    /// Override for the duplication analysis.
47    pub dupes: Option<bool>,
48}
49
50impl ProductionFlags {
51    /// The flags of a CLI run, where `--production` can only switch the mode
52    /// on.
53    #[must_use]
54    pub const fn from_cli(
55        production: bool,
56        dead_code: Option<bool>,
57        health: Option<bool>,
58        dupes: Option<bool>,
59    ) -> Self {
60        Self {
61            global: if production { Some(true) } else { None },
62            dead_code,
63            health,
64            dupes,
65        }
66    }
67
68    /// The production override of a command that runs one analysis
69    /// (`dead-code`, `dupes`, `health`): its own override, else
70    /// `--production`. `None` means that the config decides.
71    #[must_use]
72    pub const fn single_analysis_override(production: bool, own: Option<bool>) -> Option<bool> {
73        Self::from_cli(production, own, None, None).override_for(ProductionAnalysis::DeadCode)
74    }
75
76    /// The override flag of one analysis, without the global override.
77    #[must_use]
78    const fn own(self, analysis: ProductionAnalysis) -> Option<bool> {
79        match analysis {
80            ProductionAnalysis::DeadCode => self.dead_code,
81            ProductionAnalysis::Health => self.health,
82            ProductionAnalysis::Dupes => self.dupes,
83        }
84    }
85
86    /// The production override of one analysis: its own flag, else the global
87    /// override. `None` means that the config decides.
88    #[must_use]
89    pub const fn override_for(self, analysis: ProductionAnalysis) -> Option<bool> {
90        match self.own(analysis) {
91            Some(value) => Some(value),
92            None => self.global,
93        }
94    }
95
96    /// The production mode of one analysis as far as the flags decide, before
97    /// the config is loaded. A missing flag reads as `false`.
98    #[must_use]
99    pub const fn mode(self, analysis: ProductionAnalysis) -> bool {
100        match self.override_for(analysis) {
101            Some(value) => value,
102            None => false,
103        }
104    }
105
106    /// The production mode of each analysis as far as the flags decide.
107    #[must_use]
108    pub const fn modes(self) -> ProductionModes {
109        ProductionModes {
110            dead_code: self.mode(ProductionAnalysis::DeadCode),
111            health: self.mode(ProductionAnalysis::Health),
112            dupes: self.mode(ProductionAnalysis::Dupes),
113        }
114    }
115
116    /// The effective production mode of one analysis: the flags first, then
117    /// the `production` setting of the config.
118    #[must_use]
119    pub fn effective(
120        self,
121        analysis: ProductionAnalysis,
122        config: &fallow_config::ProductionConfig,
123    ) -> bool {
124        *decide_production(&self.as_inputs(), config, None)
125            .get(analysis)
126            .value()
127    }
128
129    /// The effective production mode of each analysis.
130    #[cfg(test)]
131    #[must_use]
132    pub(crate) fn effective_modes(
133        self,
134        config: &fallow_config::ProductionConfig,
135    ) -> ProductionModes {
136        let decided = decide_production(&self.as_inputs(), config, None);
137        ProductionModes {
138            dead_code: decided.dead_code.into_value(),
139            health: decided.health.into_value(),
140            dupes: decided.dupes.into_value(),
141        }
142    }
143
144    /// The override of each analysis from `self`, else from `fallback`. The
145    /// parity tests use it to put the flags before the environment
146    /// variables. The config decides only when neither source sets a
147    /// value. `fallback` has the rank of the environment variables in
148    /// `decide_production`.
149    #[cfg(test)]
150    #[must_use]
151    pub(crate) fn with_fallback(self, fallback: Self) -> Self {
152        use fallow_types::sourced::{Layer, Sourced};
153
154        let inputs = ProductionInputs {
155            global_env: fallback.global,
156            own_env: PerAnalysis {
157                dead_code: fallback.dead_code,
158                health: fallback.health,
159                dupes: fallback.dupes,
160            },
161            ..self.as_inputs()
162        };
163        let decided = decide_production(&inputs, &fallow_config::ProductionConfig::default(), None);
164        let given = |decision: &Sourced<bool>| {
165            (decision.source().layer() != Layer::Default).then_some(*decision.value())
166        };
167        Self {
168            global: None,
169            dead_code: given(&decided.dead_code),
170            health: given(&decided.health),
171            dupes: given(&decided.dupes),
172        }
173    }
174
175    /// The flags as caller-given production inputs, without environment
176    /// variables.
177    fn as_inputs(self) -> ProductionInputs {
178        let given = |value: Option<bool>, name| {
179            value.map(|value| Given {
180                value,
181                origin: Origin::ApiOption(name),
182            })
183        };
184        ProductionInputs {
185            global_flag: given(self.global, "ProductionFlags.global"),
186            own_flag: PerAnalysis {
187                dead_code: given(self.dead_code, "ProductionFlags.dead_code"),
188                health: given(self.health, "ProductionFlags.health"),
189                dupes: given(self.dupes, "ProductionFlags.dupes"),
190            },
191            global_env: None,
192            own_env: PerAnalysis::default(),
193        }
194    }
195}
196
197/// The production mode of each analysis of one run.
198#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
199pub struct ProductionModes {
200    /// Production mode of the dead-code analysis.
201    pub dead_code: bool,
202    /// Production mode of the health analysis.
203    pub health: bool,
204    /// Production mode of the duplication analysis.
205    pub dupes: bool,
206}
207
208impl ProductionModes {
209    /// The production mode of one analysis.
210    #[must_use]
211    pub const fn for_analysis(self, analysis: ProductionAnalysis) -> bool {
212        match analysis {
213            ProductionAnalysis::DeadCode => self.dead_code,
214            ProductionAnalysis::Health => self.health,
215            ProductionAnalysis::Dupes => self.dupes,
216        }
217    }
218
219    /// Whether health can reuse the dead-code parse: both run in the same mode.
220    #[must_use]
221    pub const fn dead_code_matches_health(self) -> bool {
222        self.dead_code == self.health
223    }
224
225    /// Whether duplication can reuse the dead-code files: both run in the same
226    /// mode.
227    #[must_use]
228    pub const fn dead_code_matches_dupes(self) -> bool {
229        self.dead_code == self.dupes
230    }
231
232    /// Whether all three analyses run in the same mode.
233    #[must_use]
234    pub const fn all_match(self) -> bool {
235        self.dead_code_matches_health() && self.dead_code_matches_dupes()
236    }
237}
238
239/// Resolved project config plus the config file path when one was loaded.
240#[derive(Debug)]
241pub struct ProjectConfig {
242    /// Fully resolved config for the project.
243    pub config: ResolvedConfig,
244    /// Path of the loaded config file; `None` when defaults were used.
245    pub path: Option<PathBuf>,
246    /// Workspace metadata discovered under the project root.
247    pub workspaces: Vec<WorkspaceInfo>,
248    /// Diagnostics from workspace discovery (undeclared or invalid members).
249    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
250    /// Workspace discovery wall time in milliseconds, when measured.
251    pub(crate) workspace_discovery_ms: Option<f64>,
252    /// The plugin files, rule packs and `autoDiscover` directories that
253    /// config resolution read.
254    pub inputs: fallow_config::ConfigInputs,
255    /// The content of [`Self::inputs`] just before resolution read them.
256    pub(crate) inputs_before_resolve: fallow_config::ConfigInputsSnapshot,
257    /// The files that duplication analyzes.
258    pub(crate) duplication: DuplicationScope,
259}
260
261/// The files that duplication analyzes.
262#[derive(Debug, Clone)]
263pub(crate) enum DuplicationScope {
264    /// The production mode of duplication equals the mode of the session
265    /// config, so duplication analyzes the files of the session.
266    SameAsSession,
267    /// The production mode of duplication differs from the mode of the
268    /// session config. The session resolves this config, which has the
269    /// `production` setting of duplication, and walks its files on the first
270    /// duplication call.
271    Own {
272        config: Box<FallowConfig>,
273        options: ResolveOptions,
274        env: Box<EnvSnapshot>,
275        /// The settings that win over `env`. The session writes them on the
276        /// config after it resolves the config with `env`.
277        given: Box<GivenSettings>,
278    },
279}
280
281impl DuplicationScope {
282    /// The scope of a session config that is flattened for dead code. When
283    /// the flags and the config give duplication another production mode,
284    /// duplication gets a copy of the config flattened for its own mode.
285    fn for_dead_code_session(
286        file: &ConfigFile,
287        flags: ProductionFlags,
288        options: ResolveOptions,
289        env: &EnvSnapshot,
290    ) -> Self {
291        let mode = |analysis| {
292            if file.path.is_some() {
293                flags.effective(analysis, &file.config.production)
294            } else {
295                flags.mode(analysis)
296            }
297        };
298        if mode(ProductionAnalysis::Dupes) == mode(ProductionAnalysis::DeadCode) {
299            return Self::SameAsSession;
300        }
301        let dupes = ConfigFile {
302            config: file.config.clone(),
303            path: file.path.clone(),
304            chain: file.chain.clone(),
305        }
306        .for_analysis(ProductionAnalysis::Dupes, flags);
307        Self::Own {
308            config: Box::new(dupes.config),
309            options,
310            env: Box::new(env.clone()),
311            given: Box::default(),
312        }
313    }
314}
315
316/// The run settings that resolution records on the config.
317#[derive(Debug, Clone, Copy)]
318pub struct ResolveOptions {
319    /// Output format the resolved config carries into rendering.
320    pub output: OutputFormat,
321    /// Worker thread count recorded on the resolved config.
322    pub threads: usize,
323    /// Bypass the parse cache for this run.
324    pub no_cache: bool,
325    /// Suppress progress notes on stderr.
326    pub quiet: bool,
327}
328
329impl ResolveOptions {
330    /// The settings of a host that resolves a config without a CLI run.
331    fn host_default() -> Self {
332        Self {
333            output: OutputFormat::Human,
334            threads: std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get),
335            no_cache: false,
336            quiet: true,
337        }
338    }
339}
340
341impl ConfigFile {
342    /// Flatten the `production` setting of the config for one analysis: the
343    /// flags decide first, then the config. A project without a config file
344    /// gets the mode of the flags.
345    #[must_use]
346    pub fn for_analysis(mut self, analysis: ProductionAnalysis, flags: ProductionFlags) -> Self {
347        let from_file = self.path.is_some();
348        let on = if from_file {
349            flags.effective(analysis, &self.config.production)
350        } else {
351            flags.mode(analysis)
352        };
353        flatten_production(&mut self.config, from_file, on);
354        self
355    }
356
357    /// Validate the external plugins, the boundaries and the rule packs of
358    /// the config.
359    ///
360    /// # Errors
361    ///
362    /// Returns an error that names the first invalid part and lists each of
363    /// its problems.
364    pub fn validate(&self, root: &Path) -> EngineResult<()> {
365        validate_config(root, &self.config)
366    }
367
368    /// Resolve the config for `root`, then apply the environment variables
369    /// that every host honors.
370    #[must_use]
371    pub fn resolve(self, root: &Path, options: ResolveOptions) -> ResolvedConfig {
372        resolve_with_env(self.config, root, options)
373    }
374}
375
376fn resolve_with_env(config: FallowConfig, root: &Path, options: ResolveOptions) -> ResolvedConfig {
377    resolve_with_env_from(config, root, options, &EnvSnapshot::capture())
378}
379
380impl ModeEntry {
381    /// The project config of this mode entry.
382    pub(crate) fn into_project_config(
383        self,
384        path: Option<PathBuf>,
385        duplication: DuplicationScope,
386    ) -> ProjectConfig {
387        ProjectConfig {
388            config: self.config,
389            path,
390            workspaces: self.workspaces,
391            workspace_diagnostics: self.workspace_diagnostics,
392            workspace_discovery_ms: Some(self.workspace_discovery_ms),
393            inputs: self.inputs,
394            inputs_before_resolve: self.inputs_before_resolve,
395            duplication,
396        }
397    }
398}
399
400/// Scalar config-loading knobs for one analysis family.
401#[derive(Debug, Clone, Copy)]
402pub struct ProjectConfigOptions {
403    /// Output format the resolved config carries into rendering.
404    pub output: OutputFormat,
405    /// Bypass the parse cache for this run.
406    pub no_cache: bool,
407    /// Worker thread count recorded on the resolved config.
408    pub threads: usize,
409    /// Tri-state production override: `Some` forces production-only analysis
410    /// on or off regardless of config, `None` defers to the config value.
411    pub production_override: Option<bool>,
412    /// Suppress progress notes on stderr.
413    pub quiet: bool,
414    /// Which analysis family's per-analysis production config to flatten.
415    pub analysis: ProductionAnalysis,
416    /// Permit `extends` config inheritance from remote URLs.
417    pub allow_remote_extends: bool,
418}
419
420/// Resolved project configuration plus doctor-specific plugin diagnostics.
421#[derive(Debug)]
422#[non_exhaustive]
423pub struct ProjectConfigReadiness {
424    /// The same resolved configuration returned by [`config_for_project_analysis`].
425    pub project: ProjectConfig,
426    /// Unresolved resources named explicitly by the `plugins` config field.
427    pub configured_plugin_diagnostics: Vec<fallow_config::ConfiguredPluginDiagnostic>,
428}
429
430/// Resolve the analysis config for a project.
431///
432/// # Errors
433///
434/// Returns an error when an explicit config cannot be loaded or automatic
435/// config discovery finds an invalid config.
436pub fn config_for_project(root: &Path, config_path: Option<&Path>) -> EngineResult<ProjectConfig> {
437    config_for_project_with_load_options(root, config_path, ConfigLoadOptions::default())
438}
439
440/// Resolve project config with an explicit inheritance trust policy.
441///
442/// # Errors
443///
444/// Returns an error when config loading or validation fails.
445pub fn config_for_project_with_load_options(
446    root: &Path,
447    config_path: Option<&Path>,
448    load_options: ConfigLoadOptions,
449) -> EngineResult<ProjectConfig> {
450    config_for_project_with_production(root, config_path, load_options, ProductionFlags::default())
451}
452
453/// Resolve project config with an explicit inheritance trust policy and the
454/// production flags of the run. The flags decide the production mode before
455/// resolution, so the rules that production mode turns off are off, as with
456/// the CLI `--production` flag. The config holds the production mode of dead
457/// code. Duplication in a session of this config uses its own production mode,
458/// as `fallow dupes` does.
459///
460/// # Errors
461///
462/// Returns an error when config loading or validation fails.
463pub fn config_for_project_with_production(
464    root: &Path,
465    config_path: Option<&Path>,
466    load_options: ConfigLoadOptions,
467    production: ProductionFlags,
468) -> EngineResult<ProjectConfig> {
469    load_project_config(
470        root,
471        config_path,
472        load_options,
473        production,
474        &EnvSnapshot::capture(),
475    )
476}
477
478/// Load a project config as [`config_for_project_with_production`] does, with
479/// the environment variables of `env` in place of the process environment.
480#[cfg(test)]
481pub(crate) fn config_for_project_with_env(
482    root: &Path,
483    config_path: Option<&Path>,
484    env: &EnvSnapshot,
485) -> EngineResult<ProjectConfig> {
486    load_project_config(
487        root,
488        config_path,
489        ConfigLoadOptions::default(),
490        ProductionFlags::default(),
491        env,
492    )
493}
494
495fn load_project_config(
496    root: &Path,
497    config_path: Option<&Path>,
498    load_options: ConfigLoadOptions,
499    production: ProductionFlags,
500    env: &EnvSnapshot,
501) -> EngineResult<ProjectConfig> {
502    let file = load_config_file(
503        root,
504        config_path,
505        ConfigFileOptions {
506            allow_remote_extends: load_options.allow_remote_extends,
507        },
508    )?;
509    let options = ResolveOptions::host_default();
510    let duplication = DuplicationScope::for_dead_code_session(&file, production, options, env);
511    let ConfigFile { config, path, .. } =
512        file.for_analysis(ProductionAnalysis::DeadCode, production);
513    if path.is_some() {
514        validate_boundaries_and_rule_packs(root, &config)?;
515    }
516    Ok(mode_entry(root, config, options, env)?.into_project_config(path, duplication))
517}
518
519impl ProjectConfig {
520    /// Drop the workspace metadata of the load, so that a session built from
521    /// this config discovers the workspaces again. A caller that changes the
522    /// resolved config after the load uses this.
523    #[must_use]
524    pub fn without_workspace_metadata(mut self) -> Self {
525        self.workspaces.clear();
526        self.workspace_diagnostics.clear();
527        self.workspace_discovery_ms = None;
528        self
529    }
530}
531
532/// Resolve the parse-cache size limit for a resolved config.
533#[must_use]
534pub(crate) fn resolve_cache_max_size_bytes(config: &ResolvedConfig) -> usize {
535    config
536        .cache_max_size_mb
537        .map_or(fallow_extract::cache::DEFAULT_CACHE_MAX_SIZE, |mb| {
538            (mb as usize).saturating_mul(1024 * 1024)
539        })
540}
541
542pub(crate) fn default_project_config(root: &Path) -> ProjectConfig {
543    mode_entry_lossy(
544        root,
545        FallowConfig::default(),
546        ResolveOptions::host_default(),
547        &EnvSnapshot::capture(),
548    )
549    .into_project_config(None, DuplicationScope::SameAsSession)
550}
551
552/// Resolve config for a specific analysis without depending on the CLI crate.
553///
554/// This mirrors the CLI's core config semantics: explicit production overrides
555/// are applied before resolution, per-analysis production config is flattened
556/// for the requested analysis, and boundary / external plugin / rule-pack
557/// validation happens before the resolved config reaches the engine.
558///
559/// # Errors
560///
561/// Returns an engine error when config loading or validation fails.
562pub fn config_for_project_analysis(
563    root: &Path,
564    config_path: Option<&Path>,
565    options: ProjectConfigOptions,
566) -> EngineResult<ProjectConfig> {
567    resolve_project_config_analysis(root, config_path, options, &EnvSnapshot::capture())
568        .map(|(project, _)| project)
569}
570
571/// [`config_for_project_analysis`] with the environment variables of `env`
572/// in place of the process environment.
573#[cfg(test)]
574pub(crate) fn config_for_project_analysis_with_env(
575    root: &Path,
576    config_path: Option<&Path>,
577    options: ProjectConfigOptions,
578    env: &EnvSnapshot,
579) -> EngineResult<ProjectConfig> {
580    resolve_project_config_analysis(root, config_path, options, env).map(|(project, _)| project)
581}
582
583/// Resolve project configuration and collect typed readiness diagnostics for
584/// plugin resources named explicitly by the user configuration.
585///
586/// # Errors
587///
588/// Returns an engine error when config loading or validation fails.
589pub fn config_for_project_readiness(
590    root: &Path,
591    config_path: Option<&Path>,
592    options: ProjectConfigOptions,
593) -> EngineResult<ProjectConfigReadiness> {
594    let (project, configured_plugin_paths) =
595        resolve_project_config_analysis(root, config_path, options, &EnvSnapshot::capture())?;
596    let configured_plugin_diagnostics =
597        fallow_config::diagnose_configured_external_plugins(root, &configured_plugin_paths);
598    Ok(ProjectConfigReadiness {
599        project,
600        configured_plugin_diagnostics,
601    })
602}
603
604fn resolve_project_config_analysis(
605    root: &Path,
606    config_path: Option<&Path>,
607    options: ProjectConfigOptions,
608    env: &EnvSnapshot,
609) -> EngineResult<(ProjectConfig, Vec<String>)> {
610    let file = load_config_file(
611        root,
612        config_path,
613        ConfigFileOptions {
614            allow_remote_extends: options.allow_remote_extends,
615        },
616    )?
617    .for_analysis(
618        options.analysis,
619        ProductionFlags {
620            global: options.production_override,
621            ..ProductionFlags::default()
622        },
623    );
624    file.validate(root)?;
625    let ConfigFile { config, path, .. } = file;
626    let configured_plugin_paths = config.plugins.clone();
627    let options = ResolveOptions {
628        output: options.output,
629        threads: options.threads,
630        no_cache: options.no_cache,
631        quiet: options.quiet,
632    };
633    let entry = mode_entry(root, config, options, env)?;
634    // The caller names one analysis and owns the production mode of each
635    // other analysis, so a session of this config runs duplication only when
636    // the caller found that the modes match.
637    let project = entry.into_project_config(path, DuplicationScope::SameAsSession);
638    Ok((project, configured_plugin_paths))
639}
640
641#[cfg(test)]
642mod tests {
643    use super::*;
644    use fallow_config::EnvVar;
645
646    use crate::resolved_run::steps::apply_env_overrides_from;
647
648    fn lookup_from(vars: &[(&str, &str)]) -> EnvSnapshot {
649        EnvSnapshot::from_pairs(vars, None)
650    }
651
652    #[test]
653    fn env_overrides_reach_every_host_config() {
654        let root = Path::new("/repo");
655        let mut config = default_project_config(root).config;
656
657        apply_env_overrides_from(
658            &mut config,
659            &lookup_from(&[
660                ("FALLOW_MAX_FILE_SIZE", "7"),
661                ("FALLOW_CACHE_DIR", ".cache/fallow"),
662                ("FALLOW_CACHE_MAX_SIZE", "64"),
663            ]),
664        );
665
666        assert_eq!(
667            config.max_file_size_bytes,
668            fallow_config::resolve_max_file_size_bytes(Some(7))
669        );
670        assert_eq!(config.cache_dir, root.join(".cache/fallow"));
671        assert_eq!(config.cache_max_size_mb, Some(64));
672    }
673
674    /// `FALLOW_CACHE_MAX_SIZE` gives the same limit when a host passes it to
675    /// `resolve` and when the engine applies it after `resolve`.
676    #[test]
677    fn cache_max_size_env_gives_one_limit_before_and_after_resolve() {
678        let root = Path::new("/repo");
679        let resolve = |configured: Option<u32>, argument: Option<u32>| {
680            FallowConfig {
681                cache: fallow_config::CacheConfig {
682                    dir: None,
683                    max_size_mb: configured,
684                },
685                ..FallowConfig::default()
686            }
687            .resolve(
688                root.to_path_buf(),
689                OutputFormat::Human,
690                1,
691                false,
692                true,
693                argument,
694            )
695        };
696        let values: [&[(&str, &str)]; 5] = [
697            &[],
698            &[("FALLOW_CACHE_MAX_SIZE", "64")],
699            &[("FALLOW_CACHE_MAX_SIZE", " 8 ")],
700            &[("FALLOW_CACHE_MAX_SIZE", "0")],
701            &[("FALLOW_CACHE_MAX_SIZE", "many")],
702        ];
703        for configured in [None, Some(5)] {
704            for vars in values {
705                let argument = lookup_from(vars)
706                    .get(EnvVar::CacheMaxSize)
707                    .and_then(fallow_config::cache_max_size_from_env_value);
708                let before = resolve(configured, argument);
709                let mut after = resolve(configured, None);
710                apply_env_overrides_from(&mut after, &lookup_from(vars));
711                assert_eq!(
712                    before.cache_max_size_mb, after.cache_max_size_mb,
713                    "{configured:?} {vars:?}"
714                );
715            }
716        }
717    }
718
719    #[test]
720    fn invalid_or_empty_env_values_keep_the_config() {
721        let root = Path::new("/repo");
722        let mut config = default_project_config(root).config;
723        let before_dir = config.cache_dir.clone();
724        let before_max = config.cache_max_size_mb;
725
726        apply_env_overrides_from(
727            &mut config,
728            &lookup_from(&[("FALLOW_CACHE_DIR", ""), ("FALLOW_CACHE_MAX_SIZE", "0")]),
729        );
730
731        assert_eq!(config.cache_dir, before_dir);
732        assert_eq!(config.cache_max_size_mb, before_max);
733    }
734
735    #[test]
736    fn package_baselines_env_turns_the_map_off_only_for_a_false_value() {
737        let root = Path::new("/repo");
738        let with_map = || {
739            let mut config = default_project_config(root).config;
740            config
741                .workspace_changed_since
742                .insert("packages/web".to_owned(), "main".to_owned());
743            config
744        };
745
746        let mut disabled = with_map();
747        apply_env_overrides_from(
748            &mut disabled,
749            &lookup_from(&[("FALLOW_PACKAGE_BASELINES", " Off ")]),
750        );
751        assert!(disabled.workspace_changed_since.is_empty());
752
753        for value in ["true", "1", "maybe", ""] {
754            let mut kept = with_map();
755            apply_env_overrides_from(
756                &mut kept,
757                &lookup_from(&[("FALLOW_PACKAGE_BASELINES", value)]),
758            );
759            assert_eq!(kept.workspace_changed_since.len(), 1, "{value:?}");
760        }
761    }
762}