aboutsummaryrefslogtreecommitdiffstats
path: root/crates/config
diff options
context:
space:
mode:
Diffstat (limited to 'crates/config')
-rw-r--r--crates/config/Cargo.toml3
-rw-r--r--crates/config/src/layer.rs97
2 files changed, 93 insertions, 7 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);
+ }
}