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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! viperus is an (in)complete configuration solution for Rust applications.
//!
//! I have already said that it is incomplete?
//! use at your own risk. ;-)
//! viperus handle some types of configuration needs and formats.
//!* setting defaults
//! * reading from JSON, TOML, YAML, dotenv file ,java properties config files
//! * reading from environment variables
//! * reading from Clap command line flags
//! * setting explicit values
//! * reload of all files
//! * whatch config files and reolad all in something changes
//! * caching
//! Viperus uses the following decreasing precedence order.
//! * explicit call to `add`
//! * clap flag
//! * config
//! * env variables
//! * default
//!
#![warn(clippy::all)]
#[macro_use]
#[cfg(feature = "global")]
extern crate lazy_static;

#[cfg(any(feature = "fmt-yaml", feature = "fmt-toml"))]
extern crate serde;
#[cfg(feature = "ftm-yaml")]
extern crate serde_yaml;
#[macro_use]
extern crate log;

mod adapter;
mod map;
pub use adapter::AdapterResult;
pub use adapter::ConfigAdapter;

#[cfg(feature = "cache")]
use std::cell::RefCell;

#[cfg(feature = "ftm-calp")]
use clap;

pub use map::Map;
pub use map::ViperusValue;
use std::error::Error;
use std::fmt::Display;

use std::str::FromStr;

#[cfg(feature = "global")]
mod global;

#[cfg(feature = "global")]
pub use global::*;

#[derive(Debug)]
pub enum ViperusError {
    Generic(String),
}
impl Error for ViperusError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match &self {
            _ => None,
        }
    }
}
impl Display for ViperusError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self {
            ViperusError::Generic(s) => write!(formatter, "Viperus Generic Error: {}", s),
        }
    }
}

#[macro_export]
macro_rules! path {
    ( $ x : expr ) =>  (format!("{}",$x));
    ( $ x: expr, $($y:expr),+) =>  (format!("{}{}{}",$x,std::path::MAIN_SEPARATOR,path!($($y),+)))
}

///preconfigured file formats with stock adapters
#[derive(Debug, Clone, Copy)]
pub enum Format {
    Auto,
    #[cfg(feature = "fmt-yaml")]
    YAML,
    #[cfg(feature = "fmt-json")]
    JSON,
    #[cfg(feature = "fmt-toml")]
    TOML,
    #[cfg(feature = "fmt-env")]
    ENV,
    #[cfg(feature = "fmt-javaproperties")]
    JAVAPROPERTIES,
}

/// A unified config Facade
///
/// Viperous manage config source from files, env and command line parameters in a unified manner
#[derive(Debug)]
pub struct Viperus<'a> {
    default_map: map::Map,
    config_map: map::Map,
    override_map: map::Map,

    #[cfg(feature = "fmt-clap")]
    clap_matches: clap::ArgMatches<'a>,
    #[cfg(not(feature = "fmt-clap"))]
    clap_matches: std::marker::PhantomData<&'a u32>,

    #[cfg(feature = "fmt-clap")]
    clap_bonds: std::collections::HashMap<String, String>,
    loaded_files: std::collections::LinkedList<(String, Format)>,
    #[cfg(feature = "cache")]
    cache_map: RefCell<map::Map>,
    #[cfg(feature = "cache")]
    cache_use: bool,

    enable_automatic_env: bool,

    env_prefix: String,
}

impl<'v> Default for Viperus<'v> {
    fn default() -> Self {
        Viperus::new()
    }
}

impl<'v> Viperus<'v> {
    pub fn new() -> Self {
        Viperus {
            default_map: map::Map::new(),
            config_map: map::Map::new(),
            override_map: map::Map::new(),
            #[cfg(feature = "fmt-clap")]
            clap_matches: clap::ArgMatches::default(),
            #[cfg(not(feature = "fmt-clap"))]
            clap_matches: std::marker::PhantomData,
            #[cfg(feature = "fmt-clap")]
            clap_bonds: std::collections::HashMap::new(),
            loaded_files: std::collections::LinkedList::new(),
            #[cfg(feature = "cache")]
            cache_map: RefCell::new(map::Map::new()),
            #[cfg(feature = "cache")]
            cache_use: false,
            enable_automatic_env: false,
            env_prefix: String::default(),
        }
    }

    /// whan enabled viperus will check for an environment variable any time Get request is made
    /// checking  for a environment variable with a name matching the key uppercased and prefixed with the
    /// env_prefix if set.
    /// this uses std:env if feature fmt-env is disabled
    pub fn automatic_env(&mut self, enable: bool) {
        self.enable_automatic_env = enable;
    }

    /// prepend 'pefix' when quering environment  variables
    pub fn set_env_prefix(&mut self, prefix: &str) {
        self.env_prefix = prefix.to_owned();
    }

    ///load_clap  brings in  the clap magic
    #[cfg(feature = "fmt-clap")]
    pub fn load_clap(&mut self, matches: clap::ArgMatches<'v>) -> Result<(), Box<dyn Error>> {
        debug!("loading  {:?}", matches);

        self.clap_matches = matches;

        for &k in self.clap_matches.args.keys() {
            self.clap_bonds.insert(k.to_owned(), k.to_owned());
        }

        Ok(())
    }

    ///reload   all config file preserving the order
    pub fn reload(&mut self) -> Result<(), Box<dyn Error>> {
        self.config_map.drain();

        #[cfg(feature = "cache")]
        {
            if self.cache_use {
                self.cache(true);
            }
        }

        let lf = &self.loaded_files.iter().cloned().collect::<Vec<_>>();
        for (name, format) in lf {
            if std::path::Path::new(name).exists() {
                debug!("reloading  {} => {:?}", name, format);

                self.load_file(name, format.clone())?;
            } else {
                debug!("not exists  {} => {:?}", name, format);
            }
        }
        Ok(())
    }

    pub fn loaded_file_names(&self) -> Vec<String> {
        self.loaded_files.iter().map(|e| e.0.clone()).collect()
    }

    ///load_file load a config file using one of the preconfigured addapters
    ///then applay the adatpter using load_adapter method
    pub fn load_file(&mut self, name: &str, format: Format) -> Result<(), Box<dyn Error>> {
        debug!("loading  {}", name);

        match format {
            #[cfg(feature = "fmt-yaml")]
            Format::YAML => {
                let mut adt = adapter::YamlAdapter::new();
                adt.load_file(name)?;
                self.loaded_files.push_back((name.to_owned(), format));

                self.load_adapter(&mut adt)
            }
            #[cfg(feature = "fmt-json")]
            Format::JSON => {
                let mut adt = adapter::JsonAdapter::new();
                adt.load_file(name)?;
                self.loaded_files.push_back((name.to_owned(), format));

                self.load_adapter(&mut adt)
            }

            #[cfg(feature = "fmt-toml")]
            Format::TOML => {
                let mut adt = adapter::TomlAdapter::new();
                adt.load_file(name)?;
                self.loaded_files.push_back((name.to_owned(), format));

                self.load_adapter(&mut adt)
            }

            #[cfg(feature = "fmt-env")]
            Format::ENV => {
                let mut adt = adapter::EnvAdapter::new();
                adt.load_file(name)?;
                self.loaded_files
                    .push_back((adt.get_real_path().to_str().unwrap().to_owned(), format));
                self.load_adapter(&mut adt)
            }

            #[cfg(feature = "fmt-javaproperties")]
            Format::JAVAPROPERTIES => {
                let mut adt = adapter::JavaPropertiesAdapter::new();
                adt.load_file(name)?;
                self.load_adapter(&mut adt)
            }

            _ => Err::<(), Box<dyn Error>>(Box::new(ViperusError::Generic(
                "Format not implemented".to_owned(),
            ))),
        }
    }

    /// load_adapter ask the adapter to parse her data and merges result map in the internal configartion map
    pub fn load_adapter(
        &mut self,
        adt: &mut dyn adapter::ConfigAdapter,
    ) -> Result<(), Box<dyn Error>> {
        adt.parse()?;
        self.config_map.merge(&adt.get_map());
        Ok(())
    }

    /// get a configuration value of type T in this order
    /// * overrided key
    /// * clap parameters
    /// * config adapter sourced values
    pub fn get<'a, 'b, 'c, T>(&'a self, key: &'b str) -> Option<T>
    where
        map::ViperusValue: From<T>,
        &'c map::ViperusValue: Into<T>,
        map::ViperusValue: Into<T>,
        T: FromStr,
        T: Clone,
    {
        #[cfg(feature = "cache")]
        {
            if self.cache_use {
                let res = self.cache_map.borrow().get(key);

                if let Some(v) = res {
                    return Some(v);
                }
            }
        }

        let res = self.override_map.get(key);

        if let Some(v) = res {
            #[cfg(feature = "cache")]
            {
                if self.cache_use {
                    self.cache_map.borrow_mut().add(key, v.clone());
                }
            }
            return Some(v);
        }

        #[cfg(feature = "fmt-clap")]
        let src = self.clap_bonds.get::<String>(&key.to_owned());
        #[cfg(feature = "fmt-clap")]
        {
            if let Some(dst) = src {
                debug!("clap mapped {}=>{}", key, dst);

                if self.clap_matches.is_present(dst) {
                    debug!("clap matched {}=>{}", key, dst);
                    let res = self.clap_matches.value_of(dst);

                    if let Some(v) = res {
                        let mv = &map::ViperusValue::Str(v.to_owned());
                        #[cfg(feature = "cache")]
                        {
                            if self.cache_use {
                                self.cache_map.borrow_mut().add(key, mv.clone().into());
                            }
                        }

                        return Some(mv.clone().into());
                    }
                }
            }
        }

        let cfg = self.config_map.get(key);

        if cfg.is_some() {
            #[cfg(feature = "cache")]
            {
                if self.cache_use {
                    self.cache_map.borrow_mut().add(key, cfg.clone().unwrap());
                }
            }

            return cfg;
        }

        #[cfg(feature = "fmt-clap")]
        {
            //default option value
            if let Some(dst) = src {
                debug!("clap default mapped {}=>{}", key, dst);
                if !self.clap_matches.is_present(dst) {
                    debug!("clap default matched {}=>{}", key, dst);
                    let res = self.clap_matches.value_of(dst);
                    debug!("clap default value {}=>{} {:?}", key, dst, res);
                    if let Some(v) = res {
                        let pval = v.parse::<T>().ok();
                        //UHMMMM TODO
                        #[cfg(feature = "cache")]
                        {
                            if self.cache_use {
                                self.cache_map.borrow_mut().add(key, pval.clone().unwrap());
                            }
                        }

                        return pval;
                    }
                }
            }
        }

        if self.enable_automatic_env {
            debug!("env_prefix {}", self.env_prefix);
            let env_key = format!("{}{}", self.env_prefix, key.to_uppercase());

            debug!("env_key {}", env_key);

            #[cfg(feature = "fmt-env")]
            let opt_env_val = dotenv::var(env_key);
            #[cfg(not(feature = "fmt-env"))]
            let opt_env_val = std::env::var(env_key);
            if let Ok(env_val) = opt_env_val {
                let pval = env_val.parse::<T>().ok();
                if pval.is_some() {
                    #[cfg(feature = "cache")]
                    {
                        if self.cache_use {
                            self.cache_map.borrow_mut().add(key, pval.clone().unwrap());
                        }
                    }
                    return pval;
                }
            }
        }

        let def = self.default_map.get(key);

        #[cfg(feature = "cache")]
        {
            if self.cache_use && def.is_some() {
                self.cache_map.borrow_mut().add(key, def.clone().unwrap());
            }
        }

        def
    }

    /// add an override value to the cofiguration
    ///
    /// key is structured in components separated by a "."
    pub fn add<'a, T>(&'a mut self, key: &'a str, value: T) -> Option<T>
    where
        map::ViperusValue: From<T>,
        map::ViperusValue: Into<T>,
    {
        self.override_map.add(key, value)
    }

    #[cfg(feature = "fmt-clap")]
    pub fn bond_clap(&mut self, src: &str, dst: &str) -> Option<String> {
        self.clap_bonds.insert(dst.to_owned(), src.to_owned())
    }

    /// add an default value to the configuration
    ///
    /// key is structured in components separated by a "."
    pub fn add_default<'a, T>(&'a mut self, key: &'a str, value: T) -> Option<T>
    where
        map::ViperusValue: From<T>,
        map::ViperusValue: Into<T>,
    {
        self.default_map.add(key, value)
    }

    /// cache the query results for small configs speedup is x4
    ///from v 0.1.9 returns the previus state , useful for test setups.
    #[cfg(feature = "cache")]
    pub fn cache(&mut self, enable: bool) -> bool {
        let result = self.cache_use;
        self.cache_use = enable;

        if self.cache_use {
            let cache_old = &mut map::Map::new();
            std::mem::swap(cache_old, &mut self.cache_map.borrow_mut());
        }

        result
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn init() {
        let _ = env_logger::builder().is_test(true).try_init();
    }

    #[test]
    #[should_panic]
    #[cfg(feature = "fmt-json")]
    fn lib_invalid_format() {
        init();
        let mut v = Viperus::default();
        v.load_file(&path!(".", "assets", "test.json"), Format::Auto)
            .unwrap();
    }
    #[test]
    fn lib_errors() {
        let e = ViperusError::Generic(String::from("generic"));
        let fe = format!("{}", e);
        let ex: Box<dyn Error> = Box::new(e);
        debug!("fe {}", fe);
        assert_ne!(ex.to_string(), "");
    }
    #[test]
    fn lib_works() {
        init();
        let mut v = Viperus::default();
        #[cfg(feature = "fmt-json")]
        v.load_file(&path!(".", "assets", "test.json"), Format::JSON)
            .unwrap();
        #[cfg(feature = "fmt-yaml")]
        v.load_file(&path!(".", "assets", "test.yaml"), Format::YAML)
            .unwrap();
        #[cfg(feature = "fmt-toml")]
        v.load_file(&path!(".", "assets", "test.toml"), Format::TOML)
            .unwrap();

        #[cfg(feature = "fmt-javaproperties")]
        v.load_file(
            &path!(".", "assets", "test.properties"),
            Format::JAVAPROPERTIES,
        )
        .unwrap();
        //v.load_file("asset\test.env", Format::JSON).unwrap();
        v.add("service.url", String::from("http://example.com"));
        debug!("final {:?}", v);

        let s: String = v.get("service.url").unwrap();
        assert_eq!("http://example.com", s);
        #[cfg(feature = "fmt-cache")]
        {
            v.cache(true);
            let s: String = v.get("service.url").unwrap();
            assert_eq!("http://example.com", s);
            let s: String = v.get("service.url").unwrap();
            assert_eq!("http://example.com", s);
            v.cache(false);
        }
        //test config
        #[cfg(feature = "fmt-json")]
        {
            let json_b = v.get::<bool>("level1.key_json").unwrap();
            assert_eq!(true, json_b);
        }
        #[cfg(feature = "fmt-yaml")]
        {
            let jyaml_b = v.get::<bool>("level1.key_yaml").unwrap();
            assert_eq!(true, jyaml_b);
        }

        #[cfg(feature = "fmt-javaproperties")]
        {
            let jprop_b = v.get::<bool>("level1.java_properties").unwrap();
            assert_eq!(true, jprop_b);

            //test config with cache
            #[cfg(feature = "cache")]
            {
                v.cache(true);
                let jprop_b = v.get::<bool>("level1.java_properties").unwrap();
                assert_eq!(true, jprop_b);
                let jprop_b = v.get::<bool>("level1.java_properties").unwrap();
                assert_eq!(true, jprop_b);
                v.cache(false);
            }
        }
        //test default
        v.add_default("default", true);

        assert_eq!(v.get::<bool>("default").unwrap(), true);

        //test default with cache
        #[cfg(feature = "cache")]
        {
            v.cache(true);
            assert_eq!(v.get::<bool>("default").unwrap(), true);
            assert_eq!(v.get::<bool>("default").unwrap(), true);
            v.cache(false);
        }

        //reload
        v.reload().unwrap();

        assert_eq!(v.get::<bool>("default").unwrap(), true);
        //reload with cache
        #[cfg(feature = "cache")]
        {
            v.cache(true);
            v.reload().unwrap();
            assert_eq!(v.get::<bool>("default").unwrap(), true);
            v.cache(false);
        }
    }
}