aboutsummaryrefslogtreecommitdiffstats
path: root/crates/config
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-29 01:37:39 +0000
committertv <tv@krebsco.de>2026-11-29 01:37:39 +0000
commitbcb729ce0cae2cd8bbd8f60f8e98a81674bcd4fb (patch)
tree7ed9a9bdfd0b55061cc701585e550957563f5597 /crates/config
parentfd0e8b29a86444b772f71d5db767c201b04cad2b (diff)
config: the report of a configuration, and --print-config
The report moves to the crate, as it was (report::report, Reports, Values): each option of a schema with its value, by the settings in effect given as JSON by option name, and where it came from; imported values and secrets left out. And the argument a program prints it by (arguments::with_print_config, prints_config). continuum gives its settings and what it loaded to it; --print-config and GET /admin/config say what they said.
Diffstat (limited to 'crates/config')
-rw-r--r--crates/config/Cargo.toml2
-rw-r--r--crates/config/src/arguments.rs56
-rw-r--r--crates/config/src/lib.rs2
-rw-r--r--crates/config/src/report.rs120
4 files changed, 179 insertions, 1 deletions
diff --git a/crates/config/Cargo.toml b/crates/config/Cargo.toml
index 2308315..a025f3d 100644
--- a/crates/config/Cargo.toml
+++ b/crates/config/Cargo.toml
@@ -24,7 +24,7 @@ tracing = ["dep:tracing"]
[dependencies]
anyhow = "1.0"
clap = { version = "4.6", optional = true }
-serde = { version = "1.0", optional = true }
+serde = { version = "1.0", features = ["derive"], optional = true }
serde_json = "1.0"
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 5f51b2b..4a251da 100644
--- a/crates/config/src/arguments.rs
+++ b/crates/config/src/arguments.rs
@@ -14,6 +14,24 @@ use crate::layer::{Entry, Layer, Overlay, Provenance, Sources, from_import, over
use crate::option::{Kind, OptionSpec, Schema, from_text};
pub const CONFIG: &str = "config";
+/// Printing the report of the configuration and exiting (`with_print_config`).
+pub const PRINT_CONFIG: &str = "print-config";
+
+/// `command` taking `--print-config`: a program given it prints its configuration's
+/// report (`report::report`) and exits (`prints_config`).
+pub fn with_print_config(command: Command) -> Command {
+ command.arg(
+ Arg::new(PRINT_CONFIG)
+ .long(PRINT_CONFIG)
+ .action(ArgAction::SetTrue)
+ .help("Print the effective configuration as JSON (with each value's source) and exit."),
+ )
+}
+
+/// Whether `--print-config` was given.
+pub fn prints_config(matches: &ArgMatches) -> bool {
+ matches.get_flag(PRINT_CONFIG)
+}
/// Stops on an argument naming an option that is gone, saying why, before the command
/// line is read: clap would call it unexpected.
@@ -211,6 +229,44 @@ mod tests {
assert_eq!(layer["token"].value, json!("hush"));
assert_eq!(layer["token"].shown(SCHEMA.secret("token")), "<secret>");
assert!(layer["name"].origin.to_string().ends_with("main.json"));
+ // The report: each option's value and where it is from, a secret's left out.
+ let settings: serde_json::Map<String, JsonValue> = layer
+ .iter()
+ .map(|(name, entry)| (name.clone(), entry.value.clone()))
+ .collect();
+ let origins = layer
+ .iter()
+ .map(|(name, entry)| (name.clone(), entry.origin.clone()))
+ .collect();
+ let files = [scratch.0.join("main.json")];
+ let report = crate::report::report(
+ &SCHEMA,
+ &settings,
+ &origins,
+ &files,
+ crate::report::Values::Interpolated,
+ );
+ assert_eq!(report["files"], json!([path("main.json")]));
+ let options = &report["options"];
+ assert_eq!(options["name"]["value"], json!("main"));
+ assert_eq!(options["name"]["source"], json!("file"));
+ assert!(
+ options["name"]["file"]
+ .as_str()
+ .is_some_and(|file| file.ends_with("main.json"))
+ );
+ assert_eq!(
+ options["remote"],
+ json!({ "source": "default", "value": null })
+ );
+ assert_eq!(options["token"]["secret"], json!(true));
+ assert!(options["token"].get("value").is_none());
+ assert!(!report.to_string().contains("hush"));
+ let command = with_print_config(with_options(Command::new("program"), OPTIONS));
+ let matches = command
+ .try_get_matches_from(["program", "--print-config"])
+ .unwrap();
+ assert!(prints_config(&matches));
// Arguments over files, and an unset back to the default.
let layer = merged_of(&[
"--config",
diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs
index aae8bce..bff1221 100644
--- a/crates/config/src/lib.rs
+++ b/crates/config/src/lib.rs
@@ -6,6 +6,7 @@
//! * [`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;
+//! * [`report`]: what each option ended up as and where from, to print or to serve;
//! * [`import`]: values taken from elsewhere instead of written out;
//! * [`units`]: durations and sizes as operators write them.
@@ -15,6 +16,7 @@ pub mod file;
pub mod import;
pub mod layer;
pub mod option;
+pub mod report;
pub mod units;
#[cfg(test)]
diff --git a/crates/config/src/report.rs b/crates/config/src/report.rs
new file mode 100644
index 0000000..dfbaa23
--- /dev/null
+++ b/crates/config/src/report.rs
@@ -0,0 +1,120 @@
+//! The report of a configuration: what each option ended up as and where its value came
+//! from, for a program to print (`--print-config`) or to serve.
+
+use std::collections::BTreeMap;
+use std::path::PathBuf;
+
+use serde_json::Value as JsonValue;
+
+use crate::layer::{Origin, Provenance};
+use crate::option::Schema;
+
+/// How a report shows text with placeholders.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
+#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
+pub enum Values {
+ /// As it ends up.
+ #[default]
+ Interpolated,
+ /// As written, placeholders and all.
+ Original,
+}
+
+/// The reports of a configuration, either way of showing text with placeholders: made
+/// once, at a program's start, for it to serve.
+#[derive(Debug, Clone, Default)]
+pub struct Reports {
+ interpolated: JsonValue,
+ original: JsonValue,
+}
+
+impl Reports {
+ /// Both reports (`report`).
+ pub fn of(
+ schema: &Schema,
+ settings: &serde_json::Map<String, JsonValue>,
+ origins: &BTreeMap<String, Origin>,
+ files: &[PathBuf],
+ ) -> Reports {
+ Reports {
+ interpolated: report(schema, settings, origins, files, Values::Interpolated),
+ original: report(schema, settings, origins, files, Values::Original),
+ }
+ }
+
+ pub fn get(&self, values: Values) -> &JsonValue {
+ match values {
+ Values::Interpolated => &self.interpolated,
+ Values::Original => &self.original,
+ }
+ }
+}
+
+/// The effective configuration with each value's source, as JSON: `files`, those read,
+/// and `options`, each of `schema`'s by name, with its `value` (of `settings`, the
+/// settings in effect by option name; `null` where they hold none), its `source`
+/// (`default`, `file` with the `file`, or `argument`), and where they apply `imported`,
+/// `templates`, `unset` and `secret`. Imported values are left out (they may be secret);
+/// their importers are listed instead. Secrets are left out however they were given.
+/// Text with placeholders is shown as `values` says, the text as written listed. Hidden
+/// options are left out unless set.
+pub fn report(
+ schema: &Schema,
+ settings: &serde_json::Map<String, JsonValue>,
+ origins: &BTreeMap<String, Origin>,
+ files: &[PathBuf],
+ values: Values,
+) -> JsonValue {
+ let options: serde_json::Map<String, JsonValue> = schema
+ .options
+ .iter()
+ .filter(|spec| !spec.hidden || origins.contains_key(spec.name))
+ .map(|spec| {
+ let mut entry = serde_json::Map::new();
+ let origin = origins.get(spec.name);
+ match origin {
+ None => {
+ entry.insert("source".into(), "default".into());
+ }
+ Some(origin) => {
+ match &origin.provenance {
+ Provenance::File(path) => {
+ entry.insert("source".into(), "file".into());
+ entry.insert("file".into(), path.display().to_string().into());
+ }
+ Provenance::Argument => {
+ entry.insert("source".into(), "argument".into());
+ }
+ }
+ if origin.is_imported() {
+ entry.insert("imported".into(), origin.imports.clone().into());
+ }
+ // Of a secret, the text may hold some of it.
+ if !origin.templates.is_empty() && !spec.secret {
+ entry.insert("templates".into(), origin.templates.clone().into());
+ }
+ if origin.unset {
+ entry.insert("unset".into(), true.into());
+ }
+ }
+ }
+ let given = origin.is_some_and(|origin| !origin.unset);
+ if spec.secret && given {
+ entry.insert("secret".into(), true.into());
+ } else if !origin.is_some_and(Origin::is_imported) {
+ let written = origin.and_then(|origin| origin.written.clone());
+ let value = match (values, written) {
+ (Values::Original, Some(written)) => written,
+ _ => settings.get(spec.name).cloned().unwrap_or(JsonValue::Null),
+ };
+ entry.insert("value".into(), value);
+ }
+ (spec.name.to_owned(), JsonValue::Object(entry))
+ })
+ .collect();
+ serde_json::json!({
+ "files": files.iter().map(|path| path.display().to_string()).collect::<Vec<_>>(),
+ "options": options,
+ })
+}