1use 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
38pub struct ProductionFlags {
39 pub global: Option<bool>,
42 pub dead_code: Option<bool>,
44 pub health: Option<bool>,
46 pub dupes: Option<bool>,
48}
49
50impl ProductionFlags {
51 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
199pub struct ProductionModes {
200 pub dead_code: bool,
202 pub health: bool,
204 pub dupes: bool,
206}
207
208impl ProductionModes {
209 #[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 #[must_use]
221 pub const fn dead_code_matches_health(self) -> bool {
222 self.dead_code == self.health
223 }
224
225 #[must_use]
228 pub const fn dead_code_matches_dupes(self) -> bool {
229 self.dead_code == self.dupes
230 }
231
232 #[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#[derive(Debug)]
241pub struct ProjectConfig {
242 pub config: ResolvedConfig,
244 pub path: Option<PathBuf>,
246 pub workspaces: Vec<WorkspaceInfo>,
248 pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
250 pub(crate) workspace_discovery_ms: Option<f64>,
252 pub inputs: fallow_config::ConfigInputs,
255 pub(crate) inputs_before_resolve: fallow_config::ConfigInputsSnapshot,
257 pub(crate) duplication: DuplicationScope,
259}
260
261#[derive(Debug, Clone)]
263pub(crate) enum DuplicationScope {
264 SameAsSession,
267 Own {
272 config: Box<FallowConfig>,
273 options: ResolveOptions,
274 env: Box<EnvSnapshot>,
275 given: Box<GivenSettings>,
278 },
279}
280
281impl DuplicationScope {
282 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#[derive(Debug, Clone, Copy)]
318pub struct ResolveOptions {
319 pub output: OutputFormat,
321 pub threads: usize,
323 pub no_cache: bool,
325 pub quiet: bool,
327}
328
329impl ResolveOptions {
330 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 #[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 pub fn validate(&self, root: &Path) -> EngineResult<()> {
365 validate_config(root, &self.config)
366 }
367
368 #[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 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#[derive(Debug, Clone, Copy)]
402pub struct ProjectConfigOptions {
403 pub output: OutputFormat,
405 pub no_cache: bool,
407 pub threads: usize,
409 pub production_override: Option<bool>,
412 pub quiet: bool,
414 pub analysis: ProductionAnalysis,
416 pub allow_remote_extends: bool,
418}
419
420#[derive(Debug)]
422#[non_exhaustive]
423pub struct ProjectConfigReadiness {
424 pub project: ProjectConfig,
426 pub configured_plugin_diagnostics: Vec<fallow_config::ConfiguredPluginDiagnostic>,
428}
429
430pub 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
440pub 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
453pub 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#[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 #[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#[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
552pub 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#[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
583pub 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 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 #[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}