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. --- crates/config/src/arguments.rs | 196 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 186 insertions(+), 10 deletions(-) (limited to 'crates/config/src/arguments.rs') 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)); + } } -- cgit v1.3.1