Skip to main content

codeint_config/
resolved.rs

1use std::fmt;
2use std::path::PathBuf;
3use std::str::FromStr;
4
5use codeint_model::SourceSet;
6use serde::Serialize;
7use serde_json::Value;
8
9use crate::{Budget, Configuration};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
12#[serde(rename_all = "snake_case")]
13pub enum ConfigProvenance {
14    Default,
15    File,
16    Cli,
17}
18
19impl ConfigProvenance {
20    pub fn label(self) -> &'static str {
21        match self {
22            ConfigProvenance::Default => "default",
23            ConfigProvenance::File => "file",
24            ConfigProvenance::Cli => "cli",
25        }
26    }
27}
28
29impl fmt::Display for ConfigProvenance {
30    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
31        formatter.write_str(self.label())
32    }
33}
34
35#[derive(Debug, Clone, PartialEq, Serialize)]
36pub struct ResolvedSetting {
37    pub key: String,
38    pub value: Value,
39    pub source: ConfigProvenance,
40}
41
42#[derive(Debug)]
43pub struct ResolvedConfiguration {
44    pub config_file: PathBuf,
45    pub config_file_present: bool,
46    pub configuration: Configuration,
47    pub settings: Vec<ResolvedSetting>,
48}
49
50#[derive(Debug, Clone, PartialEq)]
51pub struct BudgetOverride {
52    pub source_set: SourceSet,
53    pub metric: String,
54    pub budget: Budget,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct SourceSetOverride {
59    pub source_set: SourceSet,
60    pub glob: String,
61}
62
63#[derive(Debug, Clone, Default, PartialEq)]
64pub struct ConfigOverrides {
65    pub budgets: Vec<BudgetOverride>,
66    pub source_sets: Vec<SourceSetOverride>,
67    pub plugin_memory_mb: Option<u64>,
68    pub plugin_timeout_ms: Option<u64>,
69}
70
71impl FromStr for BudgetOverride {
72    type Err = String;
73
74    fn from_str(raw: &str) -> Result<BudgetOverride, String> {
75        let (target, ratio_text) = raw.split_once('=').ok_or_else(|| {
76            format!("{raw:?} must use SOURCE_SET.METRIC=RATIO, such as production.erosion=0.25")
77        })?;
78        let (source_set_text, metric) = target.split_once('.').ok_or_else(|| {
79            format!("{target:?} must name SOURCE_SET.METRIC, such as production.erosion")
80        })?;
81        let source_set = parse_source_set(source_set_text)?;
82        if metric.is_empty()
83            || metric.trim() != metric
84            || metric.contains('.')
85            || metric.chars().any(char::is_whitespace)
86        {
87            return Err(format!("{metric:?} is not a valid Metric key in {raw:?}"));
88        }
89        let ratio: f64 = ratio_text
90            .parse()
91            .map_err(|_| format!("{ratio_text:?} is not a number between 0 and 1"))?;
92        let budget = Budget::new(ratio)
93            .ok_or_else(|| format!("Budget ratio must be between 0 and 1, not {ratio}"))?;
94        Ok(BudgetOverride {
95            source_set,
96            metric: metric.to_owned(),
97            budget,
98        })
99    }
100}
101
102impl FromStr for SourceSetOverride {
103    type Err = String;
104
105    fn from_str(raw: &str) -> Result<SourceSetOverride, String> {
106        let (source_set_text, glob) = raw
107            .split_once('=')
108            .ok_or_else(|| format!("{raw:?} must use SOURCE_SET=GLOB, such as test=spec/**"))?;
109        let source_set = parse_source_set(source_set_text)?;
110        if glob.trim().is_empty() {
111            return Err(format!("glob in {raw:?} must not be empty"));
112        }
113        crate::config_error::compile_glob(glob)
114            .map_err(|error| format!("glob {glob:?} in {raw:?} is not a valid glob: {error}"))?;
115        Ok(SourceSetOverride {
116            source_set,
117            glob: glob.to_owned(),
118        })
119    }
120}
121
122pub(crate) fn parse_source_set(name: &str) -> Result<SourceSet, String> {
123    match name {
124        "production" => Ok(SourceSet::Production),
125        "test" => Ok(SourceSet::Test),
126        "generated" => Ok(SourceSet::Generated),
127        "vendored" => Ok(SourceSet::Vendored),
128        _ => Err(format!(
129            "{name:?} is not a Source set; use one of production, test, generated, vendored"
130        )),
131    }
132}
133
134pub(crate) fn resolve_with_provenance<T>(
135    default: T,
136    from_file: Option<T>,
137    from_cli: Option<T>,
138) -> (T, ConfigProvenance) {
139    if let Some(value) = from_cli {
140        return (value, ConfigProvenance::Cli);
141    }
142    if let Some(value) = from_file {
143        return (value, ConfigProvenance::File);
144    }
145    (default, ConfigProvenance::Default)
146}