From 2be9ca2b75d099a9ca04078f2182acda074ed270 Mon Sep 17 00:00:00 2001 From: tv Date: Wed, 2 Dec 2026 16:24:19 +0000 Subject: config: a configuration names importers of its own [meta.importer] in a file, or --meta-importer-NAME IMPORTER, names an importer: NAME:REST, { NAME = "REST" } and a placeholder of that name are then that importer, with REST as its variable `name`. So what would be built in for one tool, pass:NAME, is written by who uses it, once: pass = { command = ["pass", "show", "$(var:name)"] }. A name counts in every file and argument, wherever it is given; of two of one name, the later source's. What follows the name goes in as every variable does, as data. One named may be defined through others, not through itself. `meta` at the top of a configuration file is what the configuration says about itself. The argument is spelled as every option's, the table's keys joined with `-`; as its name is the configuration's, it is taken off the command line before the command reads it. --- CHANGELOG.md | 9 + crates/config/src/arguments.rs | 196 ++++++++++++++++++- crates/config/src/file.rs | 104 +++++++++- crates/config/src/import.rs | 419 +++++++++++++++++++++++++++++++++++++---- crates/config/src/layer.rs | 42 ++++- docs/configuration.md | 51 +++++ src/config/mod.rs | 22 ++- src/federation/party.rs | 10 +- 8 files changed, 785 insertions(+), 68 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 81db46c..3fe9e73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,15 @@ it from the release before ([`docs/operations.md`](docs/operations.md), ([`docs/configuration.md`](docs/configuration.md), [Importing values](docs/configuration.md#importing-values)). +* A configuration names importers of its own: `[meta.importer]` in a file, or + `--meta-importer-NAME IMPORTER`, makes `NAME:REST`, `{ NAME = "REST" }` and + `$(NAME:REST)` that importer, with `REST` as its variable `name`: a secret store's + command is written once, `pass = { command = ["pass", "show", "$(var:name)"] }`. A + top-level `meta` in a configuration file is this table's now + ([`docs/configuration.md`](docs/configuration.md), + [Naming importers](docs/configuration.md#naming-importers); + [`crates/config/src/import.rs`](crates/config/src/import.rs)). + * The Swagger UI (`/swagger-ui`) is a feature, `swagger-ui`, no longer built into every node: a build that is to serve it names the feature. `/openapi.yaml` is served as before ([`docs/development.md`](docs/development.md)). diff --git a/crates/config/src/arguments.rs b/crates/config/src/arguments.rs index 4a251da..2cb26b3 100644 --- a/crates/config/src/arguments.rs +++ b/crates/config/src/arguments.rs @@ -3,19 +3,24 @@ use std::path::PathBuf; -use anyhow::{Context, Result, bail}; +use anyhow::{Context, Result, anyhow, bail}; use clap::parser::ValueSource; use clap::{Arg, ArgAction, ArgMatches, Command}; use serde_json::Value as JsonValue; use crate::file::{self, UNSET}; use crate::import::{self, Raw}; -use crate::layer::{Entry, Layer, Overlay, Provenance, Sources, from_import, overlay, unset_entry}; +use crate::layer::{ + Entry, Layer, Overlay, Provenance, Sources, from_import_in, overlay, unset_entry, +}; 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"; +/// Naming an importer (`import::Importers`): `--meta-importer-NAME IMPORTER`, as +/// `[meta.importer] NAME = …` in a file (`take_importers`). +pub const META_IMPORTER: &str = "meta-importer"; /// `command` taking `--print-config`: a program given it prints its configuration's /// report (`report::report`) and exits (`prints_config`). @@ -65,6 +70,14 @@ pub fn with_options(command: Command, options: &'static [OptionSpec]) -> Command .action(ArgAction::Append) .help("Configuration file (.toml or .json); repeatable, later files win."), ) + .arg( + // For the help alone: the names are whatever follows `--meta-importer-`, + // taken off the command line before it is read (`take_importers`). + Arg::new(META_IMPORTER) + .long("meta-importer-NAME") + .value_name("IMPORTER") + .help("Name an importer: NAME:REST is then IMPORTER (env:, file:, cmd:), with REST as its variable `name`, in every file and argument; as [meta.importer] NAME in a file."), + ) .arg( Arg::new(UNSET) .long(UNSET) @@ -92,8 +105,67 @@ pub fn with_options(command: Command, options: &'static [OptionSpec]) -> Command command } -/// The values of `options` given as arguments (unsets first, so a value given too wins). +/// The arguments `arguments` without those naming importers (`--meta-importer-NAME +/// IMPORTER`, or with `=`), and the importers they name: taken off before the command +/// line is read, as their names are the configuration's, not the command's. Nothing +/// after `--` is one. +pub fn take_importers( + arguments: impl IntoIterator, +) -> Result<(Vec, import::Importers)> { + let prefix = format!("--{META_IMPORTER}-"); + let mut named = import::Importers::new(); + let mut others = Vec::new(); + let mut arguments = arguments.into_iter(); + while let Some(argument) = arguments.next() { + if argument == "--" { + others.push(argument); + others.extend(arguments); + break; + } + let Some(rest) = argument.strip_prefix(&prefix) else { + others.push(argument); + continue; + }; + let (name, importer) = match rest.split_once('=') { + Some((name, importer)) => (name.to_owned(), importer.to_owned()), + None => { + let importer = arguments + .next() + .ok_or_else(|| anyhow!("{argument} takes an importer"))?; + (rest.to_owned(), importer) + } + }; + let importer = import::named_by_argument(&name, &importer) + .with_context(|| format!("{prefix}{name}"))?; + named.insert(name, importer); + } + Ok((others, named)) +} + +/// The importers the configuration names: those of the files `files`, in order, then +/// `by_arguments`, those its arguments name (`take_importers`); of two of one name, the +/// later. +pub fn importers(files: &[PathBuf], by_arguments: &import::Importers) -> Result { + let mut named = import::Importers::new(); + for path in files { + named.extend(file::importers(path)?); + } + named.extend(by_arguments.clone()); + Ok(named) +} + +/// The values of `options` given as arguments, where no importers are named. pub fn arguments(matches: &ArgMatches, schema: &Schema) -> Result { + arguments_in(matches, schema, &import::Importers::new()) +} + +/// The values of `options` given as arguments (unsets first, so a value given too wins); +/// `named` are the importers the configuration names. +pub fn arguments_in( + matches: &ArgMatches, + schema: &Schema, + named: &import::Importers, +) -> Result { let mut layer = Layer::new(); for name in matches.get_many::(UNSET).into_iter().flatten() { if schema.spec(name).is_none() { @@ -111,13 +183,13 @@ pub fn arguments(matches: &ArgMatches, schema: &Schema) -> Result { } else { let mut values = Vec::new(); for raw in matches.get_many::(spec.name).into_iter().flatten() { - let value = match import::parse_argument(raw) { + let value = match import::parse_argument_in(raw, named) { Raw::Literal(text) => from_text(spec.kind, text).inspect(|value| { sources.literal(value); }), Raw::Import(importer) => { sources.import(&importer); - from_import(spec.kind, &importer) + from_import_in(spec.kind, &importer, named) } } .with_context(|| format!("--{}", spec.name))?; @@ -155,6 +227,16 @@ pub fn merged( matches: &ArgMatches, schema: &Schema, first: &[PathBuf], +) -> Result<(Layer, Vec)> { + merged_in(matches, schema, first, &import::Importers::new()) +} + +/// `merged`, with the importers the arguments name (`take_importers`). +pub fn merged_in( + matches: &ArgMatches, + schema: &Schema, + first: &[PathBuf], + by_arguments: &import::Importers, ) -> Result<(Layer, Vec)> { let files: Vec = first .iter() @@ -167,13 +249,14 @@ pub fn merged( .map(PathBuf::from), ) .collect(); + let named = importers(&files, by_arguments)?; let mut merged = Layer::new(); for path in &files { - for (name, entry) in file::load(path, schema)? { + for (name, entry) in file::load_in(path, schema, &named)? { overlay(&mut merged, name, entry, Overlay::FileOverFile, schema); } } - for (name, entry) in arguments(matches, schema)? { + for (name, entry) in arguments_in(matches, schema, &named)? { overlay(&mut merged, name, entry, Overlay::ArgumentOverFile, schema); } Ok((merged, files)) @@ -201,10 +284,12 @@ mod tests { }; fn merged_of(arguments: &[&str]) -> Result { + let (arguments, named) = + take_importers(arguments.iter().map(|argument| (*argument).to_owned()))?; let command = with_options(Command::new("program"), OPTIONS); - let matches = command - .try_get_matches_from(std::iter::once("program").chain(arguments.iter().copied()))?; - merged(&matches, &SCHEMA, &[]).map(|(layer, _)| layer) + let matches = + command.try_get_matches_from(std::iter::once("program".to_owned()).chain(arguments))?; + merged_in(&matches, &SCHEMA, &[], &named).map(|(layer, _)| layer) } /// A program's own options, by its schema: files in order, a file over its @@ -301,4 +386,95 @@ mod tests { assert!(said.to_string().contains("use name instead")); assert!(refuse_gone(["--name".to_owned()], &SCHEMA).is_ok()); } + + /// Importers a configuration names (`[meta.importer]`, `--meta-importer-NAME`) count in + /// every file and argument, wherever they are named; of two of one name, the later + /// source's. + #[test] + fn importers_named_in_files_and_arguments() { + let scratch = Scratch::new("arguments-importers"); + let path = |name: &str| scratch.0.join(name).display().to_string(); + scratch.file( + "names.json", + r#"{"meta": {"importer": { + "show": {"command": ["printf", "<%s>", "$(var:name)"]}, + "kept": "file:$(var:name)"}}}"#, + ); + scratch.file( + "main.json", + r#"{"include": ["names.json"], "name": {"show": "main"}, "token": {"kept": "secret"}, + "peers": ["a", "$(show:b)", {"show": "c"}]}"#, + ); + scratch.file("secret", "hush\n"); + let layer = merged_of(&["--config", &path("main.json")]).unwrap(); + assert_eq!(layer["name"].value, json!("
")); + assert_eq!(layer["token"].value, json!("hush")); + assert_eq!(layer["peers"].value, json!(["a", "", ""])); + // Shown as written, not as what it stands for. + assert_eq!(layer["name"].origin.imports, ["show:main"]); + + // Named in a later file, or by an argument: in an earlier file too; and in + // arguments. + scratch.file( + "first.json", + r#"{"name": {"late": "x"}, "local": "$(late:y)"}"#, + ); + scratch.file( + "later.json", + r#"{"meta": {"importer": {"late": "cmd:printf 'later-%s' $(var:name)"}}}"#, + ); + let files = [ + "--config", + &path("first.json"), + "--config", + &path("later.json"), + ]; + let layer = merged_of(&files).unwrap(); + assert_eq!(layer["name"].value, json!("later-x")); + assert_eq!(layer["local"].value, json!("later-y")); + // Of two of one name, the argument's, over the files'. + let mut by_argument = files.to_vec(); + by_argument.extend([ + "--meta-importer-late", + "cmd:printf 'argument-%s' $(var:name)", + "--remote", + "late:z", + ]); + let layer = merged_of(&by_argument).unwrap(); + assert_eq!(layer["name"].value, json!("argument-x")); + assert_eq!(layer["remote"].value, json!("argument-z")); + // Unnamed, it is text on the command line, and no importer in a file. + let layer = merged_of(&["--name", "late:z"]).unwrap(); + assert_eq!(layer["name"].value, json!("late:z")); + assert!(merged_of(&["--config", &path("first.json")]).is_err()); + + // What `meta` takes. + for (file, refused) in [ + ("other.json", r#"{"meta": {"other": 1}}"#), + ("list.json", r#"{"meta": {"importer": ["a"]}}"#), + ( + "builtin.json", + r#"{"meta": {"importer": {"env": "cmd:true"}}}"#, + ), + ("text.json", r#"{"meta": 1}"#), + ] { + scratch.file(file, refused); + assert!(merged_of(&["--config", &path(file)]).is_err(), "{refused}"); + } + // With `=`, too; and what it takes. + let layer = merged_of(&[ + "--meta-importer-late=cmd:printf '=%s' $(var:name)", + "--name", + "late:z", + ]) + .unwrap(); + assert_eq!(layer["name"].value, json!("=z")); + assert!(merged_of(&["--meta-importer-late"]).is_err()); + assert!(merged_of(&["--meta-importer-late", "plain"]).is_err()); + assert!(merged_of(&["--meta-importer-file", "cmd:true"]).is_err()); + // After `--`, it is the command's. + let (rest, named) = + take_importers(["--", "--meta-importer-late", "cmd:true"].map(str::to_owned)).unwrap(); + assert_eq!((rest.len(), named.len()), (3, 0)); + } } diff --git a/crates/config/src/file.rs b/crates/config/src/file.rs index b365623..1c88c15 100644 --- a/crates/config/src/file.rs +++ b/crates/config/src/file.rs @@ -7,6 +7,12 @@ //! file's own values win over theirs, and later includes over earlier ones. A cycle is //! an error. //! +//! `[meta.importer]` names importers (`import::Importers`): `NAME = { command = […] }` +//! makes `NAME:REST` and `{ NAME = "REST" }` that importer, with `REST` as its variable +//! `name`. A name counts in every file and argument of the configuration, wherever it +//! is given; of two of one name, the later source's: a file's own over its includes', +//! a later file's over an earlier one's, an argument's over them all. +//! //! `unset = [options]` sets options back to their defaults, overriding includes and //! earlier files; in JSON, `null` does the same for one option. @@ -16,22 +22,96 @@ use anyhow::{Context, Result, anyhow, bail}; use serde_json::{Map as JsonMap, Value as JsonValue}; use crate::import; -use crate::layer::{Entry, Layer, Overlay, Provenance, overlay, resolve_file_value, unset_entry}; +use crate::layer::{ + Entry, Layer, Overlay, Provenance, overlay, resolve_file_value_in, unset_entry, +}; use crate::option::Schema; +/// Configuration about the configuration: what a file says under `meta`. +const META: &str = "meta"; +/// Under `meta`: the importers the file names. +const IMPORTERS: &str = "importer"; const INCLUDE: &str = "include"; /// Undoing a value set before: the key `unset` in a file, and the argument `--unset`. pub const UNSET: &str = "unset"; /// Gone: optional includes are entries of `include`, so the order is the list's. const INCLUDE_OPTIONAL: &str = "include-optional"; -/// The settings `path` makes of the options of `schema`, its includes resolved: a key -/// naming none of them is an error. +/// The importers `path` names (`[meta.importer]`), its includes' first, its own over +/// theirs. +pub fn importers(path: &Path) -> Result { + importers_inner(path, &mut Vec::new()) +} + +fn importers_inner(path: &Path, loading: &mut Vec) -> Result { + 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)?; + let includes = take_includes(&mut root, &canonical)?; + let mut named = import::Importers::new(); + loading.push(canonical.clone()); + for (include, required) in includes { + let include = dir.join(include); + if !required && !include.exists() { + continue; + } + named.extend( + importers_inner(&include, loading) + .with_context(|| format!("included from {}", canonical.display()))?, + ); + } + loading.pop(); + named + .extend(take_meta(&mut root, &dir).with_context(|| format!("in {}", canonical.display()))?); + Ok(named) +} + +/// What `root` says under `meta`, taken out of it: the importers it names. +fn take_meta(root: &mut JsonMap, dir: &Path) -> Result { + let Some(meta) = root.remove(META) else { + return Ok(import::Importers::new()); + }; + let JsonValue::Object(mut meta) = meta else { + bail!("meta must be a table"); + }; + let importers = match meta.remove(IMPORTERS) { + None => import::Importers::new(), + Some(JsonValue::Object(table)) => import::named_in_table(&table, dir)?, + Some(other) => bail!("meta.importer must be a table, not {other}"), + }; + if let Some(unknown) = meta.keys().next() { + bail!("unknown key {unknown:?} in meta"); + } + Ok(importers) +} + +/// The settings `path` makes of the options of `schema`, as `load_in`, by the +/// importers it names itself. pub fn load(path: &Path, schema: &Schema) -> Result { - load_inner(path, schema, &mut Vec::new()) + load_in(path, schema, &importers(path)?) } -fn load_inner(path: &Path, schema: &Schema, loading: &mut Vec) -> Result { +/// The settings `path` makes of the options of `schema`, its includes resolved: a key +/// naming none of them is an error. `named` are the importers the configuration +/// names, here and elsewhere. +pub fn load_in(path: &Path, schema: &Schema, named: &import::Importers) -> Result { + load_inner(path, schema, named, &mut Vec::new()) +} + +fn load_inner( + path: &Path, + schema: &Schema, + named: &import::Importers, + loading: &mut Vec, +) -> Result { let canonical = path .canonicalize() .with_context(|| format!("configuration file {}", path.display()))?; @@ -51,6 +131,8 @@ fn load_inner(path: &Path, schema: &Schema, loading: &mut Vec) -> Resul ); } let includes = take_includes(&mut root, &canonical)?; + // Read apart, for every file and argument (`importers`). + take_meta(&mut root, &dir).with_context(|| format!("in {}", canonical.display()))?; let unsets = take_paths(&mut root, UNSET, &canonical)?; loading.push(canonical.clone()); @@ -62,7 +144,7 @@ fn load_inner(path: &Path, schema: &Schema, loading: &mut Vec) -> Resul tracing::debug!(file = %include.display(), "Optional configuration file is missing; skipped"); continue; } - let included = load_inner(&include, schema, loading) + let included = load_inner(&include, schema, named, loading) .with_context(|| format!("included from {}", canonical.display()))?; for (name, entry) in included { overlay(&mut layer, name, entry, Overlay::IncludeOverInclude, schema); @@ -88,13 +170,14 @@ fn load_inner(path: &Path, schema: &Schema, loading: &mut Vec) -> Resul } let mut own = Vec::new(); - flatten(&root, "", &dir, &mut own).with_context(|| format!("in {}", canonical.display()))?; + flatten(&root, "", &dir, named, &mut own) + .with_context(|| format!("in {}", canonical.display()))?; for (name, value) in own { let spec = schema.spec(&name).ok_or_else(|| match schema.gone(&name) { Some(why) => anyhow!("option {name:?} in {} is gone: {why}", canonical.display()), None => anyhow!("unknown option {name:?} in {}", canonical.display()), })?; - let (value, sources) = resolve_file_value(spec, value, &dir) + let (value, sources) = resolve_file_value_in(spec, value, &dir, named) .with_context(|| format!("option {name} in {}", canonical.display()))?; let entry = Entry { origin: sources.origin( @@ -214,6 +297,7 @@ fn flatten( table: &JsonMap, prefix: &str, dir: &Path, + named: &import::Importers, out: &mut Vec<(String, JsonValue)>, ) -> Result<()> { for (key, value) in table { @@ -223,8 +307,8 @@ fn flatten( format!("{prefix}-{key}") }; match value { - JsonValue::Object(nested) if import::parse_table(nested, dir)?.is_none() => { - flatten(nested, &name, dir, out)? + JsonValue::Object(nested) if import::parse_table_in(nested, dir, named)?.is_none() => { + flatten(nested, &name, dir, named, out)? } _ => out.push((name, value.clone())), } diff --git a/crates/config/src/import.rs b/crates/config/src/import.rs index 7305b49..c5d058a 100644 --- a/crates/config/src/import.rs +++ b/crates/config/src/import.rs @@ -38,6 +38,12 @@ //! names it, and those given. So what differs from one use to the next is a variable, //! and the importer is written once: `["secrets", "$(env:HOSTNAME)", "show", //! "$(var:key)"]`. +//! +//! A configuration may name importers of its own (`Importers`; `[meta.importer]` in a +//! file, `--meta-importer-NAME`, which `file` and `arguments` read): `NAME:REST`, +//! `{ NAME = "REST" }` and `$(NAME:REST)` are then the importer of that name, with +//! `REST` as its variable `name` (`fetch_in`). None is built in for a tool: `pass:NAME` +//! is `pass = { command = ["pass", "show", "$(var:name)"] }`, written by who uses it. use std::ffi::OsString; use std::os::unix::ffi::OsStringExt; @@ -51,6 +57,36 @@ use serde_json::{Map as JsonMap, Value as JsonValue}; /// (`Importer::fetch_with`): a `var:NAME` placeholder is replaced by it. pub type Variables = std::collections::BTreeMap>; +/// Importers a configuration names itself (`[meta.importer]`, `--meta-importer-NAME`), by +/// name: `NAME:REST` is the importer of that name, with `REST` as its variable `name`. +/// So what would be built in for one tool (`pass:NAME`) is written by who uses it: +/// `pass = { command = ["pass", "show", "$(var:name)"] }`. +pub type Importers = std::collections::BTreeMap; + +/// What a program and its configuration give to importers: variables and named +/// importers. +#[derive(Clone, Copy)] +struct Given<'a> { + variables: &'a Variables, + importers: &'a Importers, + /// How many named importers deep this is: one named by itself, directly or + /// through others, ends at `DEEPEST`. + depth: usize, +} + +/// How many named importers one may be defined through. +const DEEPEST: usize = 8; + +/// No named importers. +static UNNAMED: Importers = Importers::new(); + +/// What a named importer may not be called: the kinds built in, and what else a +/// value or an importer table reads as its own. +const RESERVED: [&str; 7] = ["env", "file", "cmd", "command", "var", "literal", "format"]; + +/// The variable a named importer gets what follows its name as. +pub const NAME: &str = "name"; + /// No variables: what `Importer::fetch` gives. static NONE: Variables = Variables::new(); @@ -84,6 +120,12 @@ pub enum Source { Shell(String), /// A program and its arguments, run without a shell. Argv(Vec), + /// A named importer (`Importers`), and what follows its name, which may hold + /// placeholders: its variable `name`. + Named { + importer: String, + name: String, + }, /// Text with placeholders (`interpolated`). Template(String), } @@ -104,8 +146,13 @@ pub enum Raw<'a> { Literal(&'a str), } -/// Reads a command-line value. +/// Reads a command-line value, where no importers are named. pub fn parse_argument(raw: &str) -> Raw<'_> { + parse_argument_in(raw, &UNNAMED) +} + +/// Reads a command-line value: `NAME:REST` is the importer `NAME` of `importers`. +pub fn parse_argument_in<'a>(raw: &'a str, importers: &Importers) -> Raw<'a> { if let Some(rest) = raw.strip_prefix("literal:") { return Raw::Literal(rest); } @@ -122,6 +169,10 @@ pub fn parse_argument(raw: &str) -> Raw<'_> { "env" => Source::Env(rest.to_owned()), "file" => Source::File(PathBuf::from(rest)), "cmd" => Source::Shell(rest.to_owned()), + named if importers.contains_key(named) => Source::Named { + importer: named.to_owned(), + name: rest.to_owned(), + }, _ => return literal_or_interpolated(raw), }; Raw::Import(Importer { @@ -131,6 +182,77 @@ pub fn parse_argument(raw: &str) -> Raw<'_> { }) } +/// Whether `importer` may be named `name` (`Importers`): a name of small letters, +/// digits and `-`, beginning with a letter, and none of the kinds built in; an importer +/// built in, of no format of its own, as what names it says how its content is read. +pub fn define(name: &str, importer: &Importer) -> Result<()> { + let spelled = name.starts_with(|first: char| first.is_ascii_lowercase()) + && name + .chars() + .all(|char| char.is_ascii_lowercase() || char.is_ascii_digit() || char == '-'); + if !spelled { + bail!("an importer's name is small letters, digits and `-`, a letter first: not {name:?}"); + } + if RESERVED.contains(&name) { + bail!("an importer can't be named {name:?}: that is built in"); + } + match importer.source { + Source::Template(_) => bail!( + "the importer named {name:?} must be env:, file: or a command, not text with \ + placeholders" + ), + Source::Named { .. } => { + bail!( + "the importer named {name:?} must be env:, file: or a command, not another named one" + ) + } + Source::Env(_) | Source::File(_) | Source::Shell(_) | Source::Argv(_) => {} + } + if importer.format != Format::Text { + bail!( + "the importer named {name:?} takes no format: what names it says so \ + ({name}+raw:…, {name}+json:…)" + ); + } + Ok(()) +} + +/// The importers a file in `dir` names (`[meta.importer]`): each an importer table, or +/// an importer as arguments spell them (`cmd:pass show …`). +pub fn named_in_table(table: &JsonMap, dir: &Path) -> Result { + let mut importers = Importers::new(); + for (name, value) in table { + let importer = match value { + JsonValue::Object(object) => parse_table(object, dir)?.ok_or_else(|| { + anyhow!("the importer named {name:?} must be an importer (env, file or command)") + })?, + JsonValue::String(text) => match parse_argument(text) { + Raw::Import(mut importer) => { + importer.dir = Some(dir.to_owned()); + importer + } + Raw::Literal(_) => { + bail!("the importer named {name:?} must be env:, file: or cmd:, not {text:?}") + } + }, + other => bail!("the importer named {name:?} must be an importer, not {other}"), + }; + define(name, &importer)?; + importers.insert(name.clone(), importer); + } + Ok(importers) +} + +/// The importer an argument names `name` (`--meta-importer-NAME IMPORTER`), the importer +/// as arguments spell them. +pub fn named_by_argument(name: &str, importer: &str) -> Result { + let Raw::Import(importer) = parse_argument(importer) else { + bail!("the importer named {name:?} must be env:, file: or cmd:, not {importer:?}"); + }; + define(name, &importer)?; + Ok(importer) +} + fn literal_or_interpolated(raw: &str) -> Raw<'_> { match interpolated(raw, None) { Some(importer) => Raw::Import(importer), @@ -148,22 +270,37 @@ pub fn interpolated(text: &str, dir: Option<&Path>) -> Option { }) } -/// Reads an importer table from a file in `dir`; None if `object` isn't one. +/// Reads an importer table from a file in `dir`, where no importers are named; None +/// if `object` isn't one. pub fn parse_table(object: &JsonMap, dir: &Path) -> Result> { + parse_table_in(object, dir, &UNNAMED) +} + +/// Reads an importer table from a file in `dir`: `{ NAME = "REST" }` is the importer +/// `NAME` of `importers`. None if `object` isn't one. +pub fn parse_table_in( + object: &JsonMap, + dir: &Path, + importers: &Importers, +) -> Result> { + let named: Vec<&String> = object + .keys() + .filter(|key| importers.contains_key(*key)) + .collect(); let sources = ["env", "file", "command"] .into_iter() .filter(|key| object.contains_key(*key)) - .count(); + .count() + + named.len(); if sources == 0 { return Ok(None); } if sources > 1 { - bail!("an importer takes exactly one of env, file and command"); + bail!("an importer takes exactly one of env, file, command and those named"); } - if let Some(unknown) = object - .keys() - .find(|key| !["env", "file", "command", "format"].contains(&key.as_str())) - { + if let Some(unknown) = object.keys().find(|key| { + !["env", "file", "command", "format"].contains(&key.as_str()) && !named.contains(key) + }) { bail!("unknown importer key {unknown:?}"); } let format = match object.get("format") { @@ -185,6 +322,11 @@ pub fn parse_table(object: &JsonMap, dir: &Path) -> Result Source::Shell(command.clone()), @@ -219,6 +361,7 @@ impl Importer { Source::File(path) => format!("file{format}:{}", self.in_dir(path).display()), Source::Shell(command) => format!("cmd{format}:{command}"), Source::Argv(argv) => format!("cmd{format}:{}", argv.join(" ")), + Source::Named { importer, name } => format!("{importer}{format}:{name}"), Source::Template(template) => template.clone(), } } @@ -246,12 +389,30 @@ impl Importer { /// The imported content: text, JSON, or bytes; its `var:` placeholders, and those /// of the placeholders in it, replaced by what `variables` gives. pub fn fetch_with(&self, variables: &Variables) -> Result { + self.fetch_given(Given { + variables, + importers: &UNNAMED, + depth: 0, + }) + } + + /// The imported content, as `fetch_with`; and where it, or a placeholder in it, + /// is one of `importers` by name, what that one gives. + pub fn fetch_in(&self, variables: &Variables, importers: &Importers) -> Result { + self.fetch_given(Given { + variables, + importers, + depth: 0, + }) + } + + fn fetch_given(&self, given: Given<'_>) -> Result { let dir = self.dir.as_deref(); // Its placeholders may give bytes where it does. let raw = self.format == Format::Raw; let bytes = match &self.source { Source::Env(name) => { - let name = filled(name, dir, raw, variables)?; + let name = filled(name, dir, raw, given)?; std::env::var_os(&name) .ok_or_else(|| { anyhow!("environment variable {} is not set", name.to_string_lossy()) @@ -260,13 +421,13 @@ impl Importer { } Source::File(path) => { let path = match path.to_str() { - Some(text) => self.in_dir(Path::new(&filled(text, dir, raw, variables)?)), + Some(text) => self.in_dir(Path::new(&filled(text, dir, raw, given)?)), None => self.in_dir(path), }; std::fs::read(&path).with_context(|| format!("reading {}", path.display()))? } Source::Shell(command) => { - let (script, values) = shell(command, dir, raw, variables)?; + let (script, values) = shell(command, dir, raw, given)?; let mut process = Command::new("sh"); process.arg("-c").arg(script); if !values.is_empty() { @@ -278,13 +439,42 @@ impl Importer { Source::Argv(argv) => { let argv = argv .iter() - .map(|argument| filled(argument, dir, raw, variables)) + .map(|argument| filled(argument, dir, raw, given)) .collect::>>()?; let mut process = Command::new(&argv[0]); process.args(&argv[1..]); run(process, dir, &self.describe())? } - Source::Template(template) => expand_with(template, dir, variables)?.into_bytes(), + Source::Template(template) => expand_with(template, dir, given)?.into_bytes(), + Source::Named { importer, name } => { + let named = given + .importers + .get(importer) + .ok_or_else(|| anyhow!("no importer is named {importer:?} here"))?; + if given.depth >= DEEPEST { + bail!("the importer named {importer:?} is defined through itself"); + } + // What follows the name is its variable `name`, beside the program's + // own. + let mut variables = given.variables.clone(); + variables.insert( + NAME.to_owned(), + filled(name, dir, raw, given)?.into_encoded_bytes(), + ); + let mut named = named.clone(); + named.format = Format::Raw; + let fetched = named + .fetch_given(Given { + variables: &variables, + importers: given.importers, + depth: given.depth + 1, + }) + .with_context(|| format!("the importer named {importer:?}"))?; + match fetched { + Imported::Raw(bytes) => bytes, + _ => unreachable!("a raw importer gives bytes"), + } + } }; if self.format == Format::Raw { return Ok(Imported::Raw(bytes)); @@ -378,14 +568,14 @@ fn value( within: &str, dir: Option<&Path>, raw: bool, - variables: &Variables, + given: Given<'_>, ) -> Result> { if let Some((bytes, name)) = variable(placeholder) { // Its name may hold placeholders, as an environment variable's. - let name = filled(name, dir, false, variables)?; + let name = filled(name, dir, false, given)?; let name = name.to_string_lossy(); - let Some(value) = variables.get(name.as_ref()) else { - let given: Vec<&str> = variables.keys().map(String::as_str).collect(); + let Some(value) = given.variables.get(name.as_ref()) else { + let given: Vec<&str> = given.variables.keys().map(String::as_str).collect(); bail!( "unknown variable {name:?} in {within:?}: {}", if given.is_empty() { @@ -409,7 +599,7 @@ fn value( ), }; } - let mut importer = match parse_argument(placeholder) { + let mut importer = match parse_argument_in(placeholder, given.importers) { Raw::Import(importer) if !importer.is_interpolation() => importer, _ => bail!("placeholder {placeholder:?} in {within:?} isn't env:, file:, cmd: or var:"), }; @@ -425,13 +615,20 @@ fn value( ), } importer.dir = dir.map(Path::to_owned); - match importer.fetch_with(variables)? { + match importer.fetch_given(given)? { Imported::Text(text) => Ok(text.into_bytes()), Imported::Raw(bytes) => Ok(bytes), Imported::Json(_) => unreachable!("no +json importer"), } } +/// Whether `text` begins with the name of one of `importers`, and `:` or `+raw:`. +fn names(text: &str, importers: &Importers) -> bool { + text.split_once(':').is_some_and(|(prefix, _)| { + importers.contains_key(prefix.strip_suffix("+raw").unwrap_or(prefix)) + }) +} + /// The name in a placeholder that is a variable's, `var:NAME` or `var+raw:NAME`, and /// whether it is `+raw`. fn variable(placeholder: &str) -> Option<(bool, &str)> { @@ -447,11 +644,19 @@ fn variable(placeholder: &str) -> Option<(bool, &str)> { /// Text with its placeholders replaced by their content, without variables. #[cfg(test)] fn expand(template: &str, dir: Option<&Path>) -> Result { - expand_with(template, dir, &NONE) + expand_with( + template, + dir, + Given { + variables: &NONE, + importers: &UNNAMED, + depth: 0, + }, + ) } /// Text with its placeholders replaced by their content. -fn expand_with(template: &str, dir: Option<&Path>, variables: &Variables) -> Result { +fn expand_with(template: &str, dir: Option<&Path>, given: Given<'_>) -> Result { let mut out = String::new(); let mut rest = template; while let Some(at) = rest.find('$') { @@ -463,7 +668,7 @@ fn expand_with(template: &str, dir: Option<&Path>, variables: &Variables) -> Res } else if let Some((after, close)) = opened(after) { let end = placeholder_end(after, opener(close), close) .ok_or_else(|| anyhow!("unterminated placeholder in template {template:?}"))?; - let text = value(&after[..end], template, dir, false, variables)?; + let text = value(&after[..end], template, dir, false, given)?; out.push_str(&String::from_utf8(text).expect("a text importer gives text")); rest = &after[end + 1..]; } else { @@ -502,7 +707,13 @@ const NESTED: [&str; 8] = [ /// The parts of what an importer names (a name, a path, a command, an argument): only /// `${env:`, `${file:`, `${cmd:` and `${var:` begin a placeholder, `$${` is a `${`, and /// every other `$` stays as it is. +#[cfg(test)] fn parts(text: &str) -> Result>> { + parts_in(text, &UNNAMED) +} + +/// `parts`, where `NAME:` of `importers` begins a placeholder too. +fn parts_in<'a>(text: &'a str, importers: &Importers) -> Result>> { let mut parts = Vec::new(); let mut plain = String::new(); let mut rest = text; @@ -512,9 +723,9 @@ fn parts(text: &str) -> Result>> { if from.starts_with("$${") || from.starts_with("$$(") { plain.push('$'); rest = &from[2..]; - } else if let Some((after, close)) = opened(&from[1..]) - .filter(|(after, _)| NESTED.iter().any(|prefix| after.starts_with(prefix))) - { + } else if let Some((after, close)) = opened(&from[1..]).filter(|(after, _)| { + NESTED.iter().any(|prefix| after.starts_with(prefix)) || names(after, importers) + }) { let end = placeholder_end(after, opener(close), close) .ok_or_else(|| anyhow!("unterminated placeholder in {text:?}"))?; if !plain.is_empty() { @@ -536,13 +747,13 @@ fn parts(text: &str) -> Result>> { /// What an importer names, its placeholders replaced by their content, as it is: a /// name, a path, or one argument, which stays one whatever a placeholder gives. -fn filled(text: &str, dir: Option<&Path>, raw: bool, variables: &Variables) -> Result { +fn filled(text: &str, dir: Option<&Path>, raw: bool, given: Given<'_>) -> Result { let mut out = Vec::new(); - for part in parts(text)? { + for part in parts_in(text, given.importers)? { match part { Part::Text(plain) => out.extend(plain.into_bytes()), Part::Placeholder(placeholder) => { - out.extend(value(placeholder, text, dir, raw, variables)?) + out.extend(value(placeholder, text, dir, raw, given)?) } } } @@ -558,12 +769,12 @@ fn shell( command: &str, dir: Option<&Path>, raw: bool, - variables: &Variables, + given: Given<'_>, ) -> Result<(String, Vec)> { let mut script = String::new(); let mut values = Vec::new(); let mut at = Shell::default(); - for part in parts(command)? { + for part in parts_in(command, given.importers)? { match part { Part::Text(plain) => { plain.chars().for_each(|char| at.read(char)); @@ -578,7 +789,7 @@ fn shell( command, dir, raw, - variables, + given, )?)); script.push_str(&reference); } @@ -965,7 +1176,17 @@ mod tests { .map(|(name, value)| (name.to_owned(), value.to_vec())) .collect(); let dir = Some(scratch.0.as_path()); - let text = |template: &str| expand_with(template, dir, &variables); + let text = |template: &str| { + expand_with( + template, + dir, + Given { + variables: &variables, + importers: &UNNAMED, + depth: 0, + }, + ) + }; let fetch = |raw: &str| { let Raw::Import(mut importer) = parse_argument(raw) else { panic!("no importer: {raw}"); @@ -1031,6 +1252,140 @@ mod tests { assert!(fetch("cmd:var=mine; printf '%s' \"${var:-x}\"").is_err()); } + /// An importer a configuration names is used as the kinds built in are: as a + /// value's importer, in a table, and as a placeholder; what follows its name is its + /// variable `name`, data to it, whatever it holds. + #[test] + fn importers_a_configuration_names() { + let scratch = Scratch::new("config-import-named"); + std::fs::write(scratch.0.join("tor"), "a key\n").unwrap(); + let named = named_in_table( + json!({ + "show": { "command": ["printf", "<%s>", "$(var:name)"] }, + "kept": "file:$(var:name)", + "shell": "cmd:printf '[%s]' $(var:name)", + }) + .as_object() + .unwrap(), + &scratch.0, + ) + .unwrap(); + let variables = Variables::new(); + let fetch = |raw: &str| { + let Raw::Import(mut importer) = parse_argument_in(raw, &named) else { + panic!("no importer: {raw}"); + }; + importer.dir = Some(scratch.0.clone()); + importer.fetch_in(&variables, &named) + }; + let text = |text: &str| Imported::Text(text.to_owned()); + + // As a value's importer, by argument and by table; shown as written. + assert_eq!( + fetch("show:continuum/tor").unwrap(), + text("") + ); + assert_eq!(fetch("kept:tor").unwrap(), text("a key")); + assert_eq!( + fetch("kept+raw:tor").unwrap(), + Imported::Raw(b"a key\n".to_vec()) + ); + let table = parse_table_in( + json!({ "show": "x", "format": "raw" }).as_object().unwrap(), + &scratch.0, + &named, + ) + .unwrap() + .unwrap(); + assert_eq!(table.describe(), "show+raw:x"); + assert_eq!( + table.fetch_in(&variables, &named).unwrap(), + Imported::Raw(b"".to_vec()) + ); + // What follows the name is data: one argument, one word of a shell command. + assert_eq!( + fetch("show:a b; $(echo no)").unwrap(), + text("") + ); + assert_eq!(fetch("shell:a b; echo no").unwrap(), text("[a b; echo no]")); + // As a placeholder, in text and inside another importer; its name may hold some. + let template = interpolated("node-$(show:x)-${kept:tor}", Some(&scratch.0)).unwrap(); + assert_eq!( + template.fetch_in(&variables, &named).unwrap(), + text("node--a key") + ); + assert_eq!( + fetch("cmd:printf '%s' $(show:$(kept:tor))").unwrap(), + text("") + ); + // Where it isn't named, it is none: text on the command line, an unknown key in + // a table, an unknown placeholder in text. + assert_eq!(parse_argument("show:x"), Raw::Literal("show:x")); + assert!( + parse_table(json!({ "show": "x" }).as_object().unwrap(), &scratch.0) + .unwrap() + .is_none() + ); + assert!(expand("$(show:x)", None).is_err()); + + // What may be named, and how. + let define = + |value: JsonValue| named_in_table(value.as_object().unwrap(), &scratch.0).map(|_| ()); + for refused in [ + json!({ "env": "cmd:true" }), + json!({ "var": "cmd:true" }), + json!({ "Show": "cmd:true" }), + json!({ "a+b": "cmd:true" }), + json!({ "show": "plain" }), + json!({ "show": "node-$(env:X)" }), + json!({ "show": "cmd+raw:true" }), + json!({ "show": { "command": "true", "format": "json" } }), + json!({ "show": 1 }), + ] { + assert!(define(refused.clone()).is_err(), "{refused}"); + } + // One named by another. + let nested = named_in_table( + json!({ "outer": "cmd:printf '%s' $(show:x)" }) + .as_object() + .unwrap(), + &scratch.0, + ) + .unwrap(); + let mut both = named.clone(); + both.extend(nested); + let Raw::Import(outer) = parse_argument_in("outer:y", &both) else { + panic!("no importer"); + }; + assert_eq!(outer.fetch_in(&variables, &both).unwrap(), text("")); + // One defined through itself ends, and says so. + let looping = named_in_table( + json!({ "again": "cmd:printf '%s' $(again:x)" }) + .as_object() + .unwrap(), + &scratch.0, + ) + .unwrap(); + let Raw::Import(again) = parse_argument_in("again:y", &looping) else { + panic!("no importer"); + }; + let why = format!("{:#}", again.fetch_in(&variables, &looping).unwrap_err()); + assert!(why.contains("defined through itself"), "{why}"); + + // By argument. + let importer = named_by_argument("pass", "cmd:printf '%s' $(var:name)").unwrap(); + let by_argument = Importers::from([("pass".to_owned(), importer)]); + let Raw::Import(pass) = parse_argument_in("pass:a/b", &by_argument) else { + panic!("no importer"); + }; + assert_eq!( + pass.fetch_in(&variables, &by_argument).unwrap(), + text("a/b") + ); + assert!(named_by_argument("pass", "plain").is_err()); + assert!(named_by_argument("cmd", "cmd:true").is_err()); + } + #[test] fn commands_with_braces_and_quotes() { let expanded = |template: &str| expand(template, None); diff --git a/crates/config/src/layer.rs b/crates/config/src/layer.rs index 9871d9b..916acf4 100644 --- a/crates/config/src/layer.rs +++ b/crates/config/src/layer.rs @@ -163,7 +163,17 @@ pub fn overlay(layer: &mut Layer, name: String, entry: Entry, how: Overlay, sche } pub fn from_import(kind: Kind, importer: &import::Importer) -> Result { - match importer.fetch()? { + from_import_in(kind, importer, &import::Importers::new()) +} + +/// What `importer` gives, as a value of `kind`; `named` are the importers the +/// configuration names. +pub fn from_import_in( + kind: Kind, + importer: &import::Importer, + named: &import::Importers, +) -> Result { + match importer.fetch_in(&import::Variables::new(), named)? { 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. @@ -218,25 +228,36 @@ impl Sources { } } -/// A value from a file, and where its parts came from. +/// A value from a file, and where its parts came from, where no importers are named. pub fn resolve_file_value( spec: &OptionSpec, value: JsonValue, dir: &Path, +) -> Result<(JsonValue, Sources)> { + resolve_file_value_in(spec, value, dir, &import::Importers::new()) +} + +/// A value from a file, and where its parts came from; `named` are the importers the +/// configuration names. +pub fn resolve_file_value_in( + spec: &OptionSpec, + value: JsonValue, + dir: &Path, + named: &import::Importers, ) -> Result<(JsonValue, Sources)> { let mut sources = Sources::default(); let value = match value { - JsonValue::Object(table) => match import::parse_table(&table, dir)? { + JsonValue::Object(table) => match import::parse_table_in(&table, dir, named)? { Some(importer) => { sources.import(&importer); - from_import(spec.kind, &importer)? + from_import_in(spec.kind, &importer, named)? } 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)? + from_import_in(spec.kind, &importer, named)? } None => JsonValue::String(text), }, @@ -245,10 +266,11 @@ pub fn resolve_file_value( 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)? { + let importer = + import::parse_table_in(&table, dir, named)?.ok_or_else(|| { + anyhow!("a table here must be an importer (env, file or command)") + })?; + match from_import_in(Kind::List, &importer, named)? { JsonValue::Array(more) => values.extend(more), other => values.push(other), } @@ -256,7 +278,7 @@ pub fn resolve_file_value( } JsonValue::String(text) => match import::interpolated(&text, Some(dir)) { Some(importer) => { - values.push(from_import(Kind::Text, &importer)?); + values.push(from_import_in(Kind::Text, &importer, named)?); sources.import(&importer); } None => { diff --git a/docs/configuration.md b/docs/configuration.md index 41a4aff..79e5965 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -269,6 +269,57 @@ continuum --config /etc/continuum.toml --alias env:HOSTNAME --seeds cmd+json:'my Imports are read once, at start. +### Naming importers + +A configuration can name importers of its own, under `[meta.importer]`: what would +otherwise be written out at every use, a secret store's command for one, is written +once. + +```toml +[meta.importer] +pass = { command = ["pass", "show", "$(var:name)"] } +secrets = "cmd:secrets $(env:HOSTNAME) show $(var:name)" +kept = { file = "/run/secrets/$(var:name)" } +``` + +Each is an importer as above, a table or the text an argument takes (`cmd:…`, `file:…`, +`env:…`), with the variable `name` for what follows the name where it is used: + +```toml +tor-key = { pass = "continuum/tor" } +alias = "node-$(secrets:alias)" +``` + +```sh +continuum --tor-key pass:continuum/tor +``` + +So `NAME:REST` on the command line, `{ NAME = "REST" }` in a file and `$(NAME:REST)` in +a placeholder are that importer, and `+raw` and `+json` (`format` in a table) say how +its content is read, as with the kinds built in: the importer named takes no format +itself. What follows the name goes in as every variable does: as it is, one argument, +one word of a shell command, never as something to run. It may hold placeholders, and +an importer may be defined through others named, but not through itself. + +A name is small letters, digits and `-`, a letter first, and none of `env`, `file`, +`cmd`, `command`, `var`, `literal` and `format`. Where it isn't named, `pass:x` is +what it was before: text on the command line, an unknown key in a file. + +On the command line it is named as every option is, the table's keys joined with `-`: +`--meta-importer-NAME IMPORTER`, the importer as an argument takes it: + +```sh +continuum --meta-importer-pass 'cmd:pass show $(var:name)' --tor-key pass:continuum/tor +``` + +A name counts in every file and argument of the configuration, wherever it is given: +one a later file names is known in an earlier one. Of two of one name, the later +source's counts: a file's own over its includes', a later file's over an earlier +one's, an argument's over them all. Naming an importer gives whoever writes the +configuration nothing they lack: they can write the command where it is used as well. + +Under `meta` is what a configuration says about itself; `importer` is all of it. + ## Checking the configuration `--print-config` prints the effective configuration as JSON and exits: every option diff --git a/src/config/mod.rs b/src/config/mod.rs index 6f9bd98..430ace1 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -28,7 +28,9 @@ use serde::{Deserialize, Serialize}; use serde_json::Value as JsonValue; use tracing::{info, warn}; -pub(crate) use ::config::arguments::{merged, with_options}; +#[cfg(test)] +pub(crate) use ::config::arguments::merged; +pub(crate) use ::config::arguments::with_options; pub(crate) use ::config::layer::read; pub(crate) use ::config::layer::{Layer, Origin, Provenance}; pub(crate) use ::config::option::{Kind, OptionSpec, Schema, option}; @@ -1719,18 +1721,29 @@ impl Loaded { } } +/// The command line as the command reads it, and the importers it names +/// (`--meta-importer-NAME`), which are taken off first: their names are the +/// configuration's, not the command's. Exits on `--help`, `--version` and syntax errors. +fn command_line() -> Result<(clap::ArgMatches, ::config::import::Importers)> { + let mut arguments = std::env::args(); + let program = arguments.next().unwrap_or_else(|| "continuum".to_owned()); + let (arguments, named) = ::config::arguments::take_importers(arguments)?; + let matches = command().get_matches_from(std::iter::once(program).chain(arguments)); + Ok((matches, named)) +} + /// 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 { ::config::arguments::refuse_gone(std::env::args().skip(1), &SCHEMA)?; - let matches = command().get_matches(); + let (matches, named) = command_line()?; let print_only = ::config::arguments::prints_config(&matches); if print_only { // Logs go to stdout too: the report goes there alone (it says where each value // came from anyway). let _ = crate::logging::set_filter("off"); } - let (merged, files) = merged(&matches, &SCHEMA, &[])?; + let (merged, files) = ::config::arguments::merged_in(&matches, &SCHEMA, &[], &named)?; let mut loaded = resolve(merged, files)?; loaded.print_only = print_only; Ok(loaded) @@ -1741,7 +1754,8 @@ pub(crate) fn load() -> Result { /// the configuration is read: it needs none of a node's, which a party's founders /// don't have yet as they ask for their nodes' IDs. pub(crate) fn asked_node_id() -> Option<(PathBuf, bool)> { - let matches = command().get_matches(); + // An importer named amiss is said where the configuration is read (`load`). + let (matches, _) = command_line().ok()?; let sub = matches.subcommand_matches(NODE_ID)?; let file = sub.get_one::("file").expect("required"); // Logs go to stdout too: the node ID goes there alone. diff --git a/src/federation/party.rs b/src/federation/party.rs index eaf28b5..17e3f0e 100644 --- a/src/federation/party.rs +++ b/src/federation/party.rs @@ -627,7 +627,13 @@ fn begin_federation(dir: &Path, matches: &ArgMatches) -> Result<()> { /// Runs the client, as its arguments say. pub(crate) async fn main() -> Result<()> { - let matches = command().get_matches(); + // The importers it names, off the command line first: their names are its own. + let mut arguments = std::env::args(); + let program = arguments + .next() + .unwrap_or_else(|| "continuum-party".to_owned()); + let (arguments, named) = ::config::arguments::take_importers(arguments)?; + let matches = command().get_matches_from(std::iter::once(program).chain(arguments)); let (name, sub) = matches.subcommand().expect("a subcommand is required"); // Those that use no options read no federation's. let dir = if matches!(name, "twice" | "root" | "judge" | "found") { @@ -651,7 +657,7 @@ pub(crate) async fn main() -> Result<()> { .map(|dir| dir.join("party.toml")) .filter(|file| file.exists()) .collect(); - let (merged, _) = config::merged(&matches, &config::PARTY, &first)?; + let (merged, _) = ::config::arguments::merged_in(&matches, &config::PARTY, &first, &named)?; let mut options: Options = config::read(&merged)?; // In a federation's directory, its record and key, where none other is named. if let Some(dir) = &dir { -- cgit v1.3.1