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::{EnvSnapshot, FallowConfig, ProductionAnalysis, ResolvedConfig};
6use fallow_types::output_format::OutputFormat;
7use fallow_types::sourced::{Given, Origin};
8
9use crate::EngineResult;
10use crate::resolved_run::steps::{GivenSettings, ModeEntry, flatten_production, validate_config};
11pub(crate) use crate::resolved_run::steps::{collect_workspace_metadata, resolve_with_env_from};
12use crate::resolved_run::{PerAnalysis, ProductionInputs, decide_production};
13
14#[cfg(any(test, feature = "testing"))]
15mod direct_load;
16mod loader;
17
18#[cfg(any(test, feature = "testing"))]
19pub(crate) use direct_load::default_project_config;
20#[cfg(test)]
21pub(crate) use direct_load::{
22    ProjectConfigOptions, config_for_project_analysis, config_for_project_analysis_with_env,
23    config_for_project_with_env,
24};
25#[cfg(any(test, feature = "testing"))]
26pub use direct_load::{
27    config_for_project, config_for_project_with_load_options, config_for_project_with_production,
28};
29
30#[cfg(any(test, feature = "testing"))]
31pub use loader::load_count;
32pub use loader::{
33    ConfigChainSnapshot, ConfigFile, ConfigFileOptions, ConfigLoadError, find_config_file,
34    load_config_file,
35};
36
37/// The production flags of a config load without a resolved run: the global
38/// `--production` override and one override per analysis
39/// (`--production-dead-code`, `--production-health`, `--production-dupes`).
40///
41/// The precedence is the precedence of the resolver without environment
42/// variables: the flag of the analysis, then the global override, then the
43/// config. A run of a surface decides the production mode in
44/// [`crate::resolved_run`]; these flags serve the loads of
45/// [`ConfigFile::for_analysis`] that have no run.
46#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
47pub struct ProductionFlags {
48    /// The global override. The CLI sets `Some(true)` for `--production` and
49    /// `None` without it. The programmatic API can also pass `Some(false)`.
50    pub global: Option<bool>,
51    /// Override for the dead-code analysis.
52    pub dead_code: Option<bool>,
53    /// Override for the health analysis.
54    pub health: Option<bool>,
55    /// Override for the duplication analysis.
56    pub dupes: Option<bool>,
57}
58
59impl ProductionFlags {
60    /// The flags of a CLI run, where `--production` can only switch the mode
61    /// on.
62    #[must_use]
63    pub const fn from_cli(
64        production: bool,
65        dead_code: Option<bool>,
66        health: Option<bool>,
67        dupes: Option<bool>,
68    ) -> Self {
69        Self {
70            global: if production { Some(true) } else { None },
71            dead_code,
72            health,
73            dupes,
74        }
75    }
76
77    /// The production override of a command that runs one analysis
78    /// (`dead-code`, `dupes`, `health`): its own override, else
79    /// `--production`. `None` means that the config decides.
80    #[must_use]
81    pub const fn single_analysis_override(production: bool, own: Option<bool>) -> Option<bool> {
82        Self::from_cli(production, own, None, None).override_for(ProductionAnalysis::DeadCode)
83    }
84
85    /// The override flag of one analysis, without the global override.
86    #[must_use]
87    const fn own(self, analysis: ProductionAnalysis) -> Option<bool> {
88        match analysis {
89            ProductionAnalysis::DeadCode => self.dead_code,
90            ProductionAnalysis::Health => self.health,
91            ProductionAnalysis::Dupes => self.dupes,
92        }
93    }
94
95    /// The production override of one analysis: its own flag, else the global
96    /// override. `None` means that the config decides.
97    #[must_use]
98    pub const fn override_for(self, analysis: ProductionAnalysis) -> Option<bool> {
99        match self.own(analysis) {
100            Some(value) => Some(value),
101            None => self.global,
102        }
103    }
104
105    /// The production mode of one analysis as far as the flags decide, before
106    /// the config is loaded. A missing flag reads as `false`.
107    #[must_use]
108    pub const fn mode(self, analysis: ProductionAnalysis) -> bool {
109        match self.override_for(analysis) {
110            Some(value) => value,
111            None => false,
112        }
113    }
114
115    /// The production mode of each analysis as far as the flags decide.
116    #[must_use]
117    pub const fn modes(self) -> ProductionModes {
118        ProductionModes {
119            dead_code: self.mode(ProductionAnalysis::DeadCode),
120            health: self.mode(ProductionAnalysis::Health),
121            dupes: self.mode(ProductionAnalysis::Dupes),
122        }
123    }
124
125    /// The effective production mode of one analysis: the flags first, then
126    /// the `production` setting of the config.
127    #[must_use]
128    pub fn effective(
129        self,
130        analysis: ProductionAnalysis,
131        config: &fallow_config::ProductionConfig,
132    ) -> bool {
133        *decide_production(&self.as_inputs(), config, None)
134            .get(analysis)
135            .value()
136    }
137
138    /// The effective production mode of each analysis.
139    #[cfg(test)]
140    #[must_use]
141    pub(crate) fn effective_modes(
142        self,
143        config: &fallow_config::ProductionConfig,
144    ) -> ProductionModes {
145        let decided = decide_production(&self.as_inputs(), config, None);
146        ProductionModes {
147            dead_code: decided.dead_code.into_value(),
148            health: decided.health.into_value(),
149            dupes: decided.dupes.into_value(),
150        }
151    }
152
153    /// The override of each analysis from `self`, else from `fallback`. The
154    /// parity tests use it to put the flags before the environment
155    /// variables. The config decides only when neither source sets a
156    /// value. `fallback` has the rank of the environment variables in
157    /// `decide_production`.
158    #[cfg(test)]
159    #[must_use]
160    pub(crate) fn with_fallback(self, fallback: Self) -> Self {
161        use fallow_types::sourced::{Layer, Sourced};
162
163        let inputs = ProductionInputs {
164            global_env: fallback.global,
165            own_env: PerAnalysis {
166                dead_code: fallback.dead_code,
167                health: fallback.health,
168                dupes: fallback.dupes,
169            },
170            ..self.as_inputs()
171        };
172        let decided = decide_production(&inputs, &fallow_config::ProductionConfig::default(), None);
173        let given = |decision: &Sourced<bool>| {
174            (decision.source().layer() != Layer::Default).then_some(*decision.value())
175        };
176        Self {
177            global: None,
178            dead_code: given(&decided.dead_code),
179            health: given(&decided.health),
180            dupes: given(&decided.dupes),
181        }
182    }
183
184    /// The flags as caller-given production inputs, without environment
185    /// variables.
186    fn as_inputs(self) -> ProductionInputs {
187        let given = |value: Option<bool>, name| {
188            value.map(|value| Given {
189                value,
190                origin: Origin::ApiOption(name),
191            })
192        };
193        ProductionInputs {
194            global_flag: given(self.global, "ProductionFlags.global"),
195            own_flag: PerAnalysis {
196                dead_code: given(self.dead_code, "ProductionFlags.dead_code"),
197                health: given(self.health, "ProductionFlags.health"),
198                dupes: given(self.dupes, "ProductionFlags.dupes"),
199            },
200            global_env: None,
201            own_env: PerAnalysis::default(),
202        }
203    }
204}
205
206/// The production mode of each analysis of one run.
207#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
208pub struct ProductionModes {
209    /// Production mode of the dead-code analysis.
210    pub dead_code: bool,
211    /// Production mode of the health analysis.
212    pub health: bool,
213    /// Production mode of the duplication analysis.
214    pub dupes: bool,
215}
216
217impl ProductionModes {
218    /// The production mode of one analysis.
219    #[must_use]
220    pub const fn for_analysis(self, analysis: ProductionAnalysis) -> bool {
221        match analysis {
222            ProductionAnalysis::DeadCode => self.dead_code,
223            ProductionAnalysis::Health => self.health,
224            ProductionAnalysis::Dupes => self.dupes,
225        }
226    }
227
228    /// Whether health can reuse the dead-code parse: both run in the same mode.
229    #[must_use]
230    pub const fn dead_code_matches_health(self) -> bool {
231        self.dead_code == self.health
232    }
233
234    /// Whether duplication can reuse the dead-code files: both run in the same
235    /// mode.
236    #[must_use]
237    pub const fn dead_code_matches_dupes(self) -> bool {
238        self.dead_code == self.dupes
239    }
240
241    /// Whether all three analyses run in the same mode.
242    #[must_use]
243    pub const fn all_match(self) -> bool {
244        self.dead_code_matches_health() && self.dead_code_matches_dupes()
245    }
246}
247
248/// The resolved config of one mode entry, with the config file path and the
249/// workspace metadata of the load. A session holds it. Outside this crate
250/// only tests and benchmarks (feature `testing`) see the type.
251mod project {
252    use std::path::PathBuf;
253
254    use fallow_config::{ResolvedConfig, WorkspaceDiagnostic, WorkspaceInfo};
255
256    use super::DuplicationScope;
257
258    /// Resolved project config plus the config file path when one was loaded.
259    #[derive(Debug)]
260    pub struct ProjectConfig {
261        /// Fully resolved config for the project.
262        pub config: ResolvedConfig,
263        /// Path of the loaded config file; `None` when defaults were used.
264        pub path: Option<PathBuf>,
265        /// Workspace metadata discovered under the project root.
266        pub workspaces: Vec<WorkspaceInfo>,
267        /// Diagnostics from workspace discovery (undeclared or invalid members).
268        pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
269        /// Workspace discovery wall time in milliseconds, when measured.
270        pub(crate) workspace_discovery_ms: Option<f64>,
271        /// The plugin files, rule packs and `autoDiscover` directories that
272        /// config resolution read.
273        pub inputs: fallow_config::ConfigInputs,
274        /// The content of [`Self::inputs`] just before resolution read them.
275        pub(crate) inputs_before_resolve: fallow_config::ConfigInputsSnapshot,
276        /// The files that duplication analyzes.
277        pub(crate) duplication: DuplicationScope,
278    }
279}
280
281#[cfg(any(test, feature = "testing"))]
282pub use project::ProjectConfig;
283#[cfg(not(any(test, feature = "testing")))]
284pub(crate) use project::ProjectConfig;
285
286/// The files that duplication analyzes.
287#[derive(Debug, Clone)]
288pub(crate) enum DuplicationScope {
289    /// The production mode of duplication equals the mode of the session
290    /// config, so duplication analyzes the files of the session.
291    SameAsSession,
292    /// The production mode of duplication differs from the mode of the
293    /// session config. The session resolves this config, which has the
294    /// `production` setting of duplication, and walks its files on the first
295    /// duplication call.
296    Own {
297        config: Box<FallowConfig>,
298        options: ResolveOptions,
299        env: Box<EnvSnapshot>,
300        /// The settings that win over `env`. The session writes them on the
301        /// config after it resolves the config with `env`.
302        given: Box<GivenSettings>,
303    },
304}
305
306/// The run settings that resolution records on the config.
307#[derive(Debug, Clone, Copy)]
308pub struct ResolveOptions {
309    /// Output format the resolved config carries into rendering.
310    pub output: OutputFormat,
311    /// Worker thread count recorded on the resolved config.
312    pub threads: usize,
313    /// Bypass the parse cache for this run.
314    pub no_cache: bool,
315    /// Suppress progress notes on stderr.
316    pub quiet: bool,
317}
318
319impl ConfigFile {
320    /// Flatten the `production` setting of the config for one analysis: the
321    /// flags decide first, then the config. A project without a config file
322    /// gets the mode of the flags.
323    #[must_use]
324    pub fn for_analysis(mut self, analysis: ProductionAnalysis, flags: ProductionFlags) -> Self {
325        let from_file = self.path.is_some();
326        let on = if from_file {
327            flags.effective(analysis, &self.config.production)
328        } else {
329            flags.mode(analysis)
330        };
331        flatten_production(&mut self.config, from_file, on);
332        self
333    }
334
335    /// Validate the external plugins, the boundaries and the rule packs of
336    /// the config.
337    ///
338    /// # Errors
339    ///
340    /// Returns an error that names the first invalid part and lists each of
341    /// its problems.
342    pub fn validate(&self, root: &Path) -> EngineResult<()> {
343        validate_config(root, &self.config)
344    }
345
346    /// Resolve the config for `root`, then apply the environment variables
347    /// that every host honors.
348    #[must_use]
349    pub fn resolve(self, root: &Path, options: ResolveOptions) -> ResolvedConfig {
350        resolve_with_env(self.config, root, options)
351    }
352}
353
354fn resolve_with_env(config: FallowConfig, root: &Path, options: ResolveOptions) -> ResolvedConfig {
355    resolve_with_env_from(config, root, options, &EnvSnapshot::capture())
356}
357
358impl ModeEntry {
359    /// The project config of this mode entry.
360    pub(crate) fn into_project_config(
361        self,
362        path: Option<PathBuf>,
363        duplication: DuplicationScope,
364    ) -> ProjectConfig {
365        ProjectConfig {
366            config: self.config,
367            path,
368            workspaces: self.workspaces,
369            workspace_diagnostics: self.workspace_diagnostics,
370            workspace_discovery_ms: Some(self.workspace_discovery_ms),
371            inputs: self.inputs,
372            inputs_before_resolve: self.inputs_before_resolve,
373            duplication,
374        }
375    }
376}
377
378/// Resolve the parse-cache size limit for a resolved config.
379#[must_use]
380pub(crate) fn resolve_cache_max_size_bytes(config: &ResolvedConfig) -> usize {
381    config
382        .cache_max_size_mb
383        .map_or(fallow_extract::cache::DEFAULT_CACHE_MAX_SIZE, |mb| {
384            (mb as usize).saturating_mul(1024 * 1024)
385        })
386}
387
388#[cfg(test)]
389mod tests {
390    use super::*;
391    use fallow_config::EnvVar;
392
393    use crate::resolved_run::steps::apply_env_overrides_from;
394
395    fn lookup_from(vars: &[(&str, &str)]) -> EnvSnapshot {
396        EnvSnapshot::from_pairs(vars, None)
397    }
398
399    #[test]
400    fn env_overrides_reach_every_host_config() {
401        let root = Path::new("/repo");
402        let mut config = default_project_config(root).config;
403
404        apply_env_overrides_from(
405            &mut config,
406            &lookup_from(&[
407                ("FALLOW_MAX_FILE_SIZE", "7"),
408                ("FALLOW_CACHE_DIR", ".cache/fallow"),
409                ("FALLOW_CACHE_MAX_SIZE", "64"),
410            ]),
411        );
412
413        assert_eq!(
414            config.max_file_size_bytes,
415            fallow_config::resolve_max_file_size_bytes(Some(7))
416        );
417        assert_eq!(config.cache_dir, root.join(".cache/fallow"));
418        assert_eq!(config.cache_max_size_mb, Some(64));
419    }
420
421    /// `FALLOW_CACHE_MAX_SIZE` gives the same limit when a host passes it to
422    /// `resolve` and when the engine applies it after `resolve`.
423    #[test]
424    fn cache_max_size_env_gives_one_limit_before_and_after_resolve() {
425        let root = Path::new("/repo");
426        let resolve = |configured: Option<u32>, argument: Option<u32>| {
427            FallowConfig {
428                cache: fallow_config::CacheConfig {
429                    dir: None,
430                    max_size_mb: configured,
431                },
432                ..FallowConfig::default()
433            }
434            .resolve(
435                root.to_path_buf(),
436                OutputFormat::Human,
437                1,
438                false,
439                true,
440                argument,
441            )
442        };
443        let values: [&[(&str, &str)]; 5] = [
444            &[],
445            &[("FALLOW_CACHE_MAX_SIZE", "64")],
446            &[("FALLOW_CACHE_MAX_SIZE", " 8 ")],
447            &[("FALLOW_CACHE_MAX_SIZE", "0")],
448            &[("FALLOW_CACHE_MAX_SIZE", "many")],
449        ];
450        for configured in [None, Some(5)] {
451            for vars in values {
452                let argument = lookup_from(vars)
453                    .get(EnvVar::CacheMaxSize)
454                    .and_then(fallow_config::cache_max_size_from_env_value);
455                let before = resolve(configured, argument);
456                let mut after = resolve(configured, None);
457                apply_env_overrides_from(&mut after, &lookup_from(vars));
458                assert_eq!(
459                    before.cache_max_size_mb, after.cache_max_size_mb,
460                    "{configured:?} {vars:?}"
461                );
462            }
463        }
464    }
465
466    #[test]
467    fn invalid_or_empty_env_values_keep_the_config() {
468        let root = Path::new("/repo");
469        let mut config = default_project_config(root).config;
470        let before_dir = config.cache_dir.clone();
471        let before_max = config.cache_max_size_mb;
472
473        apply_env_overrides_from(
474            &mut config,
475            &lookup_from(&[("FALLOW_CACHE_DIR", ""), ("FALLOW_CACHE_MAX_SIZE", "0")]),
476        );
477
478        assert_eq!(config.cache_dir, before_dir);
479        assert_eq!(config.cache_max_size_mb, before_max);
480    }
481
482    #[test]
483    fn package_baselines_env_turns_the_map_off_only_for_a_false_value() {
484        let root = Path::new("/repo");
485        let with_map = || {
486            let mut config = default_project_config(root).config;
487            config
488                .workspace_changed_since
489                .insert("packages/web".to_owned(), "main".to_owned());
490            config
491        };
492
493        let mut disabled = with_map();
494        apply_env_overrides_from(
495            &mut disabled,
496            &lookup_from(&[("FALLOW_PACKAGE_BASELINES", " Off ")]),
497        );
498        assert!(disabled.workspace_changed_since.is_empty());
499
500        for value in ["true", "1", "maybe", ""] {
501            let mut kept = with_map();
502            apply_env_overrides_from(
503                &mut kept,
504                &lookup_from(&[("FALLOW_PACKAGE_BASELINES", value)]),
505            );
506            assert_eq!(kept.workspace_changed_since.len(), 1, "{value:?}");
507        }
508    }
509}