diff options
| -rw-r--r-- | crates/config/Cargo.toml | 3 | ||||
| -rw-r--r-- | crates/config/src/layer.rs | 97 | ||||
| -rw-r--r-- | src/config/mod.rs | 34 |
3 files changed, 97 insertions, 37 deletions
diff --git a/crates/config/Cargo.toml b/crates/config/Cargo.toml index e46c8ef..2308315 100644 --- a/crates/config/Cargo.toml +++ b/crates/config/Cargo.toml @@ -28,3 +28,6 @@ serde = { version = "1.0", optional = true } serde_json = "1.0" toml = { version = "1.1", optional = true } tracing = { version = "0.1", optional = true } + +[dev-dependencies] +serde = { version = "1.0", features = ["derive"] } diff --git a/crates/config/src/layer.rs b/crates/config/src/layer.rs index 6693009..9871d9b 100644 --- a/crates/config/src/layer.rs +++ b/crates/config/src/layer.rs @@ -279,13 +279,96 @@ pub fn resolve_file_value( } /// `T` read from the values `merged` sets, each option's by its name: those unset take -/// `T`'s defaults. +/// `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<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}")) + let made = |keep: &dyn Fn(&str) -> bool| { + let object: serde_json::Map<String, JsonValue> = merged + .iter() + .filter(|(name, entry)| !entry.value.is_null() && keep(name)) + .map(|(name, entry)| (name.clone(), entry.value.clone())) + .collect(); + serde_json::from_value::<T>(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::<Optional>(&good).unwrap().count, 3); + assert_eq!(read::<Needed>(&good).unwrap().name, "a"); + let bad = layer(&[("name", json!("a")), ("count", json!("many"))]); + for said in [ + read::<Optional>(&bad).unwrap_err().to_string(), + read::<Needed>(&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::<Needed>(&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::<Optional>(&unset).unwrap().count, 0); + } } diff --git a/src/config/mod.rs b/src/config/mod.rs index 3e7c5d4..a32211e 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -29,9 +29,8 @@ use serde_json::Value as JsonValue; use tracing::{info, warn}; pub(crate) use ::config::arguments::{merged, with_options}; -#[cfg(feature = "federation")] pub(crate) use ::config::layer::read; -pub(crate) use ::config::layer::{Entry, Layer, Origin, Provenance}; +pub(crate) use ::config::layer::{Layer, Origin, Provenance}; pub(crate) use ::config::option::{Kind, OptionSpec, Schema, option}; /// What the node's configuration is read by: its options, those that can't be combined, @@ -49,7 +48,7 @@ pub(crate) const PARTY: Schema = Schema::of(PARTY_OPTIONS); /// As the crate's, by the node's options: what the tests call. #[cfg(test)] use ::config::{ - layer::{Overlay, unset_entry}, + layer::{Entry, Overlay, unset_entry}, option::from_text, }; @@ -1540,18 +1539,6 @@ const CONFLICTS: &[(&[&str], &[&str])] = &[( ], )]; -/// The first option whose value alone doesn't fit (serde doesn't name it). -fn culprit(merged: &Layer) -> Option<(&String, &Entry)> { - merged.iter().find(|(name, entry)| { - if entry.value.is_null() { - return false; - } - let mut alone = serde_json::Map::new(); - alone.insert((*name).clone(), entry.value.clone()); - serde_json::from_value::<Settings>(JsonValue::Object(alone)).is_err() - }) -} - // --- command line -------------------------------------------------------------- const PRINT_CONFIG: &str = "print-config"; @@ -1825,22 +1812,9 @@ fn resolve(merged: Layer, files: Vec<PathBuf>) -> Result<Loaded> { entry.origin ); } - // Unset options take their defaults. - let object: serde_json::Map<String, JsonValue> = merged - .iter() - .filter(|(_, entry)| !entry.value.is_null()) - .map(|(name, entry)| (name.clone(), entry.value.clone())) - .collect(); + // Unset options take their defaults; an option whose value fits not is named. let mut settings: Settings = - serde_json::from_value(JsonValue::Object(object)).map_err(|error| { - match culprit(&merged) { - Some((name, entry)) => anyhow!( - "invalid configuration: option {name} (set in {}): {error}", - entry.origin - ), - None => anyhow!("invalid configuration: {error}"), - } - })?; + read(&merged).map_err(|error| anyhow!("invalid configuration: {error}"))?; settings.alias = settings.alias.map(|alias| alias.trim().to_owned()); settings.transports = settings.ordered_transports(); settings.check().context("invalid configuration")?; |
