Skip to main content

vs_core/service/
config.rs

1//! Services for reading and mutating persisted configuration.
2
3use vs_config::{
4    app_config_to_value, flatten_app_config, read_app_config, set_app_config_value,
5    unset_app_config_value, write_app_config,
6};
7
8use crate::{App, CoreError};
9
10impl App {
11    /// Lists current application config values.
12    pub fn list_config(&self) -> Result<Vec<(String, String)>, CoreError> {
13        let config = self.app_config()?;
14        Ok(flatten_app_config(&config))
15    }
16
17    /// Returns the whole config as a YAML-like value.
18    pub fn config_value(&self) -> Result<serde_yaml::Value, CoreError> {
19        let config = self.app_config()?;
20        app_config_to_value(&config).map_err(Into::into)
21    }
22
23    /// Returns config entries for an exact key or section prefix.
24    pub fn config_entries_for_key(&self, key: &str) -> Result<Vec<(String, String)>, CoreError> {
25        let entries = self.list_config()?;
26        if let Some(entry) = entries.iter().find(|(entry_key, _)| entry_key == key) {
27            return Ok(vec![entry.clone()]);
28        }
29
30        let prefix = format!("{key}.");
31        let matching = entries
32            .into_iter()
33            .filter(|(entry_key, _)| entry_key.starts_with(&prefix))
34            .collect::<Vec<_>>();
35        if matching.is_empty() {
36            return Err(CoreError::Config(vs_config::ConfigError::UnknownKey(
37                key.to_string(),
38            )));
39        }
40        Ok(matching)
41    }
42
43    /// Sets a config key.
44    pub fn set_config_value(&self, key: &str, value: &str) -> Result<(), CoreError> {
45        let mut config = read_app_config(self.home())?;
46        set_app_config_value(&mut config, key, value)?;
47        write_app_config(self.home(), &config)?;
48        Ok(())
49    }
50
51    /// Unsets a config key.
52    pub fn unset_config_value(&self, key: &str) -> Result<(), CoreError> {
53        let mut config = read_app_config(self.home())?;
54        unset_app_config_value(&mut config, key)?;
55        write_app_config(self.home(), &config)?;
56        Ok(())
57    }
58}