Skip to main content

fallow_engine/project_config/
mod.rs

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