summaryrefslogtreecommitdiffstats
path: root/src/file.rs
blob: 2ffc836cabc3c0ca7ee615256c226fe23c59034c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
use std::fs;
use std::env;
use std::error::Error;
use std::io::Read;
use std::collections::HashMap;

use toml;

use value::Value;
use source::Source;

#[derive(Default)]
pub struct File {
    /// Basename of configuration file
    name: String,

    /// Directory where configuration file is found
    /// When not specified, the current working directory (CWD) is considered
    path: Option<String>,

    /// Namespace to restrict configuration from the file
    namespace: Option<String>,

    /// A required File will error if it cannot be found
    required: bool,
}

impl File {
    pub fn with_name(name: &str) -> File {
        File {
            name: name.into(),
            required: true,

            ..Default::default()
        }
    }

    pub fn path(&mut self, path: &str) -> &mut File {
        self.path = Some(path.into());
        self
    }

    pub fn namespace(&mut self, namespace: &str) -> &mut File {
        self.namespace = Some(namespace.into());
        self
    }

    pub fn required(&mut self, required: bool) -> &mut File {
        self.required = required;
        self
    }
}

fn toml_collect(content: &mut HashMap<String, Value>,
                table: &toml::Table,
                prefix: Option<String>) {
    for (key, value) in table {
        // Construct full key from prefix
        let key = if let Some(ref prefix) = prefix {
            prefix.clone() + "." + key
        } else {
            key.clone()
        };

        match *value {
            // Recurse into nested table
            toml::Value::Table(ref table) => toml_collect(content, table, Some(key)),

            toml::Value::String(ref value) => {
                content.insert(key, value.clone().into());
            }

            toml::Value::Integer(value) => {
                content.insert(key, value.into());
            }

            toml::Value::Float(value) => {
                content.insert(key, value.into());
            }

            toml::Value::Boolean(value) => {
                content.insert(key, value.into());
            }

            _ => {
                // Unhandled
            }
        }
    }
}

impl Source for File {
    fn build(&mut self) -> Result<HashMap<String, Value>, Box<Error>> {
        let mut content = HashMap::new();

        // Find file
        // TODO: Use a nearest algorithm rather than strictly CWD
        let cwd = match env::current_dir() {
            Ok(cwd) => cwd,
            Err(err) => {
                if self.required {
                    return Err(From::from(err));
                } else {
                    return Ok(content);
                }
            }
        };

        let filename = cwd.join(self.name.clone() + ".toml");

        // Read contents from file
        let mut file = match fs::File::open(filename) {
            Ok(file) => file,
            Err(err) => {
                if self.required {
                    return Err(From::from(err));
                } else {
                    return Ok(content);
                }
            }
        };

        let mut buffer = String::new();
        let res = file.read_to_string(&mut buffer);
        if res.is_err() {
            if self.required {
                return Err(From::from(res.err().unwrap()));
            } else {
                return Ok(content);
            }
        }

        // Parse
        let mut parser = toml::Parser::new(&buffer);
        // TODO: Get a solution to make this return an Error-able
        let document = parser.parse().unwrap();

        // Iterate through document and fill content
        toml_collect(&mut content, &document, None);

        Ok(content)
    }
}