ice_rs/
properties.rs

1use pest::Parser;
2use std::collections::BTreeMap;
3use std::path::Path;
4use std::fs::File;
5use std::io::prelude::*;
6
7
8#[derive(Parser)]
9#[grammar = "iceconfig.pest"]
10pub struct PropertyParser;
11
12#[derive(Clone)]
13pub struct Properties {
14    properties: BTreeMap<String, String>
15}
16
17impl Properties {
18    pub fn new() -> Properties {
19        Properties {
20            properties: BTreeMap::new()
21        }
22    }
23
24    pub fn get(&self, key: &str) -> Option<&String> {
25        return self.properties.get(key)
26    }
27
28    pub fn has(&self, key: &str) -> bool {
29        return self.properties.contains_key(key)
30    }
31
32    pub fn load(&mut self, config_file: &str) -> Result<(), Box<dyn std::error::Error>> {
33        let mut content = String::new();
34        let mut file = File::open(Path::new(&config_file))?;
35        file.read_to_string(&mut content)?;
36        let mut pairs = PropertyParser::parse(Rule::iceconfig, &content).unwrap();
37        let mut key = "";
38
39        let config = pairs.next().unwrap();
40        if config.as_rule() == Rule::iceconfig {
41            for pair in config.into_inner() {
42                match pair.as_rule() {
43                    Rule::property_key => {
44                        key = pair.as_str();
45                    }
46                    Rule::property_value => {
47                        self.properties.insert(String::from(key), String::from(pair.as_str()));
48                    }
49                    _ => {}
50                }
51            }
52        }
53
54        Ok(())
55    }
56}