comparison rust/src/config.rs @ 639:89818a14648b rust tip

- switch to using anyhow for errors, surf for http runs but surf has problems
author Matt Johnston <matt@ucc.asn.au>
date Thu, 28 Nov 2019 23:57:00 +0800
parents 43eb3cfdf769
children
comparison
equal deleted inserted replaced
638:a9f353f488d0 639:89818a14648b
1 use serde::{Serialize,Deserialize}; 1 use serde::{Serialize,Deserialize};
2 2 use anyhow::{Context, anyhow, Result, Error};
3 use super::types::*;
4 3
5 #[derive(Deserialize,Serialize,Debug,Clone)] 4 #[derive(Deserialize,Serialize,Debug,Clone)]
6 pub struct Config { 5 pub struct Config {
7 pub sensor_sleep: u64, 6 pub sensor_sleep: u64,
8 pub upload_sleep: u64, 7 pub upload_sleep: u64,
31 impl Config { 30 impl Config {
32 pub fn default_toml() -> &'static str { 31 pub fn default_toml() -> &'static str {
33 include_str!("defconfig.toml") 32 include_str!("defconfig.toml")
34 } 33 }
35 34
36 pub fn load(conf_file: &str) -> Result<Self, TemplogError> { 35 pub fn load(conf_file: &str) -> Result<Self> {
37 let mut c = config::Config::default(); 36 let mut c = config::Config::default();
38 c.merge(config::File::from_str(Self::default_toml(), config::FileFormat::Toml)).expect("Bad default config"); 37 c.merge(config::File::from_str(Self::default_toml(), config::FileFormat::Toml)).expect("Bad default config");
39 c.merge(config::File::with_name(conf_file)).or_else(|e| { 38 c.merge(config::File::with_name(conf_file)).or_else(|e| {
40 Err(match e { 39 Err(match e {
41 config::ConfigError::NotFound(_) => TemplogError::new(&format!("Missing config {}", conf_file)), 40 config::ConfigError::NotFound(_) => anyhow!("Missing config {}", conf_file),
42 _ => TemplogError::new(&format!("Problem parsing {}: {}", conf_file, e)), 41 // XXX this is ugly, why won't e.with_context() work?
42 _ => Error::new(e).context(format!("Problem parsing {}", conf_file)),
43 }) 43 })
44 })?; 44 })?;
45 c.merge(config::Environment::with_prefix("TEMPLOG")).unwrap(); 45 c.merge(config::Environment::with_prefix("TEMPLOG"))
46 c.try_into().or_else(|e| Err(TemplogError::new(&format!("Problem loading config {}: {}", conf_file, e)))) 46 .context("Failed loading from TEMPLOG_ environment variables")?;
47 Ok(c.try_into().with_context(|| format!("Problem loading config {}", conf_file))?)
47 } 48 }
48 } 49 }