gloss_utils/
config.rs

1// use config_manager::{config, ConfigInit};
2// use config::{File, FileStoredFormat, Format, Map, Value, ValueKind};
3use config::{ConfigError, FileStoredFormat, Format, Map, Value, ValueKind};
4// use serde::de::Unexpected;
5use std::error::Error;
6// use std::io::{Error, ErrorKind};
7
8#[derive(Debug, Clone)]
9pub struct MyTomlFile;
10
11impl Format for MyTomlFile {
12    fn parse(&self, uri: Option<&String>, text: &str) -> Result<Map<String, Value>, Box<dyn Error + Send + Sync>> {
13        let value = from_toml_value(uri, &toml::from_str(text)?);
14
15        // Have a proper error fire if the root of a file is ever not a Table
16        // https://github.com/mehcode/config-rs/blob/master/src/format.rs#L28
17        match value.kind {
18            ValueKind::Table(map) => Ok(map),
19            _ => Err(ConfigError::Message("The config is not a table".to_string())),
20        }
21        .map_err(|err| Box::new(err) as Box<dyn Error + Send + Sync>)
22    }
23}
24// A slice of extensions associated to this format, when an extension
25// is omitted from a file source, these will be tried implicitly:
26impl FileStoredFormat for MyTomlFile {
27    fn file_extensions(&self) -> &'static [&'static str] {
28        &["toml"]
29    }
30}
31
32//pretty much all from https://github.com/mehcode/config-rs/blob/master/src/file/format/toml.rs
33//the adition is that the word "auto" is set to nil so that we know to
34// automatically set that value later
35fn from_toml_value(uri: Option<&String>, value: &toml::Value) -> Value {
36    match *value {
37        toml::Value::String(ref value) => {
38            if value.to_string().to_lowercase() == "auto" {
39                Value::new(uri, ValueKind::Nil)
40            } else {
41                Value::new(uri, value.to_string())
42            }
43        }
44        toml::Value::Float(value) => Value::new(uri, value),
45        toml::Value::Integer(value) => Value::new(uri, value),
46        toml::Value::Boolean(value) => Value::new(uri, value),
47
48        toml::Value::Table(ref table) => {
49            let mut m = Map::new();
50
51            for (key, value) in table {
52                m.insert(key.clone(), from_toml_value(uri, value));
53            }
54
55            Value::new(uri, m)
56        }
57
58        toml::Value::Array(ref array) => {
59            let mut l = Vec::new();
60
61            for value in array {
62                l.push(from_toml_value(uri, value));
63            }
64
65            Value::new(uri, l)
66        }
67
68        toml::Value::Datetime(ref datetime) => Value::new(uri, datetime.to_string()),
69    }
70}