aboutsummaryrefslogtreecommitdiffstats
path: root/crates/config/src/option.rs
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-29 01:12:18 +0000
committertv <tv@krebsco.de>2026-11-29 01:12:18 +0000
commitf10ee79ddc2b0a541f1011aa395990df21e456b5 (patch)
treec88be3f95cbec1d5413c2b1aa5c3c9ff7135b6f3 /crates/config/src/option.rs
parent7a8e8ecd650ddb253c08445f6f60686e1c8b8bf5 (diff)
config: files, arguments and layers, by a program's own options
What reads a configuration moves to the crate config, as it was, so that other programs read theirs alike: * option: Kind, OptionSpec, and Schema: a program's options, those that can't be combined, and those that are gone; * file: TOML and JSON files, their includes and unsets; * arguments: the options as arguments, --config and --unset, and files and arguments put together (merged); * layer: values and where they came from, a later source over the earlier ones (overlay), what a value was made of (Sources); * units: durations and sizes as operators write them, which continuum keeps under crate::units. Each takes the schema it reads by, where continuum's code went by its own tables: the node's is config::SCHEMA, a party's client's config::PARTY. Whether a value is shown goes by the schema read by, so an option of the node is no secret for being one of the client's. continuum keeps its options, the settings they make, their checks and the report; its tests of files and layers stay, by the node's options, and the crate has one by a schema of its own.
Diffstat (limited to 'crates/config/src/option.rs')
-rw-r--r--crates/config/src/option.rs156
1 files changed, 156 insertions, 0 deletions
diff --git a/crates/config/src/option.rs b/crates/config/src/option.rs
new file mode 100644
index 0000000..b361d38
--- /dev/null
+++ b/crates/config/src/option.rs
@@ -0,0 +1,156 @@
+//! The options a program takes, each described once: the command line, the keys of
+//! configuration files and the reading of text values all go by them.
+
+use anyhow::{Result, anyhow, bail};
+use serde_json::Value as JsonValue;
+
+/// How an option's value is written as text (command line, text imports).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Kind {
+ /// `true`/`false`; on the command line, present or not.
+ Flag,
+ Text,
+ Integer,
+ /// Seconds, or with units: `500ms`, `30s`, `1h30m` (`units::parse_duration`).
+ Duration,
+ /// Bytes, or with a unit: `64KiB` (`units::parse_size`).
+ Size,
+ /// Comma- or line-separated; repeatable on the command line.
+ List,
+}
+
+#[derive(Debug)]
+pub struct OptionSpec {
+ pub name: &'static str,
+ pub kind: Kind,
+ pub value_name: &'static str,
+ /// For `--help` only; the effective defaults are in [`Settings`].
+ pub default: Option<&'static str>,
+ pub help: &'static str,
+ pub hidden: bool,
+ /// Its value is never shown (logs, `--print-config`, `GET /admin/config`), however
+ /// it was given.
+ pub secret: bool,
+}
+
+impl OptionSpec {
+ pub const fn secret(self) -> Self {
+ Self {
+ secret: true,
+ ..self
+ }
+ }
+}
+
+pub const fn option(
+ name: &'static str,
+ kind: Kind,
+ value_name: &'static str,
+ default: Option<&'static str>,
+ help: &'static str,
+) -> OptionSpec {
+ OptionSpec {
+ name,
+ kind,
+ value_name,
+ default,
+ help,
+ hidden: false,
+ secret: false,
+ }
+}
+
+/// Options that can't be combined: those of one side with those of the other.
+pub type Conflict = (&'static [&'static str], &'static [&'static str]);
+
+/// What a program's configuration is read by: its options, and what it says of them.
+#[derive(Debug, Clone, Copy)]
+pub struct Schema {
+ /// Every option. Names are the long option names and the configuration file keys.
+ pub options: &'static [OptionSpec],
+ /// Options that can't be combined. A source that sets one side drops the other
+ /// side's values from earlier sources (lower precedence), so one on the command line
+ /// overrides the other from a file.
+ pub conflicts: &'static [Conflict],
+ /// Options of earlier releases that are gone, each with what to do instead: a program
+ /// given one, in a configuration file or on its command line, says so and stops,
+ /// where "unknown option" would leave its operator guessing.
+ pub gone: &'static [(&'static str, &'static str)],
+}
+
+impl Schema {
+ /// A schema of `options` alone: none conflicting, none gone.
+ pub const fn of(options: &'static [OptionSpec]) -> Schema {
+ Schema {
+ options,
+ conflicts: &[],
+ gone: &[],
+ }
+ }
+
+ /// The option named `name`.
+ pub fn spec(&self, name: &str) -> Option<&'static OptionSpec> {
+ self.options.iter().find(|spec| spec.name == name)
+ }
+
+ /// Why `name` is no option any more, where it was one.
+ pub fn gone(&self, name: &str) -> Option<&'static str> {
+ self.gone
+ .iter()
+ .find(|(gone, _)| *gone == name)
+ .map(|(_, why)| *why)
+ }
+
+ /// Whether the option named `name` is never shown.
+ pub fn secret(&self, name: &str) -> bool {
+ self.spec(name).is_some_and(|spec| spec.secret)
+ }
+
+ /// The options `name` can't be combined with.
+ pub fn conflicting<'a>(&self, name: &'a str) -> impl Iterator<Item = &'static str> + 'a {
+ self.conflicts.iter().flat_map(move |(a, b)| {
+ let other: &'static [&'static str] = if a.contains(&name) {
+ b
+ } else if b.contains(&name) {
+ a
+ } else {
+ &[]
+ };
+ other.iter().copied()
+ })
+ }
+}
+
+/// The value of a text, by the option's kind.
+pub fn from_text(kind: Kind, text: &str) -> Result<JsonValue> {
+ Ok(match kind {
+ Kind::Text => JsonValue::String(text.to_owned()),
+ Kind::Integer => {
+ let number: u64 = text
+ .trim()
+ .parse()
+ .map_err(|_| anyhow!("{text:?} is not a non-negative integer"))?;
+ JsonValue::from(number)
+ }
+ Kind::Duration => {
+ crate::units::parse_duration(text).map_err(|reason| anyhow!(reason))?;
+ JsonValue::String(text.trim().to_owned())
+ }
+ Kind::Size => {
+ crate::units::parse_size(text).map_err(|reason| anyhow!(reason))?;
+ JsonValue::String(text.trim().to_owned())
+ }
+ Kind::Flag => match text.trim() {
+ "true" | "yes" | "1" => JsonValue::Bool(true),
+ "false" | "no" | "0" => JsonValue::Bool(false),
+ _ => bail!("{text:?} is not true or false"),
+ },
+ Kind::List => JsonValue::Array(
+ text.split([',', '\n'])
+ .map(str::trim)
+ .filter(|item| !item.is_empty())
+ .map(|item| JsonValue::String(item.to_owned()))
+ .collect(),
+ ),
+ })
+}