Skip to main content

fallow_engine/baseline/
saved_scope.rs

1//! What a saved baseline file records about the run that saved it.
2
3use super::{BaselineData, DuplicationBaselineData, HealthBaselineData};
4
5impl BaselineData {
6    /// Record the channels that narrowed the saving run.
7    #[must_use]
8    pub fn with_scope_reasons(mut self, reasons: fallow_output::BaselineScopeReasons) -> Self {
9        self.scope_reasons = reasons
10            .iter()
11            .map(|reason| reason.as_str().to_owned())
12            .collect();
13        self
14    }
15}
16
17impl DuplicationBaselineData {
18    /// Record whether the saving run used production mode.
19    #[must_use]
20    pub fn with_production(mut self, production: bool) -> Self {
21        self.scope_reasons = production_reason(production);
22        self
23    }
24}
25
26impl HealthBaselineData {
27    /// Record whether the saving run used production mode.
28    #[must_use]
29    pub(crate) fn with_production(mut self, production: bool) -> Self {
30        self.scope_reasons = production_reason(production);
31        self
32    }
33}
34
35/// The reasons that a health or duplication file records: production mode only,
36/// because the prune guard reads that channel and no gate reads the file.
37fn production_reason(production: bool) -> Vec<String> {
38    if production {
39        vec![fallow_output::ScopeReason::Production.as_str().to_owned()]
40    } else {
41        Vec::new()
42    }
43}
44
45/// The non-empty finding categories of a dead-code baseline file, by field
46/// name. Empty for a file that is not a JSON object.
47#[must_use]
48pub fn saved_finding_categories(json: &str) -> Vec<String> {
49    macro_rules! field_names {
50        ($($field:ident),* $(,)?) => {
51            [$(stringify!($field)),*]
52        };
53    }
54    let Ok(value) = serde_json::from_str::<serde_json::Value>(json) else {
55        return Vec::new();
56    };
57    with_baseline_fields!(field_names)
58        .into_iter()
59        .filter(|field| {
60            value
61                .get(field)
62                .and_then(serde_json::Value::as_array)
63                .is_some_and(|entries| !entries.is_empty())
64        })
65        .map(str::to_owned)
66        .collect()
67}
68
69/// The `scope_reasons` a baseline file recorded when it was saved. Empty for a
70/// whole-project save, a file saved before the file recorded its scope, or a
71/// file that is not JSON.
72#[must_use]
73pub fn saved_scope_reasons(json: &str) -> Vec<String> {
74    serde_json::from_str::<serde_json::Value>(json)
75        .ok()
76        .and_then(|value| {
77            value.get("scope_reasons")?.as_array().map(|reasons| {
78                reasons
79                    .iter()
80                    .filter_map(serde_json::Value::as_str)
81                    .map(str::to_owned)
82                    .collect()
83            })
84        })
85        .unwrap_or_default()
86}