1use 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
47pub struct ProductionFlags {
48 pub global: Option<bool>,
51 pub dead_code: Option<bool>,
53 pub health: Option<bool>,
55 pub dupes: Option<bool>,
57}
58
59impl ProductionFlags {
60 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
208pub struct ProductionModes {
209 pub dead_code: bool,
211 pub health: bool,
213 pub dupes: bool,
215}
216
217impl ProductionModes {
218 #[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 #[must_use]
230 pub const fn dead_code_matches_health(self) -> bool {
231 self.dead_code == self.health
232 }
233
234 #[must_use]
237 pub const fn dead_code_matches_dupes(self) -> bool {
238 self.dead_code == self.dupes
239 }
240
241 #[must_use]
243 pub const fn all_match(self) -> bool {
244 self.dead_code_matches_health() && self.dead_code_matches_dupes()
245 }
246}
247
248mod project {
252 use std::path::PathBuf;
253
254 use fallow_config::{ResolvedConfig, WorkspaceDiagnostic, WorkspaceInfo};
255
256 use super::DuplicationScope;
257
258 #[derive(Debug)]
260 pub struct ProjectConfig {
261 pub config: ResolvedConfig,
263 pub path: Option<PathBuf>,
265 pub workspaces: Vec<WorkspaceInfo>,
267 pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
269 pub(crate) workspace_discovery_ms: Option<f64>,
271 pub inputs: fallow_config::ConfigInputs,
274 pub(crate) inputs_before_resolve: fallow_config::ConfigInputsSnapshot,
276 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#[derive(Debug, Clone)]
288pub(crate) enum DuplicationScope {
289 SameAsSession,
292 Own {
297 config: Box<FallowConfig>,
298 options: ResolveOptions,
299 env: Box<EnvSnapshot>,
300 given: Box<GivenSettings>,
303 },
304}
305
306#[derive(Debug, Clone, Copy)]
308pub struct ResolveOptions {
309 pub output: OutputFormat,
311 pub threads: usize,
313 pub no_cache: bool,
315 pub quiet: bool,
317}
318
319impl ConfigFile {
320 #[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 pub fn validate(&self, root: &Path) -> EngineResult<()> {
343 validate_config(root, &self.config)
344 }
345
346 #[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 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#[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 #[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}