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
use std::vec::Vec;
use std::str;
use std::fs;
pub struct Configuration {
file_buffer: String,
}
pub struct NoConfiguration {
}
trait GetOptionTrait {
fn get_option(self, option_name: &str) -> Result<String, ()>;
}
impl GetOptionTrait for NoConfiguration {
fn get_option(self, _option_name: &str) -> Result<String, ()> {
Err(())
}
}
impl GetOptionTrait for Configuration {
fn get_option(self, option_name: &str) -> Result<String, ()> {
if option_name.split_whitespace().collect::<Vec<&str>>().len() > 1 {
return Err(());
}
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());
}
}
Err(())
}
}
impl Configuration {
pub fn new(paths: &[&str]) -> Result<Configuration, NoConfiguration> {
let mut filepath = String::from("");
for path in paths {
match fs::metadata(path) {
Ok(v) => match v.is_file() {
true => {
filepath = path.to_string();
break;
},
false => continue,
},
Err(_e) => continue,
}
}
match filepath {
s if s.is_empty() => return Err(NoConfiguration {} ),
_ => return Ok(Configuration { file_buffer: fs::read_to_string(filepath).unwrap(), }),
}
}
}
impl Clone for Configuration {
fn clone(&self) -> Configuration {
Configuration { file_buffer: self.file_buffer.clone() }
}
}