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
174
use std::{collections::HashMap, fmt::Display, path::PathBuf, str::FromStr};
use config::{builder::DefaultState, Config, ConfigBuilder, ConfigError, FileFormat, Value};
use serde::{Deserialize, Serialize};
pub type SettingsError = config::ConfigError;
#[derive(Default, Debug)]
pub struct SettingsBuilder {
config_builder: ConfigBuilder<DefaultState>,
mod_paths: HashMap<String, PathBuf>,
}
impl SettingsBuilder {
#[allow(clippy::result_large_err)]
pub fn add_file<T: AsRef<str>>(
mut self,
filename: T,
required: bool,
) -> Result<Self, (Self, SettingsError)> {
let source = config::File::new(filename.as_ref(), FileFormat::Toml).required(required);
let config = match Config::builder().add_source(source).build() {
Ok(config) => config,
Err(e) => return Err((self, e)),
};
let mods: HashMap<String, Value> = config.get("mod").unwrap_or_default();
for (name, _) in mods {
self.mod_paths.insert(
name,
PathBuf::from_str(filename.as_ref())
.unwrap() .parent()
.unwrap() .to_owned(),
);
}
Ok(Self {
config_builder: self.config_builder.add_source(config),
mod_paths: self.mod_paths,
})
}
#[allow(dead_code)]
pub fn add_string<T: AsRef<str>>(self, string: T) -> Self {
Self {
config_builder: self
.config_builder
.add_source(config::File::from_str(string.as_ref(), FileFormat::Toml)),
mod_paths: self.mod_paths,
}
}
pub fn build(self) -> Result<Settings, ConfigError> {
Ok(Settings {
config: self.config_builder.build()?,
mod_paths: self.mod_paths,
})
}
}
fn mod_default_enablement() -> bool {
true
}
#[derive(Serialize, Deserialize)]
pub struct Mod {
pub file_root: Option<String>,
#[serde(default = "mod_default_enablement")]
pub enabled: bool,
#[serde(default = "Vec::new")]
pub scripts: Vec<String>,
}
pub struct Settings {
config: Config,
mod_paths: HashMap<String, PathBuf>,
}
impl Display for Settings {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let toml = format!(
"{}",
self.config
.clone()
.try_deserialize::<toml::Value>()
.unwrap()
);
if toml.is_empty() {
f.write_str("<empty>")?;
} else {
f.write_str(&toml)?;
}
Ok(())
}
}
impl Settings {
pub fn mods(&self) -> HashMap<String, Mod> {
self.config.get("mod").unwrap_or_default()
}
pub fn mod_path<S: AsRef<str>>(&self, name: S) -> Option<PathBuf> {
self.mod_paths.get(name.as_ref()).cloned()
}
}
#[cfg(test)]
mod tests {
use std::error::Error;
use super::*;
#[test]
fn mod_config_is_additive() {
let settings = SettingsBuilder::default()
.add_string(
r#"
[mod.a]
file_root = "abc"
"#,
)
.add_string(
r#"
[mod.b]
file_root = "def"
"#,
)
.build()
.expect("failed to build test config for mod_config_is_additive");
let mods = settings.mods();
assert_eq!(mods.len(), 2);
assert_eq!(mods["a"].file_root, Some("abc".to_owned()));
assert_eq!(mods["b"].file_root, Some("def".to_owned()));
}
#[test]
fn mod_config_is_enabled_by_default() {
let settings = SettingsBuilder::default()
.add_string(
r#"
[mod.a]
file_root = "abc"
"#,
)
.build()
.expect("failed to build test config for mod_config_is_enabled_by_default");
let mods = settings.mods();
assert!(mods["a"].enabled);
}
#[test]
fn mod_path_is_remembered() -> Result<(), Box<dyn Error>> {
let root = format!("{}/test-data/", env!("CARGO_MANIFEST_DIR"));
let settings = SettingsBuilder::default()
.add_file(format!("{}/mod-path-is-remembered.toml", root), true)
.expect("failed to load test config file for mod_path_is_remembered")
.build()
.expect("failed to build test config for mod_path_is_remembered");
assert_eq!(PathBuf::from_str(&root).ok(), settings.mod_path("a"));
Ok(())
}
}