sterling_ops/
config.rs

1use std::convert::From;
2use std::error::Error;
3use std::fmt::{self, Display, Formatter};
4use std::fs::File;
5use std::io::{self, BufReader, ErrorKind};
6
7use serde_yaml;
8
9use currency::Currency;
10
11pub fn load_config(filename: &str) -> Result<Vec<Currency>, ConfigError> {
12    let config_file = File::open(filename)?;
13    let config: Vec<Currency> = serde_yaml::from_reader(BufReader::new(config_file))?;
14
15    Ok(config)
16}
17
18pub fn parse_currency_config(
19    config_result: Result<Vec<Currency>, ConfigError>,
20    config_file_path: Option<&str>,
21) -> Result<Vec<Currency>, String> {
22    match config_result {
23        Ok(values) => Ok(values),
24        Err(error) => match error.kind {
25            ErrorKind::NotFound => {
26                if let Some(file_path) = config_file_path {
27                    Err(format!(
28                        "Sterling Error: Can't find configuration file: \"{}\"",
29                        &file_path
30                    ))
31                } else {
32                    Ok(silver_standard_config())
33                }
34            }
35            _ => Err(format!("Sterling Error: {}", error)),
36        },
37    }
38}
39
40pub fn phb_config() -> Vec<Currency> {
41    vec![
42        Currency::new("platinum", 1000, "p", None, None),
43        Currency::new("gold", 100, "g", None, None),
44        Currency::new("electrum", 50, "e", None, Some(true)),
45        Currency::new("silver", 10, "s", None, None),
46        Currency::new("copper", 1, "c", None, None),
47    ]
48}
49
50fn silver_standard_config() -> Vec<Currency> {
51    vec![
52        Currency::new("platinum", 1_000_000, "p", None, None),
53        Currency::new("gold", 10_000, "g", None, None),
54        Currency::new("silver", 100, "s", None, None),
55        Currency::new("copper", 1, "c", None, None),
56    ]
57}
58
59#[derive(Debug)]
60pub struct ConfigError {
61    desc: String,
62    pub kind: ErrorKind,
63}
64
65impl Display for ConfigError {
66    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
67        write!(f, "Sterling Error: {}", self.desc)
68    }
69}
70
71impl Error for ConfigError {
72    fn description(&self) -> &str {
73        &self.desc
74    }
75}
76
77impl From<io::Error> for ConfigError {
78    fn from(error: io::Error) -> Self {
79        ConfigError {
80            desc: error.description().to_owned(),
81            kind: error.kind(),
82        }
83    }
84}
85
86impl From<serde_yaml::Error> for ConfigError {
87    fn from(error: serde_yaml::Error) -> Self {
88        ConfigError {
89            desc: error.description().to_owned(),
90            kind: ErrorKind::Other,
91        }
92    }
93}