ayun_config/traits/
mod.rs

1use crate::error::Error;
2use ayun_core::{support::base_path, Result};
3
4pub trait ConfigurationTrait {
5    fn new(table: toml::Table, from: Source) -> Self;
6
7    fn try_from_source(source: Source) -> Result<Self, Error>
8    where
9        Self: Sized;
10
11    fn source(&self) -> &Source;
12
13    fn has(&self, key: &str) -> bool;
14
15    fn get<T: serde::de::DeserializeOwned>(&self, key: &str) -> Result<T, Error>;
16
17    fn all(&self) -> toml::Table;
18}
19
20#[derive(Clone, Debug, Default)]
21pub enum Source {
22    #[default]
23    Default,
24    Toml(String),
25}
26
27impl std::str::FromStr for Source {
28    type Err = Error;
29
30    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
31        match s {
32            s if s.ends_with(".toml") => Ok(Self::Toml(s.to_owned())),
33            _ => Err(Error::Message("config is invalid".to_owned())),
34        }
35    }
36}
37
38impl std::fmt::Display for Source {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        match self {
41            Self::Default => "{default}".fmt(f),
42            Self::Toml(s) => {
43                let workspace = base_path("").to_string_lossy().to_string();
44
45                s.replace(&workspace, "{workspace}/").fmt(f)
46            }
47        }
48    }
49}