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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! ov-config is a configuration parsing library that provide macros and convenience functions for generating configuration schema, sanity check, flush, refresh, etc. Design for `.toml` and `.ini`.
//!
//! # Usage
//! - Create Configuration Schema
//! ```
//! extern crate ov_config;
//!
//! use ov_config::*;
//!
//! make_config!(
//!     TestConfig,
//!     SECTION1 {
//!         //key: Type: Default Value => Verification closure
//!         a_string: String: "key1".into() => |x: &String| x.len() > 0,
//!         a_vector: Vec<i32>: vec![1, 2, 3] => |x: &Vec<i32>| x.len() < 4
//!     };
//!     // Support for multi section per config
//!     SECTION2 {
//!         a_i32: i32: 15 => |x: &i32| *x < 20,
//!         a_bool: bool: true => |_| true
//!     }
//! );
//!
//! fn main() {
//!     let config = TestConfig{..Default::default()};
//!     assert_eq!(config.SECTION1.a_string, "key1");
//!     assert_eq!(config.SECTION1.a_vector, vec![1, 2, 3]);
//!     assert_eq!(config.SECTION2.a_i32, 15);
//!     assert_eq!(config.SECTION2.a_bool, true);
//! }
//! ```
//!
//! - Get config from file -- will automatcially do sanity check on each value.
//! ```
//! extern crate ov_config;
//! use ov_config::*;
//! use std::fs::File;
//! use std::io::prelude::*;
//!
//! make_config!(
//!     TestConfig,
//!     SECTION1 {
//!         //key: Type: Default Value => Verification closure
//!         a_string: String: "key1".into() => |x: &String| x.len() > 0,
//!         a_vector: Vec<i32>: vec![1, 2, 3] => |x: &Vec<i32>| x.len() < 4
//!     };
//!     // Support for multi section per config
//!     SECTION2 {
//!         a_i32: i32: 15 => |x: &i32| *x < 20,
//!         a_bool: bool: true => |_| true
//!     }
//! );
//!
//! fn main() {
//!     let config = r#"
//!         [SECTION1]
//!         a_string: i_am_a_string
//!         a_vector: [1, 2, 3]
//!         [SECTION2]
//!         a_i32: 12
//!         a_bool: true
//!     "#;
//!
//!     let mut file = File::create("PATH_TO_CONFIG.ini").unwrap();
//!     file.write_all(config.as_bytes()).unwrap();
//!     file.sync_all().unwrap();
//!
//!     let config = TestConfig::get_config("PATH_TO_CONFIG.ini").unwrap();
//!
//!     assert_eq!(config.SECTION1.a_string, "i_am_a_string");
//!     assert_eq!(config.SECTION1.a_vector, [1, 2, 3]);
//!     assert_eq!(config.SECTION2.a_i32, 12);
//!     assert_eq!(config.SECTION2.a_bool, true);
//!     std::fs::remove_file("PATH_TO_CONFIG.ini").unwrap();
//! }
//! ```
//! # Generated function [doc](../ov_config/struct.ExampleConfig.html).
//! See the [example config](../ov_config/struct.ExampleConfig.html) for generated function docs.

extern crate failure;
extern crate ini;
extern crate serde_json;

mod error;

pub use error::OVConfigError;
pub use ini::Ini;

/// The macro used to generate the configuration schema structure.
///
/// See the [crate level docs](../ov_config/index.html) for examples.
///
/// See the [example config](../ov_config/struct.ExampleConfig.html) for generated function docs.
///
#[macro_export]
macro_rules! make_config {
    (
        $name:ident,
        $(
            $section:ident {
                $($key:ident:$type:ty:$default_value:expr=>$closure:expr),*
            }
        );*
    ) => {
        mod ovconfig {
            use super::*;
            $(
                #[allow(non_camel_case_types)]
                #[derive(Debug, PartialEq)]
                pub struct $section{
                    $(pub $key: $type),*
                }

                impl $section {
                    /// Verification Function
                    pub fn verify(&self) -> Result<(), OVConfigError> {
                        $(
                            if !$closure(&self.$key) {
                                return Err(OVConfigError::BadValue{
                                    section:stringify!($section).into(),
                                    key:stringify!($key).into(),
                                    value: serde_json::to_string(&self.$key).unwrap_or("UNKONWN".into())
                                });
                            }
                        )*
                        Ok(())
                    }

                    pub fn get_config<T: AsRef<str> + ?Sized>(path: &T) -> Result<Self, OVConfigError> {
                        let ini =  Ini::load_from_file(path.as_ref())?;
                        Ok(Self{
                            $(
                                $key: match ini.get_from(Some(stringify!($section)), stringify!($key)) {
                                    None => $default_value,
                                    Some(v) => match stringify!($type) {
                                        "String" | "str" => serde_json::from_str(format!("\"{}\"", v).as_ref())?,
                                        _=> serde_json::from_str(v)?
                                    }
                                }
                            ),*
                        })
                    }

                }

                impl Default for $section {
                    fn default() -> Self {
                        Self {
                            $($key: $default_value),*
                        }
                    }
                }
            )*
        }

        #[allow(non_camel_case_types)]
        #[allow(non_snake_case)]
        #[derive(Debug, Default, PartialEq)]
        /// Configuration schema struct.
        ///
        /// Basically is a struct of all sections. User will need to use `Config.Section.Key` to access value.
        pub struct $name {
            pub c_p_a_t_h: String,
            $(pub $section: ovconfig::$section,)*
        }

        impl $name {
            /// Sanity check convenience function
            ///
            /// This function will exec the closure on each field with the input of the field's value.
            /// Change `c_p_a_t_h` will change the path that cached inthe configuration object.
            pub fn verify(&self) -> Result<(), OVConfigError> {
                $(self.$section.verify()?;)*
                Ok(())
            }

            fn get_config_impl<T:AsRef<str> + ?Sized>(path: &T) -> Result<Self, OVConfigError> {
                Ok(Self {
                    c_p_a_t_h: path.as_ref().into(),
                    $($section: ovconfig::$section::get_config(&path)?,)*
                })
            }

            /// Get configuration without auto verification.
            ///
            /// Will use default value if specific field is not found in the configuration file.
            ///
            /// # Argument:
            /// - path: Path to the configuration. This path will be cached in the object for refresh and flush.
            ///
            /// # Return:
            /// Will return configuration object on success.
            pub fn get_config_no_verify<T:AsRef<str> + ?Sized>(path: &T) -> Result<Self, OVConfigError> {
                Self::get_config_impl(path)
            }

            /// Get configuration with auto verification.
            ///
            /// Will use default value if specific field is not found in the configuration file.
            ///
            /// # Argument:
            /// - path: Path to the configuration. This path will be cached in the object for refresh and flush.
            ///
            /// # Return:
            /// Will return configuration object on success.
            pub fn get_config<T:AsRef<str> + ?Sized>(path: &T) -> Result<Self, OVConfigError> {
                let res = Self::get_config_impl(path)?;
                res.verify()?;
                Ok(res)
            }

            fn refresh_impl(&mut self) -> Result<(), OVConfigError> {
                $(self.$section = ovconfig::$section::get_config(&self.c_p_a_t_h)?;)*
                Ok(())
            }

            /// Read the configuration file and update current object.
            ///
            /// This function will automatically do sanity check on the value.
            pub fn refresh(&mut self) -> Result<(), OVConfigError>{
                self.refresh_impl()?;
                self.verify()?;
                Ok(())
            }

            /// Read the configuration file and update current object.
            ///
            /// This function will NOT automatically do sanity check on the value.
            pub fn refresh_no_verify(&mut self) -> Result<(), OVConfigError>{
                self.refresh_impl()?;
                Ok(())
            }

            fn flush_impl(&self) -> Result<(), OVConfigError> {
                let mut conf = Ini::new();
                $(
                    conf.with_section(Some(stringify!($section).to_string()))
                        $(.set(stringify!($key), serde_json::to_string(&self.$section.$key)?))*
                );*;

                conf.write_to_file(&self.c_p_a_t_h)?;
                Ok(())
            }

            /// Flush whatever in configuration object to file.
            ///
            /// This function will automatically do sanity check on the value.
            pub fn flush(&self) -> Result<(), OVConfigError> {
                self.verify()?;
                self.flush_impl()
            }

            /// Flush whatever in configuration object to file.
            ///
            /// This function will automatically do sanity check on the value.
            pub fn flush_no_verify(&self) -> Result<(), OVConfigError> {
                self.flush_impl()
            }
        }
    }
}

make_config!(ExampleConfig, Section {
    example:String:"example".into()=>|x: &String| x.len() > 0
});

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::File;
    use std::io::prelude::*;

    #[test]
    fn ovc_test_error() {
        let section = "section";
        let key = "key";
        let value = "bad_value";

        assert_eq!(
            format!(
                "OVConfigError: Bad [{}]::{}. Found: {}",
                section, key, value
            ),
            OVConfigError::BadValue {
                section: section.to_string(),
                key: key.to_string(),
                value: value.to_string(),
            }
            .to_string()
        );
    }

    make_config!(TestConfig, SECTION1 {
        a_string:String:"key1".into()=>|x: &String| x.len() > 0,
        a_vector:Vec<i32>:vec![1, 2, 3]=>|x: &Vec<i32>| x.len() < 4
    }; SECTION2 {
        a_i32:i32:15=>|x: &i32| *x < 20,
        a_bool:bool:true =>|x| vec![true, false].contains(x)
    });

    #[test]
    fn ovc_test_default() {
        let d = TestConfig {
            ..Default::default()
        };

        assert_eq!(d.SECTION1.a_string, "key1");
        assert_eq!(d.SECTION1.a_vector, vec![1, 2, 3]);
        assert_eq!(d.SECTION2.a_i32, 15);
        assert_eq!(d.SECTION2.a_bool, true);
        d.verify().unwrap();
    }

    #[test]
    fn ovc_test_verify() {
        let mut d = TestConfig {
            ..Default::default()
        };
        d.SECTION2.a_i32 = 50;
        match d.verify() {
            Ok(_) => panic!("Should not be OK"),
            Err(e) => assert_eq!(
                "OVConfigError: Bad [SECTION2]::a_i32. Found: 50",
                e.to_string()
            ),
        }
    }

    #[test]
    fn ovc_test_get_config() {
        let config = r#"
        [SECTION1]
        a_string: i_am_a_string
        a_vector: [1, 2, 3]
        [SECTION2]
        a_i32: 12
        a_bool: true
        "#;

        let mut file = File::create("ovc_test_get_config.ini").unwrap();
        file.write_all(config.as_bytes()).unwrap();
        file.sync_all().unwrap();

        let config = match TestConfig::get_config("ovc_test_get_config.ini") {
            Ok(c) => {
                std::fs::remove_file("ovc_test_get_config.ini").unwrap();
                c
            }
            Err(e) => {
                std::fs::remove_file("ovc_test_get_config.ini").unwrap();
                panic!(e);
            }
        };

        assert_eq!(config.SECTION1.a_string, "i_am_a_string");
        assert_eq!(config.SECTION1.a_vector, [1, 2, 3]);
        assert_eq!(config.SECTION2.a_i32, 12);
        assert_eq!(config.SECTION2.a_bool, true);
    }

    #[test]
    fn ovc_test_get_config_verify_failed() {
        let config = r#"
        [SECTION1]
        a_string: i_am_a_string
        a_vector: [1, 2, 3]
        [SECTION2]
        a_i32: 128
        a_bool: true
        "#;

        let mut file = File::create("ovc_test_get_config_verify_failed.ini").unwrap();
        file.write_all(config.as_bytes()).unwrap();
        file.sync_all().unwrap();

        match TestConfig::get_config("ovc_test_get_config_verify_failed.ini") {
            Ok(_) => {
                std::fs::remove_file("ovc_test_get_config_verify_failed.ini").unwrap();
                panic!("Should not be OK");
            }
            Err(e) => {
                std::fs::remove_file("ovc_test_get_config_verify_failed.ini").unwrap();
                assert_eq!(
                    "OVConfigError: Bad [SECTION2]::a_i32. Found: 128",
                    e.to_string()
                )
            }
        };
    }

    #[test]
    fn ovc_test_get_config_no_verify() {
        let config = r#"
        [SECTION1]
        a_string=i_am_a_string
        a_vector=[1, 2, 3]

        [SECTION2]
        a_i32=128
        a_bool=true
        "#;

        let mut file = File::create("ovc_test_get_config_no_verify.ini").unwrap();
        file.write_all(config.as_bytes()).unwrap();
        file.sync_all().unwrap();

        let config = match TestConfig::get_config_no_verify("ovc_test_get_config_no_verify.ini") {
            Ok(c) => {
                std::fs::remove_file("ovc_test_get_config_no_verify.ini").unwrap();
                c
            }
            Err(e) => {
                std::fs::remove_file("ovc_test_get_config_no_verify.ini").unwrap();
                panic!(e.to_string());
            }
        };

        assert_eq!(config.SECTION1.a_string, "i_am_a_string");
        assert_eq!(config.SECTION1.a_vector, [1, 2, 3]);
        assert_eq!(config.SECTION2.a_i32, 128);
        assert_eq!(config.SECTION2.a_bool, true);
    }

    #[test]
    fn ovc_test_refresh() {
        let config = r#"
        [SECTION1]
        a_string: i_am_a_string
        a_vector: [1, 2, 3]
        [SECTION2]
        a_i32: 12
        a_bool: true
        "#;

        let mut file = File::create("ovc_test_refresh.ini").unwrap();
        file.write_all(config.as_bytes()).unwrap();
        file.sync_all().unwrap();

        let mut config = TestConfig::get_config("ovc_test_refresh.ini").unwrap();

        assert_eq!(config.SECTION1.a_string, "i_am_a_string");
        assert_eq!(config.SECTION1.a_vector, [1, 2, 3]);
        assert_eq!(config.SECTION2.a_i32, 12);
        assert_eq!(config.SECTION2.a_bool, true);

        let cfg = r#"
        [SECTION1]
        a_string: i_am_a_string
        a_vector: [1, 2, 3]
        [SECTION2]
        a_i32: 13
        a_bool: true
        "#;

        let mut file = File::create("ovc_test_refresh.ini").unwrap();
        file.write_all(cfg.as_bytes()).unwrap();
        file.sync_all().unwrap();

        match config.refresh() {
            Ok(_) => std::fs::remove_file("ovc_test_refresh.ini").unwrap(),
            Err(e) => {
                std::fs::remove_file("ovc_test_refresh.ini").unwrap();
                panic!(e.to_string());
            }
        };
        assert_eq!(config.SECTION2.a_i32, 13);
    }

    #[test]
    fn ovc_test_refresh_verify_error() {
        let config = r#"
        [SECTION1]
        a_string: i_am_a_string
        a_vector: [1, 2, 3]
        [SECTION2]
        a_i32: 12
        a_bool: true
        "#;

        let mut file = File::create("ovc_test_refresh_verify_error.ini").unwrap();
        file.write_all(config.as_bytes()).unwrap();
        file.sync_all().unwrap();

        let mut config = TestConfig::get_config("ovc_test_refresh_verify_error.ini").unwrap();

        assert_eq!(config.SECTION1.a_string, "i_am_a_string");
        assert_eq!(config.SECTION1.a_vector, [1, 2, 3]);
        assert_eq!(config.SECTION2.a_i32, 12);
        assert_eq!(config.SECTION2.a_bool, true);

        let cfg = r#"
        [SECTION1]
        a_string: i_am_a_string
        a_vector: [1, 2, 3]
        [SECTION2]
        a_i32: 139
        a_bool: true
        "#;

        let mut file = File::create("ovc_test_refresh_verify_error.ini").unwrap();
        file.write_all(cfg.as_bytes()).unwrap();
        file.sync_all().unwrap();

        match config.refresh() {
            Ok(_) => {
                std::fs::remove_file("ovc_test_refresh_verify_error.ini").unwrap();
                panic!("Should not be OK.");
            }
            Err(e) => {
                std::fs::remove_file("ovc_test_refresh_verify_error.ini").unwrap();
                assert_eq!(
                    "OVConfigError: Bad [SECTION2]::a_i32. Found: 139",
                    e.to_string()
                );
            }
        };
    }

    #[test]
    fn ovc_test_refresh_no_verify() {
        let config = r#"
        [SECTION1]
        a_string: i_am_a_string
        a_vector: [1, 2, 3]
        [SECTION2]
        a_i32: 12
        a_bool: true
        "#;

        let mut file = File::create("ovc_test_refresh_no_verify.ini").unwrap();
        file.write_all(config.as_bytes()).unwrap();
        file.sync_all().unwrap();

        let mut config = TestConfig::get_config("ovc_test_refresh_no_verify.ini").unwrap();

        assert_eq!(config.SECTION1.a_string, "i_am_a_string");
        assert_eq!(config.SECTION1.a_vector, [1, 2, 3]);
        assert_eq!(config.SECTION2.a_i32, 12);
        assert_eq!(config.SECTION2.a_bool, true);

        let cfg = r#"
        [SECTION1]
        a_string: i_am_a_string
        a_vector: [1, 2, 3]
        [SECTION2]
        a_i32: 130
        a_bool: true
        "#;

        let mut file = File::create("ovc_test_refresh_no_verify.ini").unwrap();
        file.write_all(cfg.as_bytes()).unwrap();
        file.sync_all().unwrap();

        match config.refresh_no_verify() {
            Ok(_) => std::fs::remove_file("ovc_test_refresh_no_verify.ini").unwrap(),
            Err(e) => {
                std::fs::remove_file("ovc_test_refresh_no_verify.ini").unwrap();
                panic!(e.to_string());
            }
        };
        assert_eq!(config.SECTION2.a_i32, 130);
    }

    #[test]
    fn ovc_test_flush() {
        let mut d = TestConfig {
            ..Default::default()
        };

        d.c_p_a_t_h = "ovc_test_flush.ini".into();
        d.flush().unwrap();
        assert!(std::path::Path::new("ovc_test_flush.ini").exists());
        let config = TestConfig::get_config("ovc_test_flush.ini").unwrap();
        assert_eq!(d, config);
        std::fs::remove_file("ovc_test_flush.ini").unwrap();
    }

    #[test]
    fn ovc_test_flush_failed() {
        let mut d = TestConfig {
            ..Default::default()
        };
        d.SECTION2.a_i32 = 50;
        d.c_p_a_t_h = "ovc_test_flush_failed.ini".into();
        match d.flush() {
            Ok(_) => panic!("Should not be OK"),
            Err(e) => assert_eq!(
                "OVConfigError: Bad [SECTION2]::a_i32. Found: 50",
                e.to_string()
            ),
        };
        assert!(!std::path::Path::new("ovc_test_flush_failed.ini").exists());
    }

    #[test]
    fn ovc_test_flush_no_verfiy() {
        let mut d = TestConfig {
            ..Default::default()
        };
        d.SECTION2.a_i32 = 50;
        d.c_p_a_t_h = "ovc_test_flush_no_verfiy.ini".into();
        d.flush_no_verify().unwrap();
        assert!(std::path::Path::new("ovc_test_flush_no_verfiy.ini").exists());
        let config = TestConfig::get_config_no_verify("ovc_test_flush_no_verfiy.ini").unwrap();
        assert_eq!(d, config);
        std::fs::remove_file("ovc_test_flush_no_verfiy.ini").unwrap();
    }
}