Skip to main content

vs_core/service/
config.rs

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