1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use crate::error::ConfigError;
use crate::validator::{SettingPath, ValidatorError};
use serde::{de::DeserializeOwned, Deserialize, Serialize};

pub struct ConfigMeta {
    /// Name of the struct.
    pub name: &'static str,

    /// File name of the loaded config.
    pub file: Option<&'static str>,
}

pub trait PartialConfig: Clone + Default + DeserializeOwned + Serialize + Sized {
    type Context: Default;

    fn default_values(context: &Self::Context) -> Result<Self, ConfigError>;

    fn env_values() -> Result<Self, ConfigError>;

    fn extends_from(&self) -> Option<ExtendsFrom>;

    fn merge(&mut self, next: Self);
}

pub trait Config: Sized {
    type Partial: PartialConfig;

    const META: ConfigMeta;

    fn default_values(
        context: &<Self::Partial as PartialConfig>::Context,
    ) -> Result<Self, ConfigError> {
        Ok(Self::from_partial(
            <Self::Partial as PartialConfig>::default_values(context)?,
        ))
    }

    fn from_partial(partial: Self::Partial) -> Self;

    fn partial() -> Self::Partial {
        <Self::Partial as Default>::default()
    }

    fn validate(
        &self,
        context: &<Self::Partial as PartialConfig>::Context,
    ) -> Result<(), ValidatorError> {
        self.validate_with_path(context, SettingPath::default())
    }

    fn validate_with_path(
        &self,
        _context: &<Self::Partial as PartialConfig>::Context,
        _path: SettingPath,
    ) -> Result<(), ValidatorError> {
        Ok(())
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum ExtendsFrom {
    String(String),
    List(Vec<String>),
}

impl Default for ExtendsFrom {
    fn default() -> Self {
        Self::List(vec![])
    }
}