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
use std::vec::Vec;
use std::str;
use std::fs;

/// A struct that contains a file buffer which represents a configuration
/// file. It can then be used to read options from.
pub struct Configuration {
    file_buffer: String,
}

impl Clone for Configuration {
    fn clone(&self) -> Configuration {
        Configuration { file_buffer: self.file_buffer.clone() }
    }
}

impl Configuration {

    /// The creator for Configuration struct, it takes an array of filepaths
    /// and then reads from the first one that's valid. It then returns
    /// A configuration struct with the files configuration.
    pub fn new(paths: &[&str]) -> Result<Self, std::io::Error> {
        let mut filepath = "";
        for path in paths {
            if fs::metadata(path)?.is_file() {
                filepath = path;
                break;
            }
        }
        return Ok(Configuration {
            file_buffer: fs::read_to_string(filepath)?,
        });
    }

    /// Takes the name of an option and returns the value as a String
    pub fn get_option(self, option_name: &str) -> Result<String, ()> {
        for line in self.file_buffer.lines() {
            let splits: Vec<&str> = line.split_whitespace().collect();
            if splits.len() < 2 {
                return Err(());
            }
            if splits[0].to_string() == option_name {
                return Ok(splits[1].to_string());
            }
        }
        return Err(());
    }

}