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
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Named errors. No variant carries a secret's value: where a value would be shown for a secret
//! key, the text is `<redacted>`.
use std::fmt;
use crate::schema::Bound;
/// Where a value (or an offending input) came from.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Origin {
/// The default declared in the schema.
Default,
/// A configuration file, by the name it was given.
File(String),
/// An environment variable, by name.
Env(String),
/// A command-line flag (or argument position).
Cli(String),
/// A secret source (`configurant-secrets`), as the schema declares it: `<source>:<reference>`. Never the value.
Source(String),
/// A lookup by key (`Config::get`, `explain`), not a source of values.
Lookup,
/// A change made by a front end through [`crate::edit::Session`].
Edit,
}
impl fmt::Display for Origin {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Origin::Default => f.write_str("the schema default"),
Origin::File(n) => write!(f, "file `{n}`"),
Origin::Env(n) => write!(f, "environment variable `{n}`"),
Origin::Cli(n) => write!(f, "command-line `{n}`"),
Origin::Source(declared) => match declared.split_once(':') {
Some((name, reference)) => {
write!(f, "secret source `{name}` (reference `{reference}`)")
}
None => write!(f, "secret source `{declared}`"),
},
Origin::Lookup => f.write_str("this lookup"),
Origin::Edit => f.write_str("this edit"),
}
}
}
/// One refused input.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum ConfigError {
/// The schema does not declare this name.
#[error("unknown key `{key}` from {origin}{}", suggest(.suggestion))]
UnknownKey {
/// The unknown key, environment variable or flag.
key: String,
/// A declared name close to it, if there is one.
suggestion: Option<String>,
/// Where the unknown name was given.
origin: Origin,
},
/// The input is not of the type the schema declares.
#[error("`{key}` from {origin}: expected {expected}, found {found}")]
WrongType {
/// Dotted key concerned.
key: String,
/// What was wanted, such as a type name.
expected: &'static str,
/// What was given (a type name or the quoted text); `<redacted>` for a secret's text.
found: String,
/// Where the input came from.
origin: Origin,
},
/// A number is below `min` or above `max`.
#[error("`{key}` from {origin}: {found} is outside {}", range(*.min, *.max))]
OutOfRange {
/// Dotted key concerned.
key: String,
/// The refused number as shown; `<redacted>` for a secret.
found: String,
/// Lowest allowed value (inclusive), if the schema sets one.
min: Option<Bound>,
/// Highest allowed value (inclusive), if the schema sets one.
max: Option<Bound>,
/// Where the input came from.
origin: Origin,
},
/// An enum value that is not one of the schema's choices.
#[error("`{key}` from {origin}: {found} is not one of {}", .choices.join(", "))]
NotAllowed {
/// Dotted key concerned.
key: String,
/// The refused value as shown; `<redacted>` for a secret.
found: String,
/// The values the schema allows.
choices: Vec<String>,
/// Where the input came from.
origin: Origin,
},
/// A secret was given by a file, or an edit tried to set one.
#[error("`{key}` is a secret and may not come from {origin}; use its environment variable")]
SecretInForbiddenSource {
/// The secret's dotted key.
key: String,
/// Where the attempt came from.
origin: Origin,
},
/// A value the schema requires was set by no layer.
#[error("`{key}` is required and no origin set it")]
MissingRequired {
/// Dotted key of the value, table, map or row field.
key: String,
},
/// A typed read of a declared key that has no value.
#[error("`{key}` has no value (no default and no origin set it)")]
NotSet {
/// The key that was read.
key: String,
},
/// A command-line flag that takes a value was given none.
#[error("flag `{flag}` needs a value")]
MissingCliValue {
/// The flag as typed.
flag: String,
},
/// An argument that does not start with `--`; it is not echoed, as it could be a secret.
#[error("unexpected command-line argument at position {index}")]
UnexpectedArgument {
/// Position among the arguments, counting from 0.
index: usize,
},
/// The configuration file could not be read as TOML, or is too large.
#[error("configuration file `{name}`: {reason}")]
FileParse {
/// The name the file was given.
name: String,
/// The parser's message, with the line number when known.
reason: String,
},
/// The value's `provider` names a module the loader does not have.
#[error("`{key}` takes its value from module `{module}`, which is not registered")]
ModuleMissing {
/// Dotted key concerned.
key: String,
/// The module the schema names.
module: String,
},
/// The file's `config_version` is older than the schema's.
#[error(
"configuration file `{name}` is at config version {found}, this schema is at {current}; run `configurant migrate`"
)]
FileOutdated {
/// The name the file was given.
name: String,
/// The version the file records.
found: u32,
/// The version the schema is at.
current: u32,
},
/// The file's `config_version` is newer than the schema's.
#[error(
"configuration file `{name}` is at config version {found}, newer than this schema's {current}"
)]
FileNewer {
/// The name the file was given.
name: String,
/// The version the file records.
found: u32,
/// The version the schema is at.
current: u32,
},
/// A mounted fragment's section of the file is at an older version.
#[error(
"configuration file `{name}` has `{mount}` at config version {found}, the fragment is at {current}; run `configurant migrate`"
)]
MountFileOutdated {
/// The name the file was given.
name: String,
/// The name the fragment is mounted as.
mount: String,
/// The version that section records.
found: u32,
/// The version the fragment is at.
current: u32,
},
/// A mounted fragment's section of the file is at a newer version.
#[error(
"configuration file `{name}` has `{mount}` at config version {found}, newer than the fragment's {current}"
)]
MountFileNewer {
/// The name the file was given.
name: String,
/// The name the fragment is mounted as.
mount: String,
/// The version that section records.
found: u32,
/// The version the fragment is at.
current: u32,
},
/// A map entry whose key is the empty string.
#[error("map `{key}` from {origin} has an empty key")]
EmptyMapKey {
/// Dotted key of the map.
key: String,
/// Where the map came from.
origin: Origin,
},
/// An edit tried to set a table or map.
#[error("`{key}` is an array of tables or a map, which only the configuration file can set")]
FileOnly {
/// Dotted key of the table or map.
key: String,
},
/// The loaded values do not fit the type given to `Config::deserialize`.
#[error("the configuration does not fit the target type: {reason}")]
Deserialize {
/// The deserializer's message, withheld if it quoted a secret.
reason: String,
},
/// A provider module's own rule refused the value.
#[error("`{key}` from {origin} was rejected by module `{module}`: {reason}")]
ModuleRejected {
/// Dotted key concerned.
key: String,
/// Name of the module that refused it.
module: String,
/// The module's message; `<redacted>` for a secret.
reason: String,
/// Where the value came from.
origin: Origin,
},
}
fn suggest(s: &Option<String>) -> String {
s.as_ref()
.map(|s| format!(" (did you mean `{s}`?)"))
.unwrap_or_default()
}
fn range(min: Option<Bound>, max: Option<Bound>) -> String {
match (min, max) {
(Some(a), Some(b)) => format!("{a}..={b}"),
(Some(a), None) => format!(">= {a}"),
(None, Some(b)) => format!("<= {b}"),
(None, None) => "the allowed range".into(),
}
}
/// Every error found in one load (the loader does not stop at the first).
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub struct Errors(pub Vec<ConfigError>);
impl fmt::Display for Errors {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (i, e) in self.0.iter().enumerate() {
if i > 0 {
f.write_str("\n")?;
}
write!(f, "{e}")?;
}
Ok(())
}
}