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
// Copyright (C) 2014-2015 Mickaël Salaün
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

use rustc_serialize::Decodable;
use std::fs;
use std::io::Read;
use std::path::Path;
use std::sync::Arc;
use stemflow::{Domain, FileAccess};
use toml;

pub use self::error::ConfigError;

mod error;

pub mod portal;
pub mod profile;

pub type ArcDomain = Arc<Domain<Arc<FileAccess>>>;

// TODO: Check for absolute path only
pub fn get_config<T, U>(config_file: T) -> Result<U, ConfigError>
        where T: AsRef<Path>, U: Decodable {
    let mut contents = String::new();
    let _ = try!(fs::File::open(config_file)).read_to_string(&mut contents);
    let mut parser = toml::Parser::new(contents.as_ref());
    let toml = match parser.parse() {
        Some(r) => toml::Value::Table(r),
        None => return Err(ConfigError::new(format!("Parse error: {:?}", parser.errors))),
    };
    let mut decoder = toml::Decoder::new(toml);
    let config = try!(Decodable::decode(&mut decoder));
    Ok(config)
}

pub fn get_configs<T, U>(profile_dir: T) -> Result<Vec<U>, ConfigError>
        where T: AsRef<Path>, U: Decodable {
    let mut ret = vec!();
    for file in try!(fs::read_dir(profile_dir)) {
        let file = try!(file).path();
        match file.extension() {
            Some(ext) => {
                if ext == "toml" {
                    match get_config(&file) {
                        Ok(c) => ret.push(c),
                        Err(e) => return Err(ConfigError::new(format!("(file `{}`) {}",
                                             file.display(), e))),
                    };
                }
            },
            None => {}
        }
    }
    Ok(ret)
}