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
use getopts::Options;
use std::env;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use toml;
use toml::Value;
static PATH: &str = "/home/system/etc/config.toml";
static IP: &str = "127.0.0.1";
const PORT: u16 = 8080;
#[derive(Debug, Deserialize)]
pub struct Address {
ip: String,
port: u16,
}
impl Default for Address {
fn default() -> Self {
Address {
ip: IP.to_string(),
port: PORT,
}
}
}
#[derive(Debug)]
pub struct Config {
addr: Address,
raw: Value,
}
impl Default for Config {
fn default() -> Self {
Config {
addr: Address::default(),
raw: Value::String("".to_string()),
}
}
}
impl Config {
pub fn new(name: &str) -> Self {
parse_config(name, get_config_path()).unwrap_or(Config::default())
}
pub fn hosturl(&self) -> String {
format!("{}:{}", self.addr.ip, self.addr.port)
}
pub fn raw(&self) -> toml::Value {
self.raw.clone()
}
pub fn get(&self, key: &str) -> Option<toml::Value> {
match self.raw.get(key) {
Some(v) => Some(v.clone()),
None => None,
}
}
}
fn get_config_path() -> String {
let args: Vec<String> = env::args().collect();
let mut opts = Options::new();
opts.optopt("c", "config", "Path to config file", "CONFIG");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!(f.to_string()),
};
match matches.opt_str("c") {
Some(s) => s,
None => PATH.to_string(),
}
}
fn get_file_data(path: String) -> Result<String, io::Error> {
let mut contents = String::new();
let mut file = File::open(path)?;
file.read_to_string(&mut contents)?;
Ok(contents)
}
fn parse_config(name: &str, path: String) -> Result<Config, toml::de::Error> {
let contents = get_file_data(path).unwrap_or("".to_string());
let data: Value = toml::from_str(&contents)?;
let mut config = Config::default();
if let Some(data) = data.get(name) {
if let Some(address) = data.get("addr") {
config.addr = address.clone().try_into()?;
}
config.raw = data.clone();
}
Ok(config)
}