|
| 1 | +use config::{Config, File}; |
| 2 | +use lazy_static::lazy_static; |
| 3 | +use serde_derive::Deserialize; |
| 4 | +use std::sync::RwLock; |
| 5 | + |
| 6 | +lazy_static! { |
| 7 | + static ref SETTINGS: RwLock<Settings> = RwLock::new(Settings::new()); |
| 8 | +} |
| 9 | + |
| 10 | + |
| 11 | +#[derive(Default, Clone, Deserialize)] |
| 12 | +struct Cred { |
| 13 | + user: String, |
| 14 | + key: String, |
| 15 | +} |
| 16 | + |
| 17 | +#[derive(Default, Clone, Deserialize)] |
| 18 | +pub struct Settings { |
| 19 | + verbose: Option<u8>, |
| 20 | + cred: Option<Cred>, |
| 21 | +} |
| 22 | + |
| 23 | + |
| 24 | +fn build_config(file: &str) -> Settings { |
| 25 | + let s = Config::builder() |
| 26 | + // Configuration file |
| 27 | + .add_source(File::with_name(file).required(false)) |
| 28 | + .build() |
| 29 | + .expect("Config build failed"); |
| 30 | + |
| 31 | + // Deserialize (and thus freeze) the entire configuration |
| 32 | + s.try_deserialize().unwrap() |
| 33 | +} |
| 34 | + |
| 35 | +impl Settings { |
| 36 | + fn new() -> Self { |
| 37 | + let settings: Settings = Default::default(); |
| 38 | + settings |
| 39 | + } |
| 40 | + |
| 41 | + pub fn init(cfgfile: Option<&str>) { |
| 42 | + let file = match cfgfile { |
| 43 | + Some(x) => x, |
| 44 | + None => "config.toml" |
| 45 | + }; |
| 46 | + |
| 47 | + let mut new_settings = SETTINGS.write().unwrap(); |
| 48 | + *new_settings = build_config(file); |
| 49 | + } |
| 50 | + |
| 51 | + pub fn user() -> Result<String, String> { |
| 52 | + match &SETTINGS.read().unwrap().cred { |
| 53 | + Some(c) => Ok(c.user.clone()), |
| 54 | + None => Err(format!("Credential config is missing")) |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + pub fn key() -> Result<String, String> { |
| 59 | + match &SETTINGS.read().unwrap().cred { |
| 60 | + Some(c) => Ok(c.key.clone()), |
| 61 | + None => Err(format!("Credential config is missing")) |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + pub fn verbosity() -> u8 { |
| 66 | + match SETTINGS.read().unwrap().verbose { |
| 67 | + Some(v) => v, |
| 68 | + None => 0 |
| 69 | + } |
| 70 | + } |
| 71 | +} |
| 72 | + |
0 commit comments