Skip to main content

fallow_engine/resolved_run/
pick.rs

1//! The precedence of run decisions.
2//!
3//! Each decision has one candidate per input. [`pick`] keeps the candidate
4//! with the highest rank `(Layer, Scope)`, so one order decides every
5//! decision.
6
7use std::path::Path;
8
9use fallow_config::{
10    PRODUCTION_DEAD_CODE_ENV, PRODUCTION_DUPES_ENV, PRODUCTION_ENV, PRODUCTION_HEALTH_ENV,
11    ProductionAnalysis, ProductionConfig,
12};
13use fallow_types::sourced::{Given, Scope, Source, Sourced};
14
15/// The rule name of the production default: production mode is off.
16const PRODUCTION_DEFAULT: &str = "production-off";
17/// The source name of a production config that the caller built without a
18/// config file.
19const IN_MEMORY_CONFIG: &str = "config";
20
21/// The candidate with the highest rank wins. A tie keeps the first candidate.
22/// The fallback applies only when no candidate is present.
23fn pick<T>(
24    fallback: Sourced<T>,
25    candidates: impl IntoIterator<Item = Option<Sourced<T>>>,
26) -> Sourced<T> {
27    candidates
28        .into_iter()
29        .flatten()
30        .reduce(|best, candidate| {
31            if candidate.rank() > best.rank() {
32                candidate
33            } else {
34                best
35            }
36        })
37        .unwrap_or(fallback)
38}
39
40/// One value for each analysis that has a production mode.
41#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
42pub struct PerAnalysis<T> {
43    /// The value of the dead-code analysis.
44    pub dead_code: T,
45    /// The value of the health analysis.
46    pub health: T,
47    /// The value of the duplication analysis.
48    pub dupes: T,
49}
50
51impl<T> PerAnalysis<T> {
52    /// The value of `analysis`.
53    pub const fn get(&self, analysis: ProductionAnalysis) -> &T {
54        match analysis {
55            ProductionAnalysis::DeadCode => &self.dead_code,
56            ProductionAnalysis::Health => &self.health,
57            ProductionAnalysis::Dupes => &self.dupes,
58        }
59    }
60
61    fn from_fn(mut f: impl FnMut(ProductionAnalysis) -> T) -> Self {
62        Self {
63            dead_code: f(ProductionAnalysis::DeadCode),
64            health: f(ProductionAnalysis::Health),
65            dupes: f(ProductionAnalysis::Dupes),
66        }
67    }
68}
69
70/// The production inputs of one run, before the config. The config is a
71/// separate argument of [`decide_production`].
72#[derive(Debug, Clone, Copy, Default)]
73pub struct ProductionInputs {
74    /// The global value that the caller gives, for example `--production`.
75    pub global_flag: Option<Given<bool>>,
76    /// The value of each analysis that the caller gives, for example
77    /// `--production-health`.
78    pub own_flag: PerAnalysis<Option<Given<bool>>>,
79    /// `FALLOW_PRODUCTION`, when the host reads it.
80    pub global_env: Option<bool>,
81    /// `FALLOW_PRODUCTION_<ANALYSIS>`, when the host reads it.
82    pub own_env: PerAnalysis<Option<bool>>,
83}
84
85/// The production mode of each analysis, with the input that decides it.
86///
87/// The order is: the value of the analysis that the caller gives, the global
88/// value that the caller gives, the variable of the analysis, the global
89/// variable, the config, then the default `false`. `file` is the config file
90/// that gave `config`. Without a file, `config` is a value that the caller
91/// built: its value is the fallback, with [`Source::Default`] when it is the
92/// default config and [`Source::Derived`] when it is not.
93pub fn decide_production(
94    inputs: &ProductionInputs,
95    config: &ProductionConfig,
96    file: Option<&Path>,
97) -> PerAnalysis<Sourced<bool>> {
98    let given = |value: Option<Given<bool>>, scope| {
99        value.map(|given| {
100            let source = Source::Given {
101                origin: given.origin,
102            };
103            Sourced::new(given.value, source, scope)
104        })
105    };
106    let environment = |value: Option<bool>, name, scope| {
107        value.map(|value| Sourced::new(value, Source::Environment { name }, scope))
108    };
109    PerAnalysis::from_fn(|analysis| {
110        pick(
111            production_fallback(config, analysis),
112            [
113                given(*inputs.own_flag.get(analysis), Scope::Analysis),
114                given(inputs.global_flag, Scope::Global),
115                environment(
116                    *inputs.own_env.get(analysis),
117                    production_env_name(analysis),
118                    Scope::Analysis,
119                ),
120                environment(inputs.global_env, PRODUCTION_ENV, Scope::Global),
121                file.map(|file| production_config_value(config, file, analysis)),
122            ],
123        )
124    })
125}
126
127const fn production_env_name(analysis: ProductionAnalysis) -> &'static str {
128    match analysis {
129        ProductionAnalysis::DeadCode => PRODUCTION_DEAD_CODE_ENV,
130        ProductionAnalysis::Health => PRODUCTION_HEALTH_ENV,
131        ProductionAnalysis::Dupes => PRODUCTION_DUPES_ENV,
132    }
133}
134
135const fn production_config_key(analysis: ProductionAnalysis) -> &'static str {
136    match analysis {
137        ProductionAnalysis::DeadCode => "production.deadCode",
138        ProductionAnalysis::Health => "production.health",
139        ProductionAnalysis::Dupes => "production.dupes",
140    }
141}
142
143/// The config candidate. The bool form applies to every analysis; each key
144/// of the object form applies to one analysis.
145fn production_config_value(
146    config: &ProductionConfig,
147    file: &Path,
148    analysis: ProductionAnalysis,
149) -> Sourced<bool> {
150    let (key, scope) = match config {
151        ProductionConfig::Global(_) => ("production", Scope::Global),
152        ProductionConfig::PerAnalysis(_) => (production_config_key(analysis), Scope::Analysis),
153    };
154    Sourced::new(
155        config.for_analysis(analysis),
156        Source::ConfigFile {
157            file: file.to_path_buf(),
158            key,
159        },
160        scope,
161    )
162}
163
164fn production_fallback(config: &ProductionConfig, analysis: ProductionAnalysis) -> Sourced<bool> {
165    let source = if *config == ProductionConfig::default() {
166        Source::Default {
167            rule: PRODUCTION_DEFAULT,
168        }
169    } else {
170        Source::Derived {
171            from: IN_MEMORY_CONFIG,
172        }
173    };
174    Sourced::new(config.for_analysis(analysis), source, Scope::Global)
175}
176
177#[cfg(test)]
178#[path = "pick_tests.rs"]
179mod tests;