Skip to main content

cargo_util_config/
reader.rs

1use std::fmt;
2use std::str::FromStr;
3use std::sync::Mutex;
4
5use anyhow::{Result, anyhow, bail};
6use cargo_util_terminal::Shell;
7
8use super::de::Deserializer;
9use super::{ConfigError, OptValue, Value};
10use crate::{ConfigKey, ConfigStore, ConfigValue, Definition, Env, is_nonmergeable_list};
11use cargo_util::collections::HashMap;
12
13use ConfigValue as CV;
14
15/// Reads configuration values from the loaded store and the environment.
16#[derive(Clone, Copy)]
17pub struct ConfigReader<'a> {
18    pub(crate) store: &'a ConfigStore,
19    pub(crate) shell: &'a Mutex<Shell>,
20    pub(crate) env: &'a Env,
21    pub(crate) unstable_advanced_env: bool,
22}
23
24/// Helper macro for creating typed access methods.
25macro_rules! get_value_typed {
26    ($name:ident, $ty:ty, $variant:ident, $expected:expr) => {
27        /// Low-level private method for getting a config value as an [`OptValue`].
28        pub(crate) fn $name(&self, key: &ConfigKey) -> Result<OptValue<$ty>, ConfigError> {
29            let cv = self.store.get_cv(key)?;
30            let env = self.get_config_env::<$ty>(key)?;
31            match (cv, env) {
32                (Some(CV::$variant(val, definition)), Some(env)) => {
33                    if definition.is_higher_priority(&env.definition) {
34                        Ok(Some(Value { val, definition }))
35                    } else {
36                        Ok(Some(env))
37                    }
38                }
39                (Some(CV::$variant(val, definition)), None) => Ok(Some(Value { val, definition })),
40                (Some(cv), _) => Err(ConfigError::expected(key, $expected, &cv)),
41                (None, Some(env)) => Ok(Some(env)),
42                (None, None) => Ok(None),
43            }
44        }
45    };
46}
47
48impl<'a> ConfigReader<'a> {
49    pub fn new(shell: &'a Mutex<Shell>) -> Self {
50        static STORE: ConfigStore = ConfigStore::new();
51        static ENV: Env = Env::new();
52        Self {
53            store: &STORE,
54            shell,
55            env: &ENV,
56            unstable_advanced_env: false,
57        }
58    }
59
60    #[must_use]
61    pub fn config(mut self, store: &'a ConfigStore) -> Self {
62        self.store = store;
63        self
64    }
65
66    #[must_use]
67    pub fn env(mut self, env: &'a Env) -> Self {
68        self.env = env;
69        self
70    }
71
72    #[must_use]
73    pub fn unstable_advanced_env(mut self, yes: bool) -> Self {
74        self.unstable_advanced_env = yes;
75        self
76    }
77
78    /// Deserialize the value at `key` into `T`
79    ///
80    /// When reading env variables, the type will be inferred from `T`.
81    /// When `T` cannot provide a type hint (e.g. `#[serde(untagged)]`),
82    /// the type will be inferred from the structure of the env variable.
83    pub fn get<'de, T: serde::Deserialize<'de>>(self, key: ConfigKey) -> Result<T> {
84        let de = Deserializer {
85            reader: self,
86            key,
87            env_prefix_ok: true,
88        };
89        Ok(T::deserialize(de)?)
90    }
91}
92
93/// Lower-level accessors
94impl ConfigReader<'_> {
95    /// Read a raw value, including from the environment
96    ///
97    /// When reading env variables,  the type will be inferred from the structure of the env variable.
98    pub fn get_cv_with_env(&self, key: &ConfigKey) -> Result<Option<CV>> {
99        // Determine if value comes from env, cli, or file, and merge env if
100        // possible.
101        let cv = self.store.get_cv(key)?;
102        if key.is_root() {
103            // Root table can't have env value.
104            return Ok(cv);
105        }
106        let env = self.env.get_str(key.as_env_key());
107        let use_env = match (&cv, env) {
108            // Lists are always merged.
109            (Some(CV::List(..)), Some(_)) => true,
110            (Some(cv), Some(_)) => {
111                crate::Scope::Environment.is_higher_priority(cv.definition().scope())
112            }
113            (None, Some(_)) => true,
114            _ => false,
115        };
116
117        if !use_env {
118            return Ok(cv);
119        }
120
121        // Future note: If you ever need to deserialize a non-self describing
122        // map type, this should implement a starts_with check (similar to how
123        // ConfigMapAccess does).
124        let env = env.unwrap();
125        let env_def = Definition::environment(key.as_env_key().to_string());
126        if env == "true" {
127            Ok(Some(CV::Boolean(true, env_def)))
128        } else if env == "false" {
129            Ok(Some(CV::Boolean(false, env_def)))
130        } else if let Ok(i) = env.parse::<i64>() {
131            Ok(Some(CV::Integer(i, env_def)))
132        } else if self.unstable_advanced_env && env.starts_with('[') && env.ends_with(']') {
133            match cv {
134                Some(CV::List(mut cv_list, cv_def)) => {
135                    // Merge with config file.
136                    self.get_env_list(key, &mut cv_list)?;
137                    Ok(Some(CV::List(cv_list, cv_def)))
138                }
139                Some(cv) => {
140                    // This can't assume StringList.
141                    // Return an error, which is the behavior of merging
142                    // multiple config.toml files with the same scenario.
143                    bail!(
144                        "unable to merge array env for config `{}`\n\
145                        file: {:?}\n\
146                        env: {}",
147                        key,
148                        cv,
149                        env
150                    );
151                }
152                None => {
153                    let mut cv_list = Vec::new();
154                    self.get_env_list(key, &mut cv_list)?;
155                    Ok(Some(CV::List(cv_list, env_def)))
156                }
157            }
158        } else {
159            // Try to merge if possible.
160            match cv {
161                Some(CV::List(mut cv_list, cv_def)) => {
162                    // Merge with config file.
163                    self.get_env_list(key, &mut cv_list)?;
164                    Ok(Some(CV::List(cv_list, cv_def)))
165                }
166                _ => {
167                    // Note: CV::Table merging is not implemented, as env
168                    // vars do not support table values. In the future, we
169                    // could check for `{}`, and interpret it as TOML if
170                    // that seems useful.
171                    Ok(Some(CV::String(env.to_string(), env_def)))
172                }
173            }
174        }
175    }
176
177    /// Low-level method for getting a config value as an `OptValue<HashMap<String, CV>>`.
178    ///
179    /// NOTE: This does not read from env. The caller is responsible for that.
180    pub fn get_table(&self, key: &ConfigKey) -> Result<OptValue<HashMap<String, CV>>> {
181        match self.store.get_cv(key)? {
182            Some(CV::Table(val, definition)) => Ok(Some(Value { val, definition })),
183            Some(val) => expected("table", key, &val),
184            None => Ok(None),
185        }
186    }
187
188    get_value_typed! {get_integer, i64, Integer, "an integer"}
189    get_value_typed! {get_bool, bool, Boolean, "true/false"}
190    get_value_typed! {get_string_priv, String, String, "a string"}
191
192    /// Check if the configuration contains a given [`ConfigKey`].
193    ///
194    /// See `ConfigMapAccess` for a description of `env_prefix_ok`.
195    pub(crate) fn has_key(&self, key: &ConfigKey, env_prefix_ok: bool) -> Result<bool> {
196        if self.env.contains_key(key.as_env_key()) {
197            return Ok(true);
198        }
199        if env_prefix_ok {
200            let env_prefix = format!("{}_", key.as_env_key());
201            if self.env.keys_str().any(|k| k.starts_with(&env_prefix)) {
202                return Ok(true);
203            }
204        }
205        if self.store.get_cv(key)?.is_some() {
206            return Ok(true);
207        }
208        self.check_environment_key_case_mismatch(key);
209
210        Ok(false)
211    }
212
213    /// Internal method for getting an environment variable as a list.
214    /// If the key is a non-mergeable list and a value is found in the environment, existing values are cleared.
215    pub(crate) fn get_env_list(
216        &self,
217        key: &ConfigKey,
218        output: &mut Vec<ConfigValue>,
219    ) -> Result<()> {
220        let Some(env_val) = self.env.get_str(key.as_env_key()) else {
221            self.check_environment_key_case_mismatch(key);
222            return Ok(());
223        };
224
225        let env_def = Definition::environment(key.as_env_key().to_string());
226
227        if is_nonmergeable_list(&key) {
228            assert!(
229                output
230                    .windows(2)
231                    .all(|cvs| cvs[0].definition() == cvs[1].definition()),
232                "non-mergeable list must have only one definition: {output:?}",
233            );
234
235            // Keep existing config if higher priority than env (e.g., --config CLI),
236            // otherwise clear for env
237            if output
238                .first()
239                .map(|o| o.definition() > &env_def)
240                .unwrap_or_default()
241            {
242                return Ok(());
243            } else {
244                output.clear();
245            }
246        }
247
248        if self.unstable_advanced_env && env_val.starts_with('[') && env_val.ends_with(']') {
249            // Parse an environment string as a TOML array.
250            let toml_v = env_val.parse::<toml::Value>().map_err(|e| {
251                ConfigError::new(format!("could not parse TOML list: {}", e), env_def.clone())
252            })?;
253            let values = toml_v.as_array().expect("env var was not array");
254            for value in values {
255                // Until we figure out how to deal with it through `-Zadvanced-env`,
256                // complex array types are unsupported.
257                let s = value.as_str().ok_or_else(|| {
258                    ConfigError::new(
259                        format!("expected string, found {}", value.type_str()),
260                        env_def.clone(),
261                    )
262                })?;
263                output.push(CV::String(s.to_string(), env_def.clone()))
264            }
265        } else {
266            output.extend(
267                env_val
268                    .split_whitespace()
269                    .map(|s| CV::String(s.to_string(), env_def.clone())),
270            );
271        }
272        output.sort_by(|a, b| a.definition().cmp(b.definition()));
273        Ok(())
274    }
275
276    pub(crate) fn warn(&self, message: String) -> Result<()> {
277        self.shell.lock().unwrap().warn(message)
278    }
279
280    fn get_config_env<T>(&self, key: &ConfigKey) -> Result<OptValue<T>, ConfigError>
281    where
282        T: FromStr,
283        <T as FromStr>::Err: fmt::Display,
284    {
285        match self.env.get_str(key.as_env_key()) {
286            Some(value) => {
287                let definition = Definition::environment(key.as_env_key().to_string());
288                Ok(Some(Value {
289                    val: value
290                        .parse()
291                        .map_err(|e| ConfigError::new(format!("{}", e), definition.clone()))?,
292                    definition,
293                }))
294            }
295            None => {
296                self.check_environment_key_case_mismatch(key);
297                Ok(None)
298            }
299        }
300    }
301
302    fn check_environment_key_case_mismatch(&self, key: &ConfigKey) {
303        if let Some(env_key) = self.env.get_normalized(key.as_env_key()) {
304            let _ = self.warn(format!(
305                "environment variables are expected to use uppercase letters and underscores, \
306                the variable `{}` will be ignored and have no effect",
307                env_key
308            ));
309        }
310    }
311}
312
313/// Generate an error when the given value is the wrong type.
314pub fn expected<T>(ty: &str, key: &ConfigKey, val: &CV) -> Result<T> {
315    val.expected(ty, &key.to_string())
316        .map_err(|e| anyhow!("invalid configuration for key `{}`\n{}", key, e))
317}