aboutsummaryrefslogtreecommitdiffstats
path: root/crates/config/src/arguments.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/config/src/arguments.rs')
-rw-r--r--crates/config/src/arguments.rs196
1 files changed, 186 insertions, 10 deletions
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`).
@@ -66,6 +71,14 @@ pub fn with_options(command: Command, options: &'static [OptionSpec]) -> Command
.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)
.value_name("OPTION")
@@ -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<Item = String>,
+) -> Result<(Vec<String>, 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<import::Importers> {
+ 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<Layer> {
+ 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<Layer> {
let mut layer = Layer::new();
for name in matches.get_many::<String>(UNSET).into_iter().flatten() {
if schema.spec(name).is_none() {
@@ -111,13 +183,13 @@ pub fn arguments(matches: &ArgMatches, schema: &Schema) -> Result<Layer> {
} 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) {
+ 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))?;
@@ -156,6 +228,16 @@ pub fn merged(
schema: &Schema,
first: &[PathBuf],
) -> Result<(Layer, Vec<PathBuf>)> {
+ 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<PathBuf>)> {
let files: Vec<PathBuf> = first
.iter()
.cloned()
@@ -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<Layer> {
+ 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!("<main>"));
+ assert_eq!(layer["token"].value, json!("hush"));
+ assert_eq!(layer["peers"].value, json!(["a", "<b>", "<c>"]));
+ // 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));
+ }
}