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
283
284
285
286
287
288
289
290
291
|
//! Values and where they came from: each source of a configuration, a file or the
//! command line, makes a layer of them, and later ones are put over earlier ones.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use anyhow::{Result, anyhow, bail};
use serde_json::Value as JsonValue;
use crate::import::{self, Imported};
use crate::option::{Kind, OptionSpec, Schema, from_text};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Provenance {
File(PathBuf),
Argument,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Origin {
pub provenance: Provenance,
/// The option was unset here (back to its default): `--unset`, `unset = [...]` in a
/// file, or `null` in a JSON file.
pub unset: bool,
/// Importers the value (or some list elements) came from, e.g. `env:HOSTNAME`. The
/// value is never shown.
pub imports: Vec<String>,
/// Text with placeholders the value (or some list elements) came from, e.g.
/// `node-${env:HOSTNAME}`. The value is shown.
pub templates: Vec<String>,
/// With placeholders: the value as written, placeholders and all.
pub written: Option<JsonValue>,
}
impl Origin {
pub fn is_imported(&self) -> bool {
!self.imports.is_empty()
}
}
impl std::fmt::Display for Origin {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.provenance {
Provenance::File(path) => write!(f, "{}", path.display())?,
Provenance::Argument => write!(f, "the command line")?,
}
if self.unset {
write!(f, " (unset)")?;
}
// Not the text with placeholders: of a secret, it may hold some of it.
if self.is_imported() {
write!(f, " ({})", self.imports.join(", "))?;
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct Entry {
pub value: JsonValue,
pub origin: Origin,
}
impl Entry {
/// The value of `option` for logs: imported values and secrets are never shown.
pub fn shown(&self, secret: bool) -> String {
if self.origin.unset {
"<default>".to_owned()
} else if secret {
"<secret>".to_owned()
} else if self.origin.is_imported() {
"<imported>".to_owned()
} else {
self.value.to_string()
}
}
}
/// Option name to value. A `null` value unsets the option (back to its default).
pub type Layer = BTreeMap<String, Entry>;
/// An unset of `name` from `provenance`.
pub fn unset_entry(provenance: Provenance) -> Entry {
Entry {
value: JsonValue::Null,
origin: Origin {
provenance,
unset: true,
imports: Vec::new(),
templates: Vec::new(),
written: None,
},
}
}
/// How a later source relates to the earlier ones it overrides (for logging).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Overlay {
/// A later include over an earlier include of the same file: usually a mistake.
IncludeOverInclude,
/// A file's own values over its includes, or a later `--config` over an earlier.
FileOverFile,
/// The command line over files.
ArgumentOverFile,
}
/// Puts `entry` for `name` into `layer`, which holds earlier sources, logging what it
/// replaces (with the feature `tracing`) and dropping earlier values it can't be combined
/// with.
pub fn overlay(layer: &mut Layer, name: String, entry: Entry, how: Overlay, schema: &Schema) {
#[cfg(not(feature = "tracing"))]
let log = |_: &str, _: &str, _: &Entry| {};
#[cfg(feature = "tracing")]
let log = |message: &str, option: &str, previous: &Entry| match how {
Overlay::IncludeOverInclude => tracing::warn!(
option,
value = %entry.shown(schema.secret(&name)),
from = %entry.origin,
overrides = %previous.shown(schema.secret(option)),
overridden_from = %previous.origin,
"{message}"
),
Overlay::FileOverFile => tracing::debug!(
option,
from = %entry.origin,
overrides = %previous.origin,
"{message}"
),
Overlay::ArgumentOverFile => tracing::info!(
option,
value = %entry.shown(schema.secret(&name)),
overrides = %previous.shown(schema.secret(option)),
from = %previous.origin,
"{message}"
),
};
if !entry.value.is_null() {
for other in schema.conflicting(&name) {
let earlier = layer
.get(other)
.is_some_and(|previous| previous.origin.provenance != entry.origin.provenance);
if earlier && let Some(previous) = layer.remove(other) {
log(
&format!("{name} can't be combined with {other}; dropped the earlier value"),
other,
&previous,
);
}
}
}
if let Some(previous) = layer.get(&name) {
let message = match how {
Overlay::IncludeOverInclude => {
"Two included configuration files set the same option; the later one wins"
}
Overlay::FileOverFile => "Configuration file overrides an earlier one",
Overlay::ArgumentOverFile => "Command-line argument overrides the configuration file",
};
log(message, &name, previous);
}
layer.insert(name, entry);
}
pub fn from_import(kind: Kind, importer: &import::Importer) -> Result<JsonValue> {
match importer.fetch()? {
Imported::Text(text) => from_text(kind, &text),
Imported::Json(value) => Ok(value),
// As it is: one text, its line breaks kept, read as nothing else.
Imported::Raw(bytes) => String::from_utf8(bytes)
.map(JsonValue::String)
.map_err(|_| anyhow!("{} is not UTF-8: an option is text", importer.describe())),
}
}
/// A value from a file in `dir`: importer tables are resolved, also as list elements.
/// Collects where the parts of a value came from, for its [`Origin`].
#[derive(Default)]
pub struct Sources {
imports: Vec<String>,
templates: Vec<String>,
/// The parts as written: literal values, importers, text with placeholders.
written: Vec<JsonValue>,
}
impl Sources {
/// A literal part (list values count element by element).
pub fn literal(&mut self, value: &JsonValue) {
match value {
JsonValue::Array(items) => self.written.extend(items.iter().cloned()),
other => self.written.push(other.clone()),
}
}
/// A part from `importer`.
pub fn import(&mut self, importer: &import::Importer) {
let described = importer.describe();
if importer.is_interpolation() {
self.templates.push(described.clone());
} else {
self.imports.push(described.clone());
}
self.written.push(JsonValue::String(described));
}
pub fn origin(self, provenance: Provenance, unset: bool, kind: Kind) -> Origin {
let written = (!self.templates.is_empty()).then(|| match kind {
Kind::List => JsonValue::Array(self.written),
_ => self.written.into_iter().last().unwrap_or(JsonValue::Null),
});
Origin {
provenance,
unset,
imports: self.imports,
templates: self.templates,
written,
}
}
}
/// A value from a file, and where its parts came from.
pub fn resolve_file_value(
spec: &OptionSpec,
value: JsonValue,
dir: &Path,
) -> Result<(JsonValue, Sources)> {
let mut sources = Sources::default();
let value = match value {
JsonValue::Object(table) => match import::parse_table(&table, dir)? {
Some(importer) => {
sources.import(&importer);
from_import(spec.kind, &importer)?
}
None => bail!("a table here must be an importer (env, file or command)"),
},
JsonValue::String(text) => match import::interpolated(&text, Some(dir)) {
Some(importer) => {
sources.import(&importer);
from_import(spec.kind, &importer)?
}
None => JsonValue::String(text),
},
JsonValue::Array(items) if spec.kind == Kind::List => {
let mut values = Vec::new();
for item in items {
match item {
JsonValue::Object(table) => {
let importer = import::parse_table(&table, dir)?.ok_or_else(|| {
anyhow!("a table here must be an importer (env, file or command)")
})?;
match from_import(Kind::List, &importer)? {
JsonValue::Array(more) => values.extend(more),
other => values.push(other),
}
sources.import(&importer);
}
JsonValue::String(text) => match import::interpolated(&text, Some(dir)) {
Some(importer) => {
values.push(from_import(Kind::Text, &importer)?);
sources.import(&importer);
}
None => {
let value = JsonValue::String(text);
sources.literal(&value);
values.push(value);
}
},
other => {
sources.literal(&other);
values.push(other);
}
}
}
JsonValue::Array(values)
}
other => other,
};
Ok((value, sources))
}
/// `T` read from the values `merged` sets, each option's by its name: those unset take
/// `T`'s defaults.
#[cfg(feature = "serde")]
pub fn read<T: serde::de::DeserializeOwned>(merged: &Layer) -> Result<T> {
let object: serde_json::Map<String, JsonValue> = merged
.iter()
.filter(|(_, entry)| !entry.value.is_null())
.map(|(name, entry)| (name.clone(), entry.value.clone()))
.collect();
serde_json::from_value(JsonValue::Object(object)).map_err(|error| anyhow!("{error}"))
}
|