ayun_config/support/
config.rs

1use crate::{
2    error::Error,
3    traits::{ConfigurationTrait, Source},
4    Config, ConfigResult,
5};
6
7impl Config {
8    fn try_from_file(source: &str) -> ConfigResult<toml::Table> {
9        Ok(std::fs::read_to_string(source)
10            .map_err(|err| Error::Message(format!("`{source}` {err}")))?
11            .parse::<toml::Table>()?)
12    }
13}
14
15impl ConfigurationTrait for Config {
16    fn new(table: toml::Table, source: Source) -> Self {
17        Self {
18            inner: table,
19            source,
20        }
21    }
22
23    fn try_from_source(source: Source) -> ConfigResult<Self> {
24        Ok(match source.to_owned() {
25            Source::Default => Self::default(),
26            Source::Toml(file) => Self::new(Self::try_from_file(&file)?, source),
27        })
28    }
29
30    fn source(&self) -> &Source {
31        &self.source
32    }
33
34    fn has(&self, key: &str) -> bool {
35        self.inner.contains_key(key)
36    }
37
38    /// get toml config and deserialize to type
39    fn get<T: serde::de::DeserializeOwned>(&self, key: &str) -> ConfigResult<T> {
40        let value = match self.inner.get(key) {
41            Some(value) => value.clone(),
42            None => toml::from_str::<toml::Value>("")?,
43        };
44
45        Ok(value.try_into()?)
46    }
47
48    fn all(&self) -> toml::Table {
49        self.inner.clone()
50    }
51}