diff options
| -rw-r--r-- | Cargo.toml | 2 | ||||
| -rw-r--r-- | crates/config/Cargo.toml | 20 | ||||
| -rw-r--r-- | crates/config/src/arguments.rs | 14 | ||||
| -rw-r--r-- | crates/config/src/file.rs | 11 | ||||
| -rw-r--r-- | crates/config/src/layer.rs | 14 | ||||
| -rw-r--r-- | crates/config/src/lib.rs | 4 | ||||
| -rw-r--r-- | crates/config/src/units.rs | 4 |
7 files changed, 49 insertions, 20 deletions
@@ -49,7 +49,7 @@ most = ["dashboard", "federation", "libp2p", "mycelium", "tor"] [dependencies] # What a configuration is made of, from files and arguments: a crate of its own, for # other programs to make theirs alike. -config = { path = "crates/config" } +config = { path = "crates/config", features = ["clap", "serde", "toml", "tracing"] } anyhow = "1.0" # The tor feature: arti's crates are released together, at the same version. arti-client = { version = "0.48", optional = true, features = ["onion-service-client", "onion-service-service", "static-sqlite"] } diff --git a/crates/config/Cargo.toml b/crates/config/Cargo.toml index d8e75de..e46c8ef 100644 --- a/crates/config/Cargo.toml +++ b/crates/config/Cargo.toml @@ -9,10 +9,22 @@ edition = "2024" [lib] doctest = false +# None of them default: a program names what it uses. +[features] +# The command line (`arguments`): the options as arguments, `--config`, `--unset`. +clap = ["dep:clap"] +# What the values set are read into (`layer::read`), and durations and sizes as fields +# (`units::duration_option`, …). +serde = ["dep:serde"] +# Configuration files in TOML; without, in JSON alone. +toml = ["dep:toml"] +# What a source replaces of an earlier one's, logged. +tracing = ["dep:tracing"] + [dependencies] anyhow = "1.0" +clap = { version = "4.6", optional = true } +serde = { version = "1.0", optional = true } serde_json = "1.0" -clap = "4.6" -serde = { version = "1.0", features = ["derive"] } -toml = "1.1" -tracing = "0.1" +toml = { version = "1.1", optional = true } +tracing = { version = "0.1", optional = true } diff --git a/crates/config/src/arguments.rs b/crates/config/src/arguments.rs index b1b8d00..5f51b2b 100644 --- a/crates/config/src/arguments.rs +++ b/crates/config/src/arguments.rs @@ -197,12 +197,12 @@ mod tests { let scratch = Scratch::new("arguments"); let path = |name: &str| scratch.0.join(name).display().to_string(); scratch.file( - "base.toml", - "name = \"base\"\npeers = [\"a\", \"b\"]\nlocal = \"here\"\n", + "base.json", + r#"{"name": "base", "peers": ["a", "b"], "local": "here"}"#, ); scratch.file( "main.json", - r#"{"include": ["base.toml"], "name": "main", "token": {"file": "secret"}}"#, + r#"{"include": ["base.json"], "name": "main", "token": {"file": "secret"}}"#, ); scratch.file("secret", "hush\n"); let layer = merged_of(&["--config", &path("main.json")]).unwrap(); @@ -229,16 +229,16 @@ mod tests { assert!(!layer.contains_key("local")); assert_eq!(layer["remote"].value, json!("there")); // Unknown, and gone. - scratch.file("unknown.toml", "nmae = \"x\"\n"); + scratch.file("unknown.json", r#"{"nmae": "x"}"#); let said = format!( "{:#}", - merged_of(&["--config", &path("unknown.toml")]).unwrap_err() + merged_of(&["--config", &path("unknown.json")]).unwrap_err() ); assert!(said.contains("unknown option"), "{said}"); - scratch.file("gone.toml", "legacy = \"x\"\n"); + scratch.file("gone.json", r#"{"legacy": "x"}"#); let said = format!( "{:#}", - merged_of(&["--config", &path("gone.toml")]).unwrap_err() + merged_of(&["--config", &path("gone.json")]).unwrap_err() ); assert!(said.contains("use name instead"), "{said}"); let said = refuse_gone(["--legacy=x".to_owned()], &SCHEMA).unwrap_err(); diff --git a/crates/config/src/file.rs b/crates/config/src/file.rs index a5ed559..b365623 100644 --- a/crates/config/src/file.rs +++ b/crates/config/src/file.rs @@ -14,7 +14,6 @@ use std::path::{Path, PathBuf}; use anyhow::{Context, Result, anyhow, bail}; use serde_json::{Map as JsonMap, Value as JsonValue}; -use tracing::debug; use crate::import; use crate::layer::{Entry, Layer, Overlay, Provenance, overlay, resolve_file_value, unset_entry}; @@ -59,7 +58,8 @@ fn load_inner(path: &Path, schema: &Schema, loading: &mut Vec<PathBuf>) -> Resul for (include, required) in includes { let include = dir.join(include); if !required && !include.exists() { - debug!(file = %include.display(), "Optional configuration file is missing; skipped"); + #[cfg(feature = "tracing")] + tracing::debug!(file = %include.display(), "Optional configuration file is missing; skipped"); continue; } let included = load_inner(&include, schema, loading) @@ -113,11 +113,18 @@ fn parse(path: &Path) -> Result<JsonMap<String, JsonValue>> { let text = std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?; let value: JsonValue = match path.extension().and_then(|e| e.to_str()) { + #[cfg(feature = "toml")] Some("toml") => { let value: toml::Value = toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?; serde_json::to_value(value).with_context(|| format!("converting {}", path.display()))? } + #[cfg(not(feature = "toml"))] + Some("toml") => bail!( + "{}: this program reads no TOML (it is built without the config crate's feature \ + toml): use .json", + path.display() + ), Some("json") => { serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))? } diff --git a/crates/config/src/layer.rs b/crates/config/src/layer.rs index 783bcb0..6693009 100644 --- a/crates/config/src/layer.rs +++ b/crates/config/src/layer.rs @@ -6,7 +6,6 @@ use std::path::{Path, PathBuf}; use anyhow::{Result, anyhow, bail}; use serde_json::Value as JsonValue; -use tracing::{debug, info, warn}; use crate::import::{self, Imported}; use crate::option::{Kind, OptionSpec, Schema, from_text}; @@ -106,10 +105,14 @@ pub enum Overlay { } /// Puts `entry` for `name` into `layer`, which holds earlier sources, logging what it -/// replaces and dropping earlier values it can't be combined with. +/// 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 => warn!( + Overlay::IncludeOverInclude => tracing::warn!( option, value = %entry.shown(schema.secret(&name)), from = %entry.origin, @@ -117,13 +120,13 @@ pub fn overlay(layer: &mut Layer, name: String, entry: Entry, how: Overlay, sche overridden_from = %previous.origin, "{message}" ), - Overlay::FileOverFile => debug!( + Overlay::FileOverFile => tracing::debug!( option, from = %entry.origin, overrides = %previous.origin, "{message}" ), - Overlay::ArgumentOverFile => info!( + Overlay::ArgumentOverFile => tracing::info!( option, value = %entry.shown(schema.secret(&name)), overrides = %previous.shown(schema.secret(option)), @@ -277,6 +280,7 @@ pub fn resolve_file_value( /// `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() diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index fe2432e..aae8bce 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -3,11 +3,13 @@ //! //! * [`option`]: the options a program takes, described once (`Schema`); //! * [`file`]: configuration files, TOML or JSON, including others; -//! * [`arguments`]: the command line, and files and arguments put together; +//! * [`arguments`]: the command line, and files and arguments put together (with the +//! feature `clap`); //! * [`layer`]: values and where they came from, later sources over earlier ones; //! * [`import`]: values taken from elsewhere instead of written out; //! * [`units`]: durations and sizes as operators write them. +#[cfg(feature = "clap")] pub mod arguments; pub mod file; pub mod import; diff --git a/crates/config/src/units.rs b/crates/config/src/units.rs index 1e72da3..61ece46 100644 --- a/crates/config/src/units.rs +++ b/crates/config/src/units.rs @@ -141,6 +141,7 @@ pub fn format_size(bytes: u64) -> String { /// Serde for a `Duration` option: a string as [`parse_duration`] reads it, or a number /// of seconds (configuration files may write either); written as [`format_duration`]. +#[cfg(feature = "serde")] pub mod duration_option { use std::time::Duration; @@ -165,6 +166,7 @@ pub mod duration_option { /// Reads an optional `Duration` in a request (JSON body or query string) as /// [`duration_option`] reads it; absent is `None`. Use as /// `#[serde(default, deserialize_with = "crate::units::optional_duration")]`. +#[cfg(feature = "serde")] pub fn optional_duration<'de, D: serde::Deserializer<'de>>( d: D, ) -> Result<Option<Duration>, D::Error> { @@ -172,6 +174,7 @@ pub fn optional_duration<'de, D: serde::Deserializer<'de>>( } /// Writes an optional `Duration` as [`duration_option`] does; `None` as null. +#[cfg(feature = "serde")] pub fn serialize_optional_duration<S: serde::Serializer>( value: &Option<Duration>, s: S, @@ -184,6 +187,7 @@ pub fn serialize_optional_duration<S: serde::Serializer>( /// Serde for a size option: a string as [`parse_size`] reads it, or a number of bytes; /// written as [`format_size`]. +#[cfg(feature = "serde")] pub mod size_option { use serde::{Deserialize, Deserializer, Serializer, de::Error as _}; use serde_json::Value as JsonValue; |
