use std::path::{Path, PathBuf};
use fallow_config::{
ConfigLoadOptions, EnvSnapshot, FallowConfig, ProductionAnalysis, ResolvedConfig,
WorkspaceDiagnostic, WorkspaceInfo,
};
use fallow_types::output_format::OutputFormat;
use fallow_types::sourced::{Given, Origin};
use crate::EngineResult;
use crate::resolved_run::steps::{
GivenSettings, ModeEntry, flatten_production, mode_entry, mode_entry_lossy,
validate_boundaries_and_rule_packs, validate_config,
};
pub(crate) use crate::resolved_run::steps::{collect_workspace_metadata, resolve_with_env_from};
use crate::resolved_run::{PerAnalysis, ProductionInputs, decide_production};
mod loader;
#[cfg(any(test, feature = "testing"))]
pub use loader::load_count;
pub use loader::{
ConfigChainSnapshot, ConfigFile, ConfigFileOptions, ConfigLoadError, find_config_file,
load_config_file,
};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ProductionFlags {
pub global: Option<bool>,
pub dead_code: Option<bool>,
pub health: Option<bool>,
pub dupes: Option<bool>,
}
impl ProductionFlags {
#[must_use]
pub const fn from_cli(
production: bool,
dead_code: Option<bool>,
health: Option<bool>,
dupes: Option<bool>,
) -> Self {
Self {
global: if production { Some(true) } else { None },
dead_code,
health,
dupes,
}
}
#[must_use]
pub const fn single_analysis_override(production: bool, own: Option<bool>) -> Option<bool> {
Self::from_cli(production, own, None, None).override_for(ProductionAnalysis::DeadCode)
}
#[must_use]
const fn own(self, analysis: ProductionAnalysis) -> Option<bool> {
match analysis {
ProductionAnalysis::DeadCode => self.dead_code,
ProductionAnalysis::Health => self.health,
ProductionAnalysis::Dupes => self.dupes,
}
}
#[must_use]
pub const fn override_for(self, analysis: ProductionAnalysis) -> Option<bool> {
match self.own(analysis) {
Some(value) => Some(value),
None => self.global,
}
}
#[must_use]
pub const fn mode(self, analysis: ProductionAnalysis) -> bool {
match self.override_for(analysis) {
Some(value) => value,
None => false,
}
}
#[must_use]
pub const fn modes(self) -> ProductionModes {
ProductionModes {
dead_code: self.mode(ProductionAnalysis::DeadCode),
health: self.mode(ProductionAnalysis::Health),
dupes: self.mode(ProductionAnalysis::Dupes),
}
}
#[must_use]
pub fn effective(
self,
analysis: ProductionAnalysis,
config: &fallow_config::ProductionConfig,
) -> bool {
*decide_production(&self.as_inputs(), config, None)
.get(analysis)
.value()
}
#[cfg(test)]
#[must_use]
pub(crate) fn effective_modes(
self,
config: &fallow_config::ProductionConfig,
) -> ProductionModes {
let decided = decide_production(&self.as_inputs(), config, None);
ProductionModes {
dead_code: decided.dead_code.into_value(),
health: decided.health.into_value(),
dupes: decided.dupes.into_value(),
}
}
#[cfg(test)]
#[must_use]
pub(crate) fn with_fallback(self, fallback: Self) -> Self {
use fallow_types::sourced::{Layer, Sourced};
let inputs = ProductionInputs {
global_env: fallback.global,
own_env: PerAnalysis {
dead_code: fallback.dead_code,
health: fallback.health,
dupes: fallback.dupes,
},
..self.as_inputs()
};
let decided = decide_production(&inputs, &fallow_config::ProductionConfig::default(), None);
let given = |decision: &Sourced<bool>| {
(decision.source().layer() != Layer::Default).then_some(*decision.value())
};
Self {
global: None,
dead_code: given(&decided.dead_code),
health: given(&decided.health),
dupes: given(&decided.dupes),
}
}
fn as_inputs(self) -> ProductionInputs {
let given = |value: Option<bool>, name| {
value.map(|value| Given {
value,
origin: Origin::ApiOption(name),
})
};
ProductionInputs {
global_flag: given(self.global, "ProductionFlags.global"),
own_flag: PerAnalysis {
dead_code: given(self.dead_code, "ProductionFlags.dead_code"),
health: given(self.health, "ProductionFlags.health"),
dupes: given(self.dupes, "ProductionFlags.dupes"),
},
global_env: None,
own_env: PerAnalysis::default(),
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ProductionModes {
pub dead_code: bool,
pub health: bool,
pub dupes: bool,
}
impl ProductionModes {
#[must_use]
pub const fn for_analysis(self, analysis: ProductionAnalysis) -> bool {
match analysis {
ProductionAnalysis::DeadCode => self.dead_code,
ProductionAnalysis::Health => self.health,
ProductionAnalysis::Dupes => self.dupes,
}
}
#[must_use]
pub const fn dead_code_matches_health(self) -> bool {
self.dead_code == self.health
}
#[must_use]
pub const fn dead_code_matches_dupes(self) -> bool {
self.dead_code == self.dupes
}
#[must_use]
pub const fn all_match(self) -> bool {
self.dead_code_matches_health() && self.dead_code_matches_dupes()
}
}
#[derive(Debug)]
pub struct ProjectConfig {
pub config: ResolvedConfig,
pub path: Option<PathBuf>,
pub workspaces: Vec<WorkspaceInfo>,
pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
pub(crate) workspace_discovery_ms: Option<f64>,
pub inputs: fallow_config::ConfigInputs,
pub(crate) inputs_before_resolve: fallow_config::ConfigInputsSnapshot,
pub(crate) duplication: DuplicationScope,
}
#[derive(Debug, Clone)]
pub(crate) enum DuplicationScope {
SameAsSession,
Own {
config: Box<FallowConfig>,
options: ResolveOptions,
env: Box<EnvSnapshot>,
given: Box<GivenSettings>,
},
}
impl DuplicationScope {
fn for_dead_code_session(
file: &ConfigFile,
flags: ProductionFlags,
options: ResolveOptions,
env: &EnvSnapshot,
) -> Self {
let mode = |analysis| {
if file.path.is_some() {
flags.effective(analysis, &file.config.production)
} else {
flags.mode(analysis)
}
};
if mode(ProductionAnalysis::Dupes) == mode(ProductionAnalysis::DeadCode) {
return Self::SameAsSession;
}
let dupes = ConfigFile {
config: file.config.clone(),
path: file.path.clone(),
chain: file.chain.clone(),
}
.for_analysis(ProductionAnalysis::Dupes, flags);
Self::Own {
config: Box::new(dupes.config),
options,
env: Box::new(env.clone()),
given: Box::default(),
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct ResolveOptions {
pub output: OutputFormat,
pub threads: usize,
pub no_cache: bool,
pub quiet: bool,
}
impl ResolveOptions {
fn host_default() -> Self {
Self {
output: OutputFormat::Human,
threads: std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get),
no_cache: false,
quiet: true,
}
}
}
impl ConfigFile {
#[must_use]
pub fn for_analysis(mut self, analysis: ProductionAnalysis, flags: ProductionFlags) -> Self {
let from_file = self.path.is_some();
let on = if from_file {
flags.effective(analysis, &self.config.production)
} else {
flags.mode(analysis)
};
flatten_production(&mut self.config, from_file, on);
self
}
pub fn validate(&self, root: &Path) -> EngineResult<()> {
validate_config(root, &self.config)
}
#[must_use]
pub fn resolve(self, root: &Path, options: ResolveOptions) -> ResolvedConfig {
resolve_with_env(self.config, root, options)
}
}
fn resolve_with_env(config: FallowConfig, root: &Path, options: ResolveOptions) -> ResolvedConfig {
resolve_with_env_from(config, root, options, &EnvSnapshot::capture())
}
impl ModeEntry {
pub(crate) fn into_project_config(
self,
path: Option<PathBuf>,
duplication: DuplicationScope,
) -> ProjectConfig {
ProjectConfig {
config: self.config,
path,
workspaces: self.workspaces,
workspace_diagnostics: self.workspace_diagnostics,
workspace_discovery_ms: Some(self.workspace_discovery_ms),
inputs: self.inputs,
inputs_before_resolve: self.inputs_before_resolve,
duplication,
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct ProjectConfigOptions {
pub output: OutputFormat,
pub no_cache: bool,
pub threads: usize,
pub production_override: Option<bool>,
pub quiet: bool,
pub analysis: ProductionAnalysis,
pub allow_remote_extends: bool,
}
#[derive(Debug)]
#[non_exhaustive]
pub struct ProjectConfigReadiness {
pub project: ProjectConfig,
pub configured_plugin_diagnostics: Vec<fallow_config::ConfiguredPluginDiagnostic>,
}
pub fn config_for_project(root: &Path, config_path: Option<&Path>) -> EngineResult<ProjectConfig> {
config_for_project_with_load_options(root, config_path, ConfigLoadOptions::default())
}
pub fn config_for_project_with_load_options(
root: &Path,
config_path: Option<&Path>,
load_options: ConfigLoadOptions,
) -> EngineResult<ProjectConfig> {
config_for_project_with_production(root, config_path, load_options, ProductionFlags::default())
}
pub fn config_for_project_with_production(
root: &Path,
config_path: Option<&Path>,
load_options: ConfigLoadOptions,
production: ProductionFlags,
) -> EngineResult<ProjectConfig> {
load_project_config(
root,
config_path,
load_options,
production,
&EnvSnapshot::capture(),
)
}
#[cfg(test)]
pub(crate) fn config_for_project_with_env(
root: &Path,
config_path: Option<&Path>,
env: &EnvSnapshot,
) -> EngineResult<ProjectConfig> {
load_project_config(
root,
config_path,
ConfigLoadOptions::default(),
ProductionFlags::default(),
env,
)
}
fn load_project_config(
root: &Path,
config_path: Option<&Path>,
load_options: ConfigLoadOptions,
production: ProductionFlags,
env: &EnvSnapshot,
) -> EngineResult<ProjectConfig> {
let file = load_config_file(
root,
config_path,
ConfigFileOptions {
allow_remote_extends: load_options.allow_remote_extends,
},
)?;
let options = ResolveOptions::host_default();
let duplication = DuplicationScope::for_dead_code_session(&file, production, options, env);
let ConfigFile { config, path, .. } =
file.for_analysis(ProductionAnalysis::DeadCode, production);
if path.is_some() {
validate_boundaries_and_rule_packs(root, &config)?;
}
Ok(mode_entry(root, config, options, env)?.into_project_config(path, duplication))
}
impl ProjectConfig {
#[must_use]
pub fn without_workspace_metadata(mut self) -> Self {
self.workspaces.clear();
self.workspace_diagnostics.clear();
self.workspace_discovery_ms = None;
self
}
}
#[must_use]
pub(crate) fn resolve_cache_max_size_bytes(config: &ResolvedConfig) -> usize {
config
.cache_max_size_mb
.map_or(fallow_extract::cache::DEFAULT_CACHE_MAX_SIZE, |mb| {
(mb as usize).saturating_mul(1024 * 1024)
})
}
pub(crate) fn default_project_config(root: &Path) -> ProjectConfig {
mode_entry_lossy(
root,
FallowConfig::default(),
ResolveOptions::host_default(),
&EnvSnapshot::capture(),
)
.into_project_config(None, DuplicationScope::SameAsSession)
}
pub fn config_for_project_analysis(
root: &Path,
config_path: Option<&Path>,
options: ProjectConfigOptions,
) -> EngineResult<ProjectConfig> {
resolve_project_config_analysis(root, config_path, options, &EnvSnapshot::capture())
.map(|(project, _)| project)
}
#[cfg(test)]
pub(crate) fn config_for_project_analysis_with_env(
root: &Path,
config_path: Option<&Path>,
options: ProjectConfigOptions,
env: &EnvSnapshot,
) -> EngineResult<ProjectConfig> {
resolve_project_config_analysis(root, config_path, options, env).map(|(project, _)| project)
}
pub fn config_for_project_readiness(
root: &Path,
config_path: Option<&Path>,
options: ProjectConfigOptions,
) -> EngineResult<ProjectConfigReadiness> {
let (project, configured_plugin_paths) =
resolve_project_config_analysis(root, config_path, options, &EnvSnapshot::capture())?;
let configured_plugin_diagnostics =
fallow_config::diagnose_configured_external_plugins(root, &configured_plugin_paths);
Ok(ProjectConfigReadiness {
project,
configured_plugin_diagnostics,
})
}
fn resolve_project_config_analysis(
root: &Path,
config_path: Option<&Path>,
options: ProjectConfigOptions,
env: &EnvSnapshot,
) -> EngineResult<(ProjectConfig, Vec<String>)> {
let file = load_config_file(
root,
config_path,
ConfigFileOptions {
allow_remote_extends: options.allow_remote_extends,
},
)?
.for_analysis(
options.analysis,
ProductionFlags {
global: options.production_override,
..ProductionFlags::default()
},
);
file.validate(root)?;
let ConfigFile { config, path, .. } = file;
let configured_plugin_paths = config.plugins.clone();
let options = ResolveOptions {
output: options.output,
threads: options.threads,
no_cache: options.no_cache,
quiet: options.quiet,
};
let entry = mode_entry(root, config, options, env)?;
let project = entry.into_project_config(path, DuplicationScope::SameAsSession);
Ok((project, configured_plugin_paths))
}
#[cfg(test)]
mod tests {
use super::*;
use fallow_config::EnvVar;
use crate::resolved_run::steps::apply_env_overrides_from;
fn lookup_from(vars: &[(&str, &str)]) -> EnvSnapshot {
EnvSnapshot::from_pairs(vars, None)
}
#[test]
fn env_overrides_reach_every_host_config() {
let root = Path::new("/repo");
let mut config = default_project_config(root).config;
apply_env_overrides_from(
&mut config,
&lookup_from(&[
("FALLOW_MAX_FILE_SIZE", "7"),
("FALLOW_CACHE_DIR", ".cache/fallow"),
("FALLOW_CACHE_MAX_SIZE", "64"),
]),
);
assert_eq!(
config.max_file_size_bytes,
fallow_config::resolve_max_file_size_bytes(Some(7))
);
assert_eq!(config.cache_dir, root.join(".cache/fallow"));
assert_eq!(config.cache_max_size_mb, Some(64));
}
#[test]
fn cache_max_size_env_gives_one_limit_before_and_after_resolve() {
let root = Path::new("/repo");
let resolve = |configured: Option<u32>, argument: Option<u32>| {
FallowConfig {
cache: fallow_config::CacheConfig {
dir: None,
max_size_mb: configured,
},
..FallowConfig::default()
}
.resolve(
root.to_path_buf(),
OutputFormat::Human,
1,
false,
true,
argument,
)
};
let values: [&[(&str, &str)]; 5] = [
&[],
&[("FALLOW_CACHE_MAX_SIZE", "64")],
&[("FALLOW_CACHE_MAX_SIZE", " 8 ")],
&[("FALLOW_CACHE_MAX_SIZE", "0")],
&[("FALLOW_CACHE_MAX_SIZE", "many")],
];
for configured in [None, Some(5)] {
for vars in values {
let argument = lookup_from(vars)
.get(EnvVar::CacheMaxSize)
.and_then(fallow_config::cache_max_size_from_env_value);
let before = resolve(configured, argument);
let mut after = resolve(configured, None);
apply_env_overrides_from(&mut after, &lookup_from(vars));
assert_eq!(
before.cache_max_size_mb, after.cache_max_size_mb,
"{configured:?} {vars:?}"
);
}
}
}
#[test]
fn invalid_or_empty_env_values_keep_the_config() {
let root = Path::new("/repo");
let mut config = default_project_config(root).config;
let before_dir = config.cache_dir.clone();
let before_max = config.cache_max_size_mb;
apply_env_overrides_from(
&mut config,
&lookup_from(&[("FALLOW_CACHE_DIR", ""), ("FALLOW_CACHE_MAX_SIZE", "0")]),
);
assert_eq!(config.cache_dir, before_dir);
assert_eq!(config.cache_max_size_mb, before_max);
}
#[test]
fn package_baselines_env_turns_the_map_off_only_for_a_false_value() {
let root = Path::new("/repo");
let with_map = || {
let mut config = default_project_config(root).config;
config
.workspace_changed_since
.insert("packages/web".to_owned(), "main".to_owned());
config
};
let mut disabled = with_map();
apply_env_overrides_from(
&mut disabled,
&lookup_from(&[("FALLOW_PACKAGE_BASELINES", " Off ")]),
);
assert!(disabled.workspace_changed_since.is_empty());
for value in ["true", "1", "maybe", ""] {
let mut kept = with_map();
apply_env_overrides_from(
&mut kept,
&lookup_from(&[("FALLOW_PACKAGE_BASELINES", value)]),
);
assert_eq!(kept.workspace_changed_since.len(), 1, "{value:?}");
}
}
}