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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
use crate::CmdLine;
use config::ConfigError;
type ConfigBuilder = config::builder::ConfigBuilder<config::builder::DefaultState>;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Default)]
pub struct ConfigurationSources {
files: Vec<(PathBuf, MustRead)>,
options: Vec<String>,
mistrust: fs_mistrust::Mistrust,
}
#[derive(Clone, Debug, Copy, Eq, PartialEq)]
enum MustRead {
TolerateAbsence,
MustRead,
}
impl ConfigurationSources {
pub fn new_empty() -> Self {
Self::default()
}
pub fn from_cmdline<F, O>(
default_config_file: impl Into<PathBuf>,
config_files_options: impl IntoIterator<Item = F>,
cmdline_toml_override_options: impl IntoIterator<Item = O>,
) -> Self
where
F: Into<PathBuf>,
O: Into<String>,
{
let mut cfg_sources = ConfigurationSources::new_empty();
let mut any_files = false;
for f in config_files_options {
let f = f.into();
cfg_sources.push_file(f);
any_files = true;
}
if !any_files {
let default = default_config_file.into();
cfg_sources.push_optional_file(default);
}
for s in cmdline_toml_override_options {
cfg_sources.push_option(s);
}
cfg_sources
}
pub fn push_file(&mut self, p: impl Into<PathBuf>) {
self.files.push((p.into(), MustRead::MustRead));
}
pub fn push_optional_file(&mut self, p: impl Into<PathBuf>) {
self.files.push((p.into(), MustRead::TolerateAbsence));
}
pub fn push_option(&mut self, option: impl Into<String>) {
self.options.push(option.into());
}
pub fn set_mistrust(&mut self, mistrust: fs_mistrust::Mistrust) {
self.mistrust = mistrust;
}
pub fn mistrust(&self) -> &fs_mistrust::Mistrust {
&self.mistrust
}
pub fn files(&self) -> impl Iterator<Item = &Path> {
self.files.iter().map(|(f, _)| f.as_path())
}
pub fn load(&self) -> Result<config::Config, ConfigError> {
let mut builder = config::Config::builder();
builder = add_sources(builder, &self.mistrust, &self.files, &self.options)?;
builder.build()
}
}
fn add_sources<P>(
mut builder: ConfigBuilder,
mistrust: &fs_mistrust::Mistrust,
files: &[(P, MustRead)],
opts: &[String],
) -> Result<ConfigBuilder, ConfigError>
where
P: AsRef<Path>,
{
for (path, must_read) in files {
let required = must_read == &MustRead::MustRead;
match mistrust
.verifier()
.permit_readable()
.require_file()
.check(&path)
{
Ok(()) => {}
Err(fs_mistrust::Error::NotFound(_)) if !required => {}
Err(e) => return Err(ConfigError::Foreign(e.into())),
}
let f: config::File<_, _> = path.as_ref().into();
builder = builder.add_source(f.format(config::FileFormat::Toml).required(required));
}
let mut cmdline = CmdLine::new();
for opt in opts {
cmdline.push_toml_line(opt.clone());
}
builder = builder.add_source(cmdline);
Ok(builder)
}
#[cfg(test)]
mod test {
#![allow(clippy::unwrap_used)]
use super::*;
use tempfile::tempdir;
static EX_TOML: &str = "
[hello]
world = \"stuff\"
friends = 4242
";
fn load_nodefaults<P: AsRef<Path>>(
files: &[(P, MustRead)],
opts: &[String],
) -> Result<config::Config, config::ConfigError> {
let mistrust = fs_mistrust::Mistrust::new_dangerously_trust_everyone();
add_sources(config::Config::builder(), &mistrust, files, opts)
.unwrap()
.build()
}
#[test]
fn non_required_file() {
let td = tempdir().unwrap();
let dflt = td.path().join("a_file");
let files = vec![(dflt, MustRead::TolerateAbsence)];
load_nodefaults(&files, Default::default()).unwrap();
}
static EX2_TOML: &str = "
[hello]
world = \"nonsense\"
";
#[test]
fn both_required_and_not() {
let td = tempdir().unwrap();
let dflt = td.path().join("a_file");
let cf = td.path().join("other_file");
std::fs::write(&cf, EX2_TOML).unwrap();
let files = vec![(dflt, MustRead::TolerateAbsence), (cf, MustRead::MustRead)];
let c = load_nodefaults(&files, Default::default()).unwrap();
assert!(c.get_string("hello.friends").is_err());
assert_eq!(c.get_string("hello.world").unwrap(), "nonsense".to_string());
}
#[test]
fn load_two_files_with_cmdline() {
let td = tempdir().unwrap();
let cf1 = td.path().join("a_file");
let cf2 = td.path().join("other_file");
std::fs::write(&cf1, EX_TOML).unwrap();
std::fs::write(&cf2, EX2_TOML).unwrap();
let v = vec![(cf1, MustRead::TolerateAbsence), (cf2, MustRead::MustRead)];
let v2 = vec!["other.var=present".to_string()];
let c = load_nodefaults(&v, &v2).unwrap();
assert_eq!(c.get_string("hello.friends").unwrap(), "4242".to_string());
assert_eq!(c.get_string("hello.world").unwrap(), "nonsense".to_string());
assert_eq!(c.get_string("other.var").unwrap(), "present".to_string());
}
#[test]
fn from_cmdline() {
let sources = ConfigurationSources::from_cmdline(
"/etc/loid.toml",
["/family/yor.toml", "/family/anya.toml"],
["decade=1960", "snack=peanuts"],
);
let files: Vec<_> = sources.files().map(|path| path.to_str().unwrap()).collect();
assert_eq!(files, vec!["/family/yor.toml", "/family/anya.toml"]);
assert_eq!(sources.files[0].1, MustRead::MustRead);
assert_eq!(
&sources.options,
&vec!["decade=1960".to_owned(), "snack=peanuts".to_owned()]
);
let sources = ConfigurationSources::from_cmdline(
"/etc/loid.toml",
Vec::<PathBuf>::new(),
["decade=1960", "snack=peanuts"],
);
assert_eq!(
&sources.files,
&vec![("/etc/loid.toml".into(), MustRead::TolerateAbsence)]
);
}
}