1use std::fmt;
4use std::env;
5use std::io::Read;
6use std::fs::File;
7use std::path::Path;
8use serde_json::{self, Map, Value};
9
10#[derive(Clone)]
32pub struct Config {
33 config: serde_json::Map<String, Value>,
34}
35
36impl Default for Config {
37 fn default() -> Config {
38 Config::new()
39 }
40}
41
42impl Config {
43 pub fn new() -> Config {
45 let json_object: Map<String, Value> = Map::new();
46 Config {
47 config: json_object,
48 }
49 }
50
51 pub fn set(&mut self, key: &str, value: Value) {
53 self.config.insert(key.to_string(), value);
54 }
55
56 pub fn get(&self, key: &str) -> Option<&Value> {
58 self.config.get(&key.to_string())
59 }
60
61 pub fn get_boolean(&self, key: &str, default: bool) -> bool {
65 match self.get(key) {
66 Some(value) => {
67 match *value {
68 Value::Bool(value) => value,
69 _ => default
70 }
71 },
72 None => default
73 }
74 }
75
76 pub fn from_envvar(&mut self, variable_name: &str) {
79 match env::var(variable_name) {
80 Ok(value) => self.from_jsonfile(&value),
81 Err(_) => panic!("The environment variable {} is not set.", variable_name),
82 }
83 }
84
85 pub fn from_jsonfile(&mut self, filepath: &str) {
87 let path = Path::new(filepath);
88 let mut file = File::open(&path).unwrap();
89 let mut content = String::new();
90 file.read_to_string(&mut content).unwrap();
91 let object: Value = serde_json::from_str(&content).unwrap();
92 match object {
93 Value::Object(object) => { self.from_object(object); },
94 _ => { panic!("The configuration file is not an JSON object."); }
95 }
96 }
97
98 pub fn from_object(&mut self, object: Map<String, Value>) {
100 for (key, value) in &object {
101 self.set(&key, value.clone());
102 }
103 }
104}
105
106impl fmt::Debug for Config {
107 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
108 write!(f, "<Pencil Config {:?}>", self.config)
109 }
110}