1use 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
28pub struct ProductionFlags {
29 pub global: Option<bool>,
32 pub dead_code: Option<bool>,
34 pub health: Option<bool>,
36 pub dupes: Option<bool>,
38}
39
40impl ProductionFlags {
41 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
155pub struct ProductionModes {
156 pub dead_code: bool,
158 pub health: bool,
160 pub dupes: bool,
162}
163
164impl ProductionModes {
165 #[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 #[must_use]
177 pub const fn dead_code_matches_health(self) -> bool {
178 self.dead_code == self.health
179 }
180
181 #[must_use]
184 pub const fn dead_code_matches_dupes(self) -> bool {
185 self.dead_code == self.dupes
186 }
187
188 #[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#[derive(Debug)]
197pub struct ProjectConfig {
198 pub config: ResolvedConfig,
200 pub path: Option<PathBuf>,
202 pub workspaces: Vec<WorkspaceInfo>,
204 pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
206 pub workspace_discovery_ms: Option<f64>,
208 pub inputs: fallow_config::ConfigInputs,
211 pub inputs_before_resolve: fallow_config::ConfigInputsSnapshot,
213}
214
215#[derive(Debug, Clone, Copy)]
217pub struct ResolveOptions {
218 pub output: OutputFormat,
220 pub threads: usize,
222 pub no_cache: bool,
224 pub quiet: bool,
226}
227
228impl ResolveOptions {
229 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 #[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 pub fn validate(&self, root: &Path) -> EngineResult<()> {
264 validate_config(root, &self.config)
265 }
266
267 #[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#[derive(Debug, Clone, Copy)]
290pub struct ProjectConfigOptions {
291 pub output: OutputFormat,
293 pub no_cache: bool,
295 pub threads: usize,
297 pub production_override: Option<bool>,
300 pub quiet: bool,
302 pub analysis: ProductionAnalysis,
304 pub allow_remote_extends: bool,
306}
307
308#[derive(Debug)]
310#[non_exhaustive]
311pub struct ProjectConfigReadiness {
312 pub project: ProjectConfig,
314 pub configured_plugin_diagnostics: Vec<fallow_config::ConfiguredPluginDiagnostic>,
316}
317
318pub 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
328pub 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
341pub 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 #[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#[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
426pub 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
444pub 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
515fn 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 #[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}