aboutsummaryrefslogtreecommitdiffstats
path: root/src/config
diff options
context:
space:
mode:
Diffstat (limited to 'src/config')
-rw-r--r--src/config/file.rs233
-rw-r--r--src/config/mod.rs618
2 files changed, 57 insertions, 794 deletions
diff --git a/src/config/file.rs b/src/config/file.rs
index 5984c10..b534f93 100644
--- a/src/config/file.rs
+++ b/src/config/file.rs
@@ -1,238 +1,17 @@
-//! Configuration files: TOML (`.toml`) for people, JSON (`.json`) for generated
-//! configuration, with the same keys: the long option names. Nested tables join their
-//! keys with `-`, so `[mycelium] key-file = …` is `mycelium-key-file`.
-//!
-//! `include = [paths]` loads other files first (relative to this one), in the order
-//! listed; an entry `{ path = "…", optional = true }` is skipped where missing. This
-//! file's own values win over theirs, and later includes over earlier ones. A cycle is
-//! an error.
-//!
-//! `unset = [options]` sets options back to their defaults, overriding includes and
-//! earlier files; in JSON, `null` does the same for one option.
+//! Configuration files (`config::file`), read by the node's options: TOML (`.toml`) for
+//! people, JSON (`.json`) for generated configuration, with the same keys.
use std::path::{Path, PathBuf};
-use anyhow::{Context, Result, anyhow, bail};
-use serde_json::{Map as JsonMap, Value as JsonValue};
-use tracing::debug;
+use anyhow::Result;
-use super::import;
-use super::{Entry, Layer, OptionSpec, Overlay, Provenance, UNSET, overlay, spec_in, unset_entry};
-
-const INCLUDE: &str = "include";
-/// Gone: optional includes are entries of `include`, so the order is the list's.
-const INCLUDE_OPTIONAL: &str = "include-optional";
+use super::{Layer, SCHEMA};
/// The settings `path` makes, its includes resolved.
-#[cfg(test)]
-pub(super) fn load(path: &Path) -> Result<Layer> {
- load_with(path, super::OPTIONS)
-}
-
-/// The settings `path` makes of `options`, its includes resolved: a key naming none of
-/// them is an error.
-pub(super) fn load_with(path: &Path, options: &'static [OptionSpec]) -> Result<Layer> {
- load_inner(path, options, &mut Vec::new())
-}
-
-fn load_inner(
- path: &Path,
- options: &'static [OptionSpec],
- loading: &mut Vec<PathBuf>,
-) -> Result<Layer> {
- let canonical = path
- .canonicalize()
- .with_context(|| format!("configuration file {}", path.display()))?;
- if loading.contains(&canonical) {
- bail!("{} includes itself (through {:?})", path.display(), loading);
- }
- let dir = canonical
- .parent()
- .map(Path::to_owned)
- .unwrap_or_else(|| PathBuf::from("/"));
-
- let mut root = parse(&canonical)?;
- if root.contains_key(INCLUDE_OPTIONAL) {
- bail!(
- "{}: include-optional is gone; list the file in include as {{ path = \"…\", optional = true }}, where it goes in the order",
- canonical.display()
- );
- }
- let includes = take_includes(&mut root, &canonical)?;
- let unsets = take_paths(&mut root, UNSET, &canonical)?;
-
- loading.push(canonical.clone());
- let mut layer = Layer::new();
- for (include, required) in includes {
- let include = dir.join(include);
- if !required && !include.exists() {
- debug!(file = %include.display(), "Optional configuration file is missing; skipped");
- continue;
- }
- let included = load_inner(&include, options, loading)
- .with_context(|| format!("included from {}", canonical.display()))?;
- for (name, entry) in included {
- overlay(&mut layer, name, entry, Overlay::IncludeOverInclude);
- }
- }
- loading.pop();
-
- for name in unsets {
- if spec_in(options, &name).is_none() {
- if let Some(why) = super::gone(&name) {
- bail!(
- "option {name:?} in unset, in {}, is gone: {why}",
- canonical.display()
- );
- }
- bail!(
- "unknown option {name:?} in unset, in {}",
- canonical.display()
- );
- }
- let entry = unset_entry(Provenance::File(canonical.clone()));
- overlay(&mut layer, name, entry, Overlay::FileOverFile);
- }
-
- let mut own = Vec::new();
- flatten(&root, "", &dir, &mut own).with_context(|| format!("in {}", canonical.display()))?;
- for (name, value) in own {
- let spec = spec_in(options, &name).ok_or_else(|| match super::gone(&name) {
- Some(why) => anyhow!("option {name:?} in {} is gone: {why}", canonical.display()),
- None => anyhow!("unknown option {name:?} in {}", canonical.display()),
- })?;
- let (value, sources) = super::resolve_file_value(spec, value, &dir)
- .with_context(|| format!("option {name} in {}", canonical.display()))?;
- let entry = Entry {
- origin: sources.origin(
- Provenance::File(canonical.clone()),
- value.is_null(),
- spec.kind,
- ),
- value,
- };
- overlay(&mut layer, name, entry, Overlay::FileOverFile);
- }
- Ok(layer)
-}
-
-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()) {
- 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()))?
- }
- Some("json") => {
- serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))?
- }
- _ => bail!(
- "{}: unknown configuration format (use .toml or .json)",
- path.display()
- ),
- };
- match value {
- JsonValue::Object(map) => Ok(map),
- _ => bail!("{}: the top level must be a table", path.display()),
- }
-}
-
-/// The files `include` names, in its order, and whether each is required: a path, or
-/// `{ path = "…", optional = true }`.
-fn take_includes(
- root: &mut JsonMap<String, JsonValue>,
- path: &Path,
-) -> Result<Vec<(String, bool)>> {
- let items = match root.remove(INCLUDE) {
- None => return Ok(Vec::new()),
- Some(JsonValue::Array(items)) => items,
- Some(single) => vec![single],
- };
- items
- .into_iter()
- .map(|item| match item {
- JsonValue::String(file) => Ok((file, true)),
- JsonValue::Object(mut entry) => {
- let file = match entry.remove("path") {
- Some(JsonValue::String(file)) => file,
- _ => bail!("{}: an include entry needs a path", path.display()),
- };
- let optional = match entry.remove("optional") {
- None => false,
- Some(JsonValue::Bool(optional)) => optional,
- Some(other) => bail!(
- "{}: include's optional is true or false, not {other}",
- path.display()
- ),
- };
- if let Some(key) = entry.keys().next() {
- bail!(
- "{}: unknown key {key:?} in an include entry",
- path.display()
- );
- }
- Ok((file, !optional))
- }
- other => Err(anyhow!(
- "{}: include entries are paths or {{ path, optional }}, not {other}",
- path.display()
- )),
- })
- .collect()
-}
-
-fn take_paths(
- root: &mut JsonMap<String, JsonValue>,
- key: &str,
- path: &Path,
-) -> Result<Vec<String>> {
- match root.remove(key) {
- None => Ok(Vec::new()),
- Some(JsonValue::String(single)) => Ok(vec![single]),
- Some(JsonValue::Array(items)) => items
- .into_iter()
- .map(|item| match item {
- JsonValue::String(item) => Ok(item),
- other => Err(anyhow!(
- "{}: {key} entries must be paths, not {other}",
- path.display()
- )),
- })
- .collect(),
- Some(other) => bail!(
- "{}: {key} must be a list of paths, not {other}",
- path.display()
- ),
- }
-}
-
-/// Option names and values, with nested tables joined by `-`. Importer tables are
-/// values, not nesting.
-fn flatten(
- table: &JsonMap<String, JsonValue>,
- prefix: &str,
- dir: &Path,
- out: &mut Vec<(String, JsonValue)>,
-) -> Result<()> {
- for (key, value) in table {
- let name = if prefix.is_empty() {
- key.clone()
- } else {
- format!("{prefix}-{key}")
- };
- match value {
- JsonValue::Object(nested) if import::parse_table(nested, dir)?.is_none() => {
- flatten(nested, &name, dir, out)?
- }
- _ => out.push((name, value.clone())),
- }
- }
- Ok(())
+fn load(path: &Path) -> Result<Layer> {
+ ::config::file::load(path, &SCHEMA)
}
-#[cfg(test)]
mod tests {
use super::*;
use crate::files::scratch_dir;
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 2f67547..3e7c5d4 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -9,77 +9,68 @@
//! All options are described once, in [`OPTIONS`]: the command line, the file keys and
//! the conversion of text values all derive from it. The merged values are then read
//! into [`Settings`] and checked.
+//!
+//! Files, arguments, layers and importers are the crate `config`'s, which reads them by a
+//! program's options (`SCHEMA`, the node's; `PARTY`, a party's client's); here are the
+//! options, the settings they make, and what is checked and reported of them.
+#[cfg(test)]
mod file;
use std::collections::BTreeMap;
use std::net::SocketAddr;
-use std::path::{Path, PathBuf};
+use std::path::PathBuf;
use std::time::Duration;
use anyhow::{Context, Result, anyhow, bail};
-use clap::parser::ValueSource;
-use clap::{Arg, ArgAction, ArgMatches, Command};
+use clap::{Arg, ArgAction, Command};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
-use tracing::{debug, info, warn};
+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::option::{Kind, OptionSpec, Schema, option};
+
+/// What the node's configuration is read by: its options, those that can't be combined,
+/// and those that are gone.
+pub(crate) const SCHEMA: Schema = Schema {
+ options: OPTIONS,
+ conflicts: CONFLICTS,
+ gone: GONE,
+};
-use ::config::import::{self, Imported, Raw};
+/// What the configuration of a party's client is read by.
+#[cfg(feature = "federation")]
+pub(crate) const PARTY: Schema = Schema::of(PARTY_OPTIONS);
-/// How an option's value is written as text (command line, text imports).
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(crate) 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,
+/// As the crate's, by the node's options: what the tests call.
+#[cfg(test)]
+use ::config::{
+ layer::{Overlay, unset_entry},
+ option::from_text,
+};
+
+#[cfg(test)]
+fn overlay(layer: &mut Layer, name: String, entry: Entry, how: Overlay) {
+ ::config::layer::overlay(layer, name, entry, how, &SCHEMA);
}
-#[derive(Debug)]
-pub(crate) struct OptionSpec {
- pub(crate) name: &'static str,
- pub(crate) kind: Kind,
- pub(crate) value_name: &'static str,
- /// For `--help` only; the effective defaults are in [`Settings`].
- pub(crate) default: Option<&'static str>,
- pub(crate) help: &'static str,
- pub(crate) hidden: bool,
- /// Its value is never shown (logs, `--print-config`, `GET /admin/config`), however
- /// it was given.
- pub(crate) secret: bool,
+#[cfg(test)]
+fn arguments(matches: &clap::ArgMatches) -> Result<Layer> {
+ ::config::arguments::arguments(matches, &SCHEMA)
}
-impl OptionSpec {
- const fn secret(self) -> Self {
- Self {
- secret: true,
- ..self
- }
- }
+#[cfg(test)]
+fn refuse_gone(arguments: impl IntoIterator<Item = String>) -> Result<()> {
+ ::config::arguments::refuse_gone(arguments, &SCHEMA)
}
-pub(crate) 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,
- }
+#[cfg(test)]
+fn gone(name: &str) -> Option<&'static str> {
+ SCHEMA.gone(name)
}
/// What `--force` may override at start (`force`).
@@ -732,11 +723,6 @@ pub(crate) const OPTIONS: &[OptionSpec] = &[
},
];
-/// The option of `options` named `name`.
-pub(super) fn spec_in(options: &'static [OptionSpec], name: &str) -> Option<&'static OptionSpec> {
- options.iter().find(|spec| spec.name == name)
-}
-
/// Options of earlier releases that are gone, each with what to do instead: a node given
/// one, in a configuration file or on its command line, says so and stops, where "unknown
/// option" would leave its operator guessing.
@@ -748,28 +734,6 @@ const GONE: &[(&str, &str)] = &[(
Two proposed at once)",
)];
-/// Why `name` is no option any more, where it was one (`GONE`).
-pub(super) fn gone(name: &str) -> Option<&'static str> {
- GONE.iter()
- .find(|(gone, _)| *gone == name)
- .map(|(_, why)| *why)
-}
-
-/// Stops on an argument naming an option that is gone, saying why, before the command
-/// line is read: clap would call it unexpected.
-fn refuse_gone(arguments: impl IntoIterator<Item = String>) -> Result<()> {
- for argument in arguments {
- let Some(name) = argument.strip_prefix("--") else {
- continue;
- };
- let name = name.split('=').next().unwrap_or(name);
- if let Some(why) = gone(name) {
- bail!("--{name} is gone: {why}");
- }
- }
- Ok(())
-}
-
/// The options of a party's client (`continuum-party`), set as the node's are: on the
/// command line, or in configuration files of the same format (`with_options`,
/// `merged`).
@@ -813,16 +777,6 @@ pub(crate) const PARTY_OPTIONS: &[OptionSpec] = &[
"The party it works as where no record names it, for reading: the one it logs in to the node as, by --key, where --node names no user and no --token is given",
),
];
-#[cfg(not(feature = "federation"))]
-const PARTY_OPTIONS: &[OptionSpec] = &[];
-
-/// Whether `option`, the node's or a party's client's, is never shown.
-fn secret(option: &str) -> bool {
- OPTIONS
- .iter()
- .chain(PARTY_OPTIONS)
- .any(|spec| spec.name == option && spec.secret)
-}
/// The effective configuration.
#[derive(Debug, Clone, Deserialize, Serialize)]
@@ -1571,91 +1525,6 @@ fn check_alias(alias: &str) -> Result<()> {
Ok(())
}
-// --- values and where they came from -------------------------------------------
-
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub(crate) enum Provenance {
- File(PathBuf),
- Argument,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub(crate) struct Origin {
- pub(crate) provenance: Provenance,
- /// The option was unset here (back to its default): `--unset`, `unset = [...]` in a
- /// file, or `null` in a JSON file.
- pub(crate) unset: bool,
- /// Importers the value (or some list elements) came from, e.g. `env:HOSTNAME`. The
- /// value is never shown.
- pub(crate) imports: Vec<String>,
- /// Text with placeholders the value (or some list elements) came from, e.g.
- /// `node-${env:HOSTNAME}`. The value is shown.
- pub(crate) templates: Vec<String>,
- /// With placeholders: the value as written, placeholders and all.
- pub(crate) written: Option<JsonValue>,
-}
-
-impl Origin {
- pub(crate) fn is_imported(&self) -> bool {
- !self.imports.is_empty()
- }
-}
-
-impl std::fmt::Display for Origin {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- match &self.provenance {
- Provenance::File(path) => write!(f, "{}", path.display())?,
- Provenance::Argument => write!(f, "the command line")?,
- }
- if self.unset {
- write!(f, " (unset)")?;
- }
- // Not the text with placeholders: of a secret, it may hold some of it.
- if self.is_imported() {
- write!(f, " ({})", self.imports.join(", "))?;
- }
- Ok(())
- }
-}
-
-#[derive(Debug, Clone)]
-pub(crate) struct Entry {
- pub(crate) value: JsonValue,
- pub(crate) origin: Origin,
-}
-
-impl Entry {
- /// The value of `option` for logs: imported values and secrets are never shown.
- pub(crate) fn shown(&self, option: &str) -> String {
- if self.origin.unset {
- "<default>".to_owned()
- } else if secret(option) {
- "<secret>".to_owned()
- } else if self.origin.is_imported() {
- "<imported>".to_owned()
- } else {
- self.value.to_string()
- }
- }
-}
-
-/// Option name to value. A `null` value unsets the option (back to its default).
-pub(crate) type Layer = BTreeMap<String, Entry>;
-
-/// An unset of `name` from `provenance`.
-fn unset_entry(provenance: Provenance) -> Entry {
- Entry {
- value: JsonValue::Null,
- origin: Origin {
- provenance,
- unset: true,
- imports: Vec::new(),
- templates: Vec::new(),
- written: None,
- },
- }
-}
-
/// Options that can't be combined. A source that sets one side drops the other side's
/// values from earlier sources (lower precedence), so e.g. `--mycelium-rest-url` on the
/// command line overrides `mycelium-key-file` from a file. Both set in one source is an
@@ -1671,235 +1540,6 @@ const CONFLICTS: &[(&[&str], &[&str])] = &[(
],
)];
-/// The options `name` can't be combined with.
-fn conflicting(name: &str) -> impl Iterator<Item = &'static str> + '_ {
- 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()
- })
-}
-
-/// How a later source relates to the earlier ones it overrides (for logging).
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(crate) enum Overlay {
- /// A later include over an earlier include of the same file: usually a mistake.
- IncludeOverInclude,
- /// A file's own values over its includes, or a later `--config` over an earlier.
- FileOverFile,
- /// The command line over files.
- ArgumentOverFile,
-}
-
-/// Puts `entry` for `name` into `layer`, which holds earlier sources, logging what it
-/// replaces and dropping earlier values it can't be combined with.
-pub(crate) fn overlay(layer: &mut Layer, name: String, entry: Entry, how: Overlay) {
- let log = |message: &str, option: &str, previous: &Entry| match how {
- Overlay::IncludeOverInclude => warn!(
- option,
- value = %entry.shown(&name),
- from = %entry.origin,
- overrides = %previous.shown(option),
- overridden_from = %previous.origin,
- "{message}"
- ),
- Overlay::FileOverFile => debug!(
- option,
- from = %entry.origin,
- overrides = %previous.origin,
- "{message}"
- ),
- Overlay::ArgumentOverFile => info!(
- option,
- value = %entry.shown(&name),
- overrides = %previous.shown(option),
- from = %previous.origin,
- "{message}"
- ),
- };
-
- if !entry.value.is_null() {
- for other in conflicting(&name) {
- let earlier = layer
- .get(other)
- .is_some_and(|previous| previous.origin.provenance != entry.origin.provenance);
- if earlier && let Some(previous) = layer.remove(other) {
- log(
- &format!("{name} can't be combined with {other}; dropped the earlier value"),
- other,
- &previous,
- );
- }
- }
- }
- if let Some(previous) = layer.get(&name) {
- let message = match how {
- Overlay::IncludeOverInclude => {
- "Two included configuration files set the same option; the later one wins"
- }
- Overlay::FileOverFile => "Configuration file overrides an earlier one",
- Overlay::ArgumentOverFile => "Command-line argument overrides the configuration file",
- };
- log(message, &name, previous);
- }
- layer.insert(name, entry);
-}
-
-/// The value of a text, by the option's kind.
-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(),
- ),
- })
-}
-
-fn from_import(kind: Kind, importer: &import::Importer) -> Result<JsonValue> {
- match importer.fetch()? {
- Imported::Text(text) => from_text(kind, &text),
- Imported::Json(value) => Ok(value),
- // As it is: one text, its line breaks kept, read as nothing else.
- Imported::Raw(bytes) => String::from_utf8(bytes)
- .map(JsonValue::String)
- .map_err(|_| anyhow!("{} is not UTF-8: an option is text", importer.describe())),
- }
-}
-
-/// A value from a file in `dir`: importer tables are resolved, also as list elements.
-/// Collects where the parts of a value came from, for its [`Origin`].
-#[derive(Default)]
-struct Sources {
- imports: Vec<String>,
- templates: Vec<String>,
- /// The parts as written: literal values, importers, text with placeholders.
- written: Vec<JsonValue>,
-}
-
-impl Sources {
- /// A literal part (list values count element by element).
- fn literal(&mut self, value: &JsonValue) {
- match value {
- JsonValue::Array(items) => self.written.extend(items.iter().cloned()),
- other => self.written.push(other.clone()),
- }
- }
-
- /// A part from `importer`.
- fn import(&mut self, importer: &import::Importer) {
- let described = importer.describe();
- if importer.is_interpolation() {
- self.templates.push(described.clone());
- } else {
- self.imports.push(described.clone());
- }
- self.written.push(JsonValue::String(described));
- }
-
- fn origin(self, provenance: Provenance, unset: bool, kind: Kind) -> Origin {
- let written = (!self.templates.is_empty()).then(|| match kind {
- Kind::List => JsonValue::Array(self.written),
- _ => self.written.into_iter().last().unwrap_or(JsonValue::Null),
- });
- Origin {
- provenance,
- unset,
- imports: self.imports,
- templates: self.templates,
- written,
- }
- }
-}
-
-/// A value from a file, and where its parts came from.
-fn resolve_file_value(
- spec: &OptionSpec,
- value: JsonValue,
- dir: &Path,
-) -> Result<(JsonValue, Sources)> {
- let mut sources = Sources::default();
- let value = match value {
- JsonValue::Object(table) => match import::parse_table(&table, dir)? {
- Some(importer) => {
- sources.import(&importer);
- from_import(spec.kind, &importer)?
- }
- None => bail!("a table here must be an importer (env, file or command)"),
- },
- JsonValue::String(text) => match import::interpolated(&text, Some(dir)) {
- Some(importer) => {
- sources.import(&importer);
- from_import(spec.kind, &importer)?
- }
- None => JsonValue::String(text),
- },
- JsonValue::Array(items) if spec.kind == Kind::List => {
- let mut values = Vec::new();
- for item in items {
- match item {
- JsonValue::Object(table) => {
- let importer = import::parse_table(&table, dir)?.ok_or_else(|| {
- anyhow!("a table here must be an importer (env, file or command)")
- })?;
- match from_import(Kind::List, &importer)? {
- JsonValue::Array(more) => values.extend(more),
- other => values.push(other),
- }
- sources.import(&importer);
- }
- JsonValue::String(text) => match import::interpolated(&text, Some(dir)) {
- Some(importer) => {
- values.push(from_import(Kind::Text, &importer)?);
- sources.import(&importer);
- }
- None => {
- let value = JsonValue::String(text);
- sources.literal(&value);
- values.push(value);
- }
- },
- other => {
- sources.literal(&other);
- values.push(other);
- }
- }
- }
- JsonValue::Array(values)
- }
- other => other,
- };
- Ok((value, sources))
-}
-
/// 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)| {
@@ -1914,10 +1554,7 @@ fn culprit(merged: &Layer) -> Option<(&String, &Entry)> {
// --- command line --------------------------------------------------------------
-const CONFIG: &str = "config";
const PRINT_CONFIG: &str = "print-config";
-/// Undoing a value set before: the argument `--unset`, and the key `unset` in a file.
-pub(super) const UNSET: &str = "unset";
fn command() -> Command {
let command = Command::new("continuum")
@@ -1950,112 +1587,6 @@ fn command() -> Command {
/// `continuum node-id FILE`: the node ID of the key in `FILE` (`Loaded::node_id`).
const NODE_ID: &str = "node-id";
-/// `command` taking `options` as arguments, and configuration files for them
-/// (`--config`) and unsets of what those set (`--unset`).
-pub(crate) fn with_options(command: Command, options: &'static [OptionSpec]) -> Command {
- let mut command = command
- .after_help(
- "Every option can also be set in a configuration file (--config); arguments win.\n\
- A value can be imported instead of written out: env:NAME, file:PATH or cmd:COMMAND \
- (as text), or env+json:, file+json:, cmd+json: (parsed as JSON). \
- literal:VALUE passes a value that starts with one of these prefixes.",
- )
- .arg(
- Arg::new(CONFIG)
- .long(CONFIG)
- .value_name("PATH")
- .action(ArgAction::Append)
- .help("Configuration file (.toml or .json); repeatable, later files win."),
- )
- .arg(
- Arg::new(UNSET)
- .long(UNSET)
- .value_name("OPTION")
- .action(ArgAction::Append)
- .help("Unset an option set by a configuration file (back to its default); repeatable."),
- );
- for spec in options {
- let help = match spec.default {
- Some(default) => format!("{} [default: {default}]", spec.help),
- None => spec.help.to_owned(),
- };
- let arg = Arg::new(spec.name)
- .long(spec.name)
- .help(help)
- .hide(spec.hidden);
- command = command.arg(match spec.kind {
- Kind::Flag => arg.action(ArgAction::SetTrue),
- Kind::List => arg.value_name(spec.value_name).action(ArgAction::Append),
- Kind::Text | Kind::Integer | Kind::Duration | Kind::Size => {
- arg.value_name(spec.value_name).action(ArgAction::Set)
- }
- });
- }
- command
-}
-
-/// The values given as arguments (unsets first, so a value given too wins).
-#[cfg(test)]
-fn arguments(matches: &ArgMatches) -> Result<Layer> {
- arguments_with(matches, OPTIONS)
-}
-
-/// The values of `options` given as arguments (unsets first, so a value given too wins).
-fn arguments_with(matches: &ArgMatches, options: &'static [OptionSpec]) -> Result<Layer> {
- let mut layer = Layer::new();
- for name in matches.get_many::<String>(UNSET).into_iter().flatten() {
- if spec_in(options, name).is_none() {
- bail!("--unset {name}: no such option");
- }
- layer.insert(name.clone(), unset_entry(Provenance::Argument));
- }
- for spec in options {
- if matches.value_source(spec.name) != Some(ValueSource::CommandLine) {
- continue;
- }
- let mut sources = Sources::default();
- let value = if spec.kind == Kind::Flag {
- JsonValue::Bool(true)
- } else {
- let mut values = Vec::new();
- for raw in matches.get_many::<String>(spec.name).into_iter().flatten() {
- let value = match import::parse_argument(raw) {
- Raw::Literal(text) => from_text(spec.kind, text).inspect(|value| {
- sources.literal(value);
- }),
- Raw::Import(importer) => {
- sources.import(&importer);
- from_import(spec.kind, &importer)
- }
- }
- .with_context(|| format!("--{}", spec.name))?;
- values.push(value);
- }
- if spec.kind == Kind::List {
- JsonValue::Array(
- values
- .into_iter()
- .flat_map(|value| match value {
- JsonValue::Array(items) => items,
- other => vec![other],
- })
- .collect(),
- )
- } else {
- values.pop().unwrap_or(JsonValue::Null)
- }
- };
- layer.insert(
- spec.name.to_owned(),
- Entry {
- value,
- origin: sources.origin(Provenance::Argument, false, spec.kind),
- },
- );
- }
- Ok(layer)
-}
-
/// The configuration, and where each value set came from (absent: default).
#[derive(Debug, Clone)]
pub(crate) struct Loaded {
@@ -2197,7 +1728,7 @@ impl Loaded {
/// Reads the command line and the configuration files it names. Exits on `--help`,
/// `--version` and command-line syntax errors, like any command.
pub(crate) fn load() -> Result<Loaded> {
- refuse_gone(std::env::args().skip(1))?;
+ ::config::arguments::refuse_gone(std::env::args().skip(1), &SCHEMA)?;
let matches = command().get_matches();
let print_only = matches.get_flag(PRINT_CONFIG);
let node_id = matches.subcommand_matches(NODE_ID).map(|sub| {
@@ -2209,63 +1740,13 @@ pub(crate) fn load() -> Result<Loaded> {
// says where each value came from anyway).
let _ = crate::logging::set_filter("off");
}
- let (merged, files) = merged(&matches, OPTIONS)?;
+ let (merged, files) = merged(&matches, &SCHEMA, &[])?;
let mut loaded = resolve(merged, files)?;
loaded.print_only = print_only;
loaded.node_id = node_id;
Ok(loaded)
}
-/// The values of `options`: from the configuration files `matches` names (`--config`), in
-/// order, then from its arguments; and those files.
-pub(crate) fn merged(
- matches: &ArgMatches,
- options: &'static [OptionSpec],
-) -> Result<(Layer, Vec<PathBuf>)> {
- merged_with(matches, options, &[])
-}
-
-/// As `merged`, the files `first` read before those `matches` names, which win over them.
-pub(crate) fn merged_with(
- matches: &ArgMatches,
- options: &'static [OptionSpec],
- first: &[PathBuf],
-) -> Result<(Layer, Vec<PathBuf>)> {
- let files: Vec<PathBuf> = first
- .iter()
- .cloned()
- .chain(
- matches
- .get_many::<String>(CONFIG)
- .into_iter()
- .flatten()
- .map(PathBuf::from),
- )
- .collect();
- let mut merged = Layer::new();
- for path in &files {
- for (name, entry) in file::load_with(path, options)? {
- overlay(&mut merged, name, entry, Overlay::FileOverFile);
- }
- }
- for (name, entry) in arguments_with(matches, options)? {
- overlay(&mut merged, name, entry, Overlay::ArgumentOverFile);
- }
- Ok((merged, files))
-}
-
-/// `T` read from the values `merged` sets, each option's by its name: those unset take
-/// `T`'s defaults.
-#[cfg(feature = "federation")]
-pub(crate) 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}"))
-}
-
/// HyParView's active view, where `neighbours` isn't set: the paper's, for swarms of up
/// to about 10 000 members (its fanout of 4, plus one).
const HYPARVIEW_NEIGHBOURS: usize = 5;
@@ -2939,7 +2420,10 @@ mod tests {
.unwrap();
let mut layer = arguments(&matches).unwrap();
assert!(!layer["alias"].origin.is_imported());
- assert_eq!(layer["alias"].shown("alias"), "\"node-berlin\"");
+ assert_eq!(
+ layer["alias"].shown(SCHEMA.secret("alias")),
+ "\"node-berlin\""
+ );
with_built_transport(&mut layer);
let loaded = resolve(layer, Vec::new()).unwrap();
@@ -2979,7 +2463,7 @@ mod tests {
json!({ "htpasswd": "users", "node-key-file": "node.key", "mycelium-rest-url": "http://u:pw@h:8989" }),
);
assert_eq!(
- values["mycelium-rest-url"].shown("mycelium-rest-url"),
+ values["mycelium-rest-url"].shown(SCHEMA.secret("mycelium-rest-url")),
"<secret>"
);
let loaded = resolve(values, Vec::new()).unwrap();