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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
use std::{fs, path::Path, str::FromStr};
use crate::{Entry, generate_builder_method, LibSDBootConfError};
#[derive(Default, Debug)]
pub struct Config {
pub default: Option<String>,
pub timeout: Option<u32>,
}
impl FromStr for Config {
type Err = LibSDBootConfError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut config = Self::default();
let lines = s.lines();
for line in lines {
if line.starts_with('#') {
continue;
}
let mut parts = line.splitn(2, ' ');
let key = parts.next().ok_or(LibSDBootConfError::ConfigParseError)?;
let value = parts.next().ok_or(LibSDBootConfError::ConfigParseError)?;
match key {
"default" => config.default = Some(value.to_string()),
"timeout" => config.timeout = Some(value.parse().unwrap_or_default()),
_ => continue,
}
}
Ok(config)
}
}
impl ToString for Config {
fn to_string(&self) -> String {
let mut buffer = String::new();
if let Some(default) = &self.default {
buffer.push_str(&format!("default {}\n", default));
}
if let Some(timeout) = &self.timeout {
buffer.push_str(&format!("timeout {}\n", timeout));
}
buffer
}
}
impl Config {
pub fn new<S: Into<String>>(default: Option<S>, timeout: Option<u32>) -> Config {
Config {
default: default.map(|x| x.into()),
timeout,
}
}
pub fn load<P: AsRef<Path>>(path: P) -> Result<Config, LibSDBootConfError> {
Config::from_str(&fs::read_to_string(path.as_ref())?)
}
pub fn write<P: AsRef<Path>>(&self, path: P) -> Result<(), LibSDBootConfError> {
fs::write(path.as_ref(), self.to_string())?;
Ok(())
}
pub fn set_default(&mut self, default: &Entry) {
self.default = Some(default.id.to_owned());
}
}
#[derive(Default, Debug)]
pub struct ConfigBuilder {
config: Config,
}
impl ConfigBuilder {
pub fn new() -> Self {
Self {
config: Config::default(),
}
}
generate_builder_method!(
option REAL(config) default(S => String)
);
generate_builder_method!(
option REAL(config) timeout(U => u32)
);
pub fn default_entry(mut self, entry: &Entry) -> Self {
self.config.set_default(entry);
self
}
pub fn build(self) -> Config {
self.config
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_builder() {
let entry = ConfigBuilder::new().default("5.12.0-aosc-main").build();
println!("{:?}", &entry);
}
}