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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
//! Configuration sources module, see the [examples](https://github.com/leptonyu/cfg-rs/tree/main/examples) for general usage information.
use crate::*;

#[allow(unused_imports)]
use self::file::FileLoader;
use std::path::PathBuf;

/// Config key module.
pub mod key {
    pub use crate::key::{CacheKey, PartialKey, PartialKeyCollector};
}
pub use super::configuration::ManualSource;
pub use memory::ConfigSourceBuilder;

pub(crate) mod cargo;
pub(crate) mod environment;
pub(crate) mod file;
pub(crate) mod memory;
#[doc(hidden)]
#[cfg(feature = "rand")]
#[cfg_attr(docsrs, doc(cfg(feature = "rand")))]
pub(crate) mod random;

#[allow(dead_code)]
#[derive(Debug, FromConfig)]
pub(crate) struct EnabledOption {
    #[config(default = true)]
    pub(crate) enabled: bool,
}

macro_rules! file_block {
    ($($nm:ident.$name:literal.$file:literal: $($k:pat)|* => $x:path,)+) => {
$(
#[doc(hidden)]
#[cfg(feature = $name)]
#[cfg_attr(docsrs, doc(cfg(feature = $name)))]
pub mod $nm;
)+

#[derive(Debug, FromConfig)]
#[config(prefix = "app.sources")]
pub(crate) struct SourceOption {
    #[cfg(feature = "rand")]
    pub(crate) random: EnabledOption,
    $(
    #[cfg(feature = $name)]
    $nm: EnabledOption,
    )+
}

#[inline]
#[allow(unreachable_code, unused_variables, unused_mut)]
pub(crate) fn register_by_ext(
    mut config: Configuration,
    path: PathBuf,
    required: bool,
) -> Result<Configuration, ConfigError> {
    let ext = path
        .extension()
        .and_then(|x| x.to_str())
        .ok_or_else(|| ConfigError::ConfigFileNotSupported(path.clone()))?;
        match ext {
            $(
                #[cfg(feature = $name)]
                $($k)|* => {
                    config = config.register_source(<FileLoader<$x>>::new(
                        path.clone(),
                        required,
                        true,
                    ))?;
                }
            )+
            _ => return Err(ConfigError::ConfigFileNotSupported(path)),
        }
    Ok(config)
}

#[allow(unused_mut, unused_variables)]
pub(crate) fn register_files(
    mut config: Configuration,
    option: &SourceOption,
    path: PathBuf,
    has_ext: bool,
) -> Result<Configuration, ConfigError> {
    $(
    #[cfg(feature = $name)]
    if option.$nm.enabled {
        config =
            config.register_source(<FileLoader<$x>>::new(path.clone(), false, has_ext))?;
    }
    )+
    Ok(config)
}


#[cfg(test)]
mod test {
    $(
    #[test]
    #[cfg(not(feature = $name))]
    fn $nm() {
        use super::memory::HashSource;
        use crate::*;

        let _v: Result<HashSource, ConfigError> = inline_source!($file);
        match _v {
          Err(ConfigError::ConfigFileNotSupported(_)) =>{}
          _ => assert_eq!(true, false),
        }
    }
    )+
}
    };
}

file_block!(
    toml."toml"."../../app.toml" : "toml" | "tml" => crate::source::toml::Toml,
    yaml."yaml"."../../app.yaml" : "yaml" | "yml" => crate::source::yaml::Yaml,
    json."json"."../../app.json" : "json" => crate::source::json::Json,
    ini."ini"."../../app.ini" : "ini" => crate::source::ini::Ini,
);

/// Inline config file in repo, see [Supported File Formats](index.html#supported-file-format).
#[macro_export]
macro_rules! inline_source {
    ($path:literal) => {
        $crate::inline_source_internal!(
        $path:
        toml."toml": "toml" | "tml" => $crate::source::toml::Toml,
        yaml."yaml": "yaml" | "yml" => $crate::source::yaml::Yaml,
        json."json": "json" => $crate::source::json::Json,
        ini."ini": "ini" => $crate::source::ini::Ini,
        )
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! inline_source_internal {
    ($path:literal: $($nm:ident.$name:literal: $($k:pat)|* => $x:path,)+) => {
        match $path.rsplit_once(".") {
            Some((_, ext)) => {
                let _name = format!("inline:{}", $path);
                let _content = include_str!($path);
                match ext {
                    $(
                    #[cfg(feature = $name)]
                    $($k)|*  => $crate::inline_source_config::<$x>(_name, _content),
                    )+
                    _ => Err($crate::ConfigError::ConfigFileNotSupported($path.into()))
                }
            }
            _ => Err($crate::ConfigError::ConfigFileNotSupported($path.into()))
        }
    };
}

/// Config source adaptor is an intermediate representation of config source.
/// It can convert to [`ConfigSource`]. We have toml, yaml and json values implement this trait.
///
/// Config source adaptor examples:
/// * Toml format.
/// * Yaml format.
/// * Json format.
/// * Ini  format.
/// * ...
pub trait ConfigSourceAdaptor {
    /// Convert adaptor to standard config source.
    fn convert_source(self, builder: &mut ConfigSourceBuilder<'_>) -> Result<(), ConfigError>;
}

/// Parse config source from string.
pub trait ConfigSourceParser: Send {
    /// Config source adaptor.
    type Adaptor: ConfigSourceAdaptor;

    /// Parse config source.
    fn parse_source(_: &str) -> Result<Self::Adaptor, ConfigError>;

    /// File extenstions.
    fn file_extensions() -> Vec<&'static str>;
}

/// Config source.
///
/// Config source examples:
/// * Load from programming.
/// * Load from environment.
/// * Load from file.
/// * Load from network.
/// * ...
pub trait ConfigSource: Send {
    /// Config source name.
    fn name(&self) -> &str;

    /// Load config source.
    fn load(&self, builder: &mut ConfigSourceBuilder<'_>) -> Result<(), ConfigError>;

    /// If this config source can be refreshed.
    fn allow_refresh(&self) -> bool {
        false
    }

    /// Check if config source is refreshable.
    ///
    /// Implementor should notice that everytime this method is called, the refreshable state **must** be reset to **false**.
    fn refreshable(&self) -> Result<bool, ConfigError> {
        Ok(false)
    }
}