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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
//! This module define main configuration structures: [`Config`] and [`ConfigBuilder`].

use crate::{AnyParser, Error, MergeCase, Parse, Result, Value, DEFAULT_KEYS_SEPARATOR};
use blake3::Hash;
use serde::de::DeserializeOwned;
use std::cmp::Ordering;
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};

/// Container for all parser sources which will (re)load data from a parsers in order in which they was added
/// to [`ConfigBuilder`]. It will provide access to merged set of (re)loaded configuration parameters.
pub struct Config {
    parsers: Vec<AnyParser>,
    value: Value,
    case_on: bool,
    hash: Hash,
    sealed_suffix: String,
    keys_delimiter: String,
}

impl Config {
    /// Reload and re-merge all configuration data from parsers.
    ///
    /// # Errors
    ///
    /// If any errors will occur during parsing/merging then error will be returned.
    pub fn reload(&mut self) -> Result<&mut Self> {
        let mut value = Value::default();
        for (idx, parser) in self.parsers.iter_mut().enumerate() {
            value = parser
                .parse(&value)
                .map_err(|e| Error::ParseValue(e, idx + 1))?
                .merge_with_case(&value, self.case_on);
        }

        value.seal(&self.sealed_suffix);
        self.hash = blake3::hash(&value.as_bytes());
        self.value = value;
        Ok(self)
    }

    /// Calculate hash for currently loaded configuration data.
    #[inline]
    pub fn hash(&self) -> String {
        format!("BLAKE3: {}", self.hash.to_hex())
    }

    /// Returns configuration data value to corresponding key/nested keys.
    ///
    /// # Example
    ///
    /// ```no_run
    /// let name: Option<u32> = conf.get_by_keys(["logger", "name"])?;
    /// ```
    ///
    /// # Errors
    ///
    /// If keys is empty, the error will be returned.
    #[inline]
    pub fn get_by_keys<I, K, T>(&self, keys: I) -> Result<Option<T>>
    where
        I: IntoIterator<Item = K>,
        K: AsRef<str>,
        T: DeserializeOwned,
    {
        self.value.get_by_keys(keys)
    }

    /// Returns configuration data value to corresponding key path with keys delimiter. Default delimiter is
    /// [`DEFAULT_KEYS_SEPARATOR`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use serde::Deserialize;
    ///
    /// #[derive(Deserialize)]
    /// struct Person {
    ///     first_name: String,
    ///     last_name: String,
    ///     age: u8,
    /// }
    ///
    /// let person: Option<Person> = conf.get_by_key_path("contact:info")?;
    /// ```
    ///
    /// # Errors
    ///
    /// If keys path or keys delimiter is empty, the corresponding error will be returned.
    #[inline]
    pub fn get_by_key_path<T, P>(&self, path: P) -> Result<Option<T>>
    where
        T: DeserializeOwned,
        P: AsRef<str>,
    {
        self.value
            .get_by_key_path_with_delim(path, &self.keys_delimiter)
    }

    /// Returns configuration data value to corresponding key path with delimiter.
    ///
    /// # Example
    ///
    /// ```no_run
    /// let name: Option<u32> = conf.get_by_key_path_with_delim("logger:name", ":")?;
    /// ```
    ///
    /// # Errors
    ///
    /// If keys path or delimiter is empty, the corresponding error will be returned.
    #[inline]
    pub fn get_by_key_path_with_delim<T, P, D>(&self, path: P, delim: D) -> Result<Option<T>>
    where
        T: DeserializeOwned,
        P: AsRef<str>,
        D: AsRef<str>,
    {
        self.value.get_by_key_path_with_delim(path, delim)
    }

    /// Deserialize configuration to destination struct/value.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use serde::Deserialize;
    ///
    /// #[derive(Deserialize)]
    /// struct Person {
    ///     first_name: String,
    ///     last_name: String,
    ///     age: u8,
    /// }
    ///
    /// let person: Person = conf.get()?;
    /// ```
    ///
    /// # Errors
    ///
    /// In case of any de-serialization problems the corresponding error will be returned.
    #[inline]
    pub fn get<T: DeserializeOwned>(&self) -> Result<T> {
        self.value.get()
    }

    /// Get reference to internal [`Value`] structure.
    #[inline]
    pub fn get_value(&self) -> &Value {
        &self.value
    }
}

impl Debug for Config {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        f.write_fmt(format_args!(
            "Config {{ parsers: size({}), value: {:?}, case_on: {:?}, hash: {:?}, sealed_suffix: {:?}, keys_delimiter: {:?} }}",
            self.parsers.len(),
            self.value,
            self.case_on,
            self.hash,
            self.sealed_suffix,
            self.keys_delimiter,
        ))
    }
}

impl Display for Config {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        f.write_fmt(format_args!("Config: {}\n{}", self.hash(), self.value))
    }
}

impl PartialEq for Config {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.hash == other.hash
    }
}

impl Eq for Config {}

impl PartialOrd for Config {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Config {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        self.hash.as_bytes().cmp(other.hash.as_bytes())
    }
}

/// The builder for [`Config`] structure.
pub struct ConfigBuilder {
    parsers: Vec<AnyParser>,
    sealed_suffix: String,
    keys_delimiter: String,
    auto_case_on: bool,
    merge_case: MergeCase,
}

impl ConfigBuilder {
    /// Append a parser to [`Config`]. First appended parser will have highest priority during (re)load merge, the last
    /// one will have lowest priority.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use irx_config::parsers::{env, json};
    /// use irx_config::ConfigBuilder;
    ///
    /// let config = ConfigBuilder::default()
    ///     .append_parser(
    ///         json::ParserBuilder::default()
    ///             .default_path("config.json")
    ///             .build()?,
    ///     )
    ///     .append_parser(
    ///         env::ParserBuilder::default()
    ///             .default_prefix("APP_")
    ///             .build()?,
    ///     )
    ///     .load()?;
    /// ```
    #[inline]
    pub fn append_parser<P>(mut self, parser: P) -> Self
    where
        P: Parse + 'static,
    {
        self.auto_case_on = self.auto_case_on && parser.is_case_sensitive();
        self.parsers.push(Box::new(parser));
        self
    }

    /// Set suffix for keys to mark them as a secret value which will be obfuscated during display/debugging output.
    /// If not set then all values will be displayed as is.
    ///
    ///
    /// # Example
    ///
    /// ```no_run
    /// use irx_config::parsers::env;
    /// use irx_config::ConfigBuilder;
    ///
    /// let config = ConfigBuilder::default()
    ///     .append_parser(
    ///         env::ParserBuilder::default()
    ///             .default_prefix("APP_")
    ///             .build()?,
    ///     )
    ///     .sealed_suffix("_sealed_")
    ///     .load()?;
    /// ```
    #[inline]
    pub fn sealed_suffix<S>(mut self, suffix: S) -> Self
    where
        S: Into<String>,
    {
        self.sealed_suffix = suffix.into();
        self
    }

    /// Set default key level delimiter. Default is [`DEFAULT_KEYS_SEPARATOR`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use clap::app_from_crate;
    /// use irx_config::parsers::cmd;
    /// use irx_config::ConfigBuilder;
    ///
    /// let app = app_from_crate!();
    ///
    /// let config = ConfigBuilder::default()
    ///     .append_parser(cmd::ParserBuilder::new(app).build()?)
    ///     .keys_delimiter("/")
    ///     .load()?;
    /// ```
    #[inline]
    pub fn keys_delimiter<D>(mut self, delim: D) -> Self
    where
        D: Into<String>,
    {
        self.keys_delimiter = delim.into();
        self
    }

    /// Set merge case mode for a keys (see [`MergeCase`]). Default is [`MergeCase::Auto`].
    #[inline]
    pub fn merge_case(mut self, case: MergeCase) -> Self {
        self.merge_case = case;
        self
    }

    /// Load all data from all previously appended parsers, merge data according to appended order and return [`Config`].
    ///
    /// # Errors
    ///
    /// If any errors will occur during parsing/merging then error will be returned.
    pub fn load(self) -> Result<Config> {
        let value = Value::default();
        let hash = blake3::hash(&value.as_bytes());
        let case_on = if MergeCase::Auto == self.merge_case {
            self.auto_case_on
        } else {
            MergeCase::Sensitive == self.merge_case
        };

        let mut config = Config {
            parsers: self.parsers,
            value,
            case_on,
            hash,
            sealed_suffix: self.sealed_suffix,
            keys_delimiter: self.keys_delimiter,
        };
        config.reload()?;
        Ok(config)
    }

    /// Load data from one parser and return [`Config`].
    ///
    /// # Errors
    ///
    /// If any errors will occur during parsing/merging then error will be returned.
    #[inline]
    pub fn load_one<P>(parser: P) -> Result<Config>
    where
        P: Parse + 'static,
    {
        ConfigBuilder::default().append_parser(parser).load()
    }

    /// Load all data from parsers' iterator, merge data according to iterator order and return [`Config`].
    ///
    /// # Errors
    ///
    /// If any errors will occur during parsing/merging then error will be returned.
    #[inline]
    pub fn load_from<I, P>(parsers: I) -> Result<Config>
    where
        I: IntoIterator<Item = P>,
        P: Parse + 'static,
    {
        parsers
            .into_iter()
            .fold(ConfigBuilder::default(), |s, p| s.append_parser(p))
            .load()
    }
}

impl Default for ConfigBuilder {
    fn default() -> Self {
        Self {
            parsers: Default::default(),
            sealed_suffix: Default::default(),
            keys_delimiter: DEFAULT_KEYS_SEPARATOR.to_string(),
            auto_case_on: true,
            merge_case: Default::default(),
        }
    }
}