//! 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, /// Text with placeholders the value (or some list elements) came from, e.g. /// `node-${env:HOSTNAME}`. The value is shown. pub templates: Vec, /// With placeholders: the value as written, placeholders and all. pub written: Option, } 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 { "".to_owned() } else if secret { "".to_owned() } else if self.origin.is_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; /// 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 { 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, templates: Vec, /// The parts as written: literal values, importers, text with placeholders. written: Vec, } 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. Where they don't make a `T`, the error names the option whose value /// doesn't fit, and where it was set, which serde doesn't: the first that alone makes /// none; or, where a `T` needs more than one option, the first without which the others /// make one. #[cfg(feature = "serde")] pub fn read(merged: &Layer) -> Result { let made = |keep: &dyn Fn(&str) -> bool| { let object: serde_json::Map = merged .iter() .filter(|(name, entry)| !entry.value.is_null() && keep(name)) .map(|(name, entry)| (name.clone(), entry.value.clone())) .collect(); serde_json::from_value::(JsonValue::Object(object)) }; let error = match made(&|_| true) { Ok(read) => return Ok(read), Err(error) => error, }; let alone = made(&|_| false).is_ok(); let culprit = merged.iter().find(|(name, entry)| { !entry.value.is_null() && if alone { made(&|other| other == name.as_str()).is_err() } else { made(&|other| other != name.as_str()).is_ok() } }); Err(match culprit { Some((name, entry)) => anyhow!("option {name} (set in {}): {error}", entry.origin), None => anyhow!("{error}"), }) } #[cfg(all(test, feature = "serde"))] mod tests { use super::*; use serde::Deserialize; use serde_json::json; fn layer(values: &[(&str, JsonValue)]) -> Layer { values .iter() .map(|(name, value)| { let entry = Entry { value: value.clone(), origin: Sources::default().origin(Provenance::Argument, false, Kind::Text), }; ((*name).to_owned(), entry) }) .collect() } /// Where the values set make none of what they are read into, the option whose /// value doesn't fit is named, and where it was set: whether every option may be /// left out, or some must be there. #[test] fn the_option_that_fits_not_is_named() { #[derive(Debug, Deserialize)] #[allow(dead_code)] struct Optional { #[serde(default)] name: String, #[serde(default)] count: u64, } #[derive(Debug, Deserialize)] #[allow(dead_code)] struct Needed { name: String, #[serde(default)] count: u64, } let good = layer(&[("name", json!("a")), ("count", json!(3))]); assert_eq!(read::(&good).unwrap().count, 3); assert_eq!(read::(&good).unwrap().name, "a"); let bad = layer(&[("name", json!("a")), ("count", json!("many"))]); for said in [ read::(&bad).unwrap_err().to_string(), read::(&bad).unwrap_err().to_string(), ] { assert!(said.contains("option count"), "{said}"); assert!(said.contains("the command line"), "{said}"); } // Nothing to name: what is needed isn't there. let lacking = layer(&[("count", json!(3))]); let said = read::(&lacking).unwrap_err().to_string(); assert!(!said.contains("option count"), "{said}"); // An unset is left out, and takes the default. let mut unset = layer(&[("name", json!("a"))]); unset.insert("count".to_owned(), unset_entry(Provenance::Argument)); assert_eq!(read::(&unset).unwrap().count, 0); } }