//! The command line: a program's options as arguments, the configuration files it //! names (`--config`) and what it unsets of theirs (`--unset`), put together. use std::path::PathBuf; use anyhow::{Context, Result, 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::option::{Kind, OptionSpec, Schema, from_text}; pub const CONFIG: &str = "config"; /// Stops on an argument naming an option that is gone, saying why, before the command /// line is read: clap would call it unexpected. pub fn refuse_gone(arguments: impl IntoIterator, schema: &Schema) -> 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) = schema.gone(name) { bail!("--{name} is gone: {why}"); } } Ok(()) } /// `command` taking `options` as arguments, and configuration files for them /// (`--config`) and unsets of what those set (`--unset`). pub 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 of `options` given as arguments (unsets first, so a value given too wins). pub fn arguments(matches: &ArgMatches, schema: &Schema) -> Result { let mut layer = Layer::new(); for name in matches.get_many::(UNSET).into_iter().flatten() { if schema.spec(name).is_none() { bail!("--unset {name}: no such option"); } layer.insert(name.clone(), unset_entry(Provenance::Argument)); } for spec in schema.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::(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 values of the options of `schema`: from the configuration files `first` and then /// those `matches` names (`--config`), in order, later ones winning, then from its /// arguments; and those files. pub fn merged( matches: &ArgMatches, schema: &Schema, first: &[PathBuf], ) -> Result<(Layer, Vec)> { let files: Vec = first .iter() .cloned() .chain( matches .get_many::(CONFIG) .into_iter() .flatten() .map(PathBuf::from), ) .collect(); let mut merged = Layer::new(); for path in &files { for (name, entry) in file::load(path, schema)? { overlay(&mut merged, name, entry, Overlay::FileOverFile, schema); } } for (name, entry) in arguments(matches, schema)? { overlay(&mut merged, name, entry, Overlay::ArgumentOverFile, schema); } Ok((merged, files)) } #[cfg(test)] mod tests { use super::*; use crate::option::{OptionSpec, option}; use crate::testing::Scratch; use serde_json::json; const OPTIONS: &[OptionSpec] = &[ option("name", Kind::Text, "NAME", None, "A name"), option("peers", Kind::List, "PEER,[...]", None, "Peers"), option("local", Kind::Text, "PATH", None, "A local one"), option("remote", Kind::Text, "URL", None, "A remote one"), option("token", Kind::Text, "TOKEN", None, "A token").secret(), ]; const SCHEMA: Schema = Schema { options: OPTIONS, conflicts: &[(&["remote"], &["local"])], gone: &[("legacy", "use name instead")], }; fn merged_of(arguments: &[&str]) -> Result { 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) } /// A program's own options, by its schema: files in order, a file over its /// includes, arguments over files; unsets; a conflict dropping the earlier side; an /// option that is gone said as such, in a file and as an argument. #[test] fn files_and_arguments_of_a_schema_of_ones_own() { let scratch = Scratch::new("arguments"); let path = |name: &str| scratch.0.join(name).display().to_string(); scratch.file( "base.toml", "name = \"base\"\npeers = [\"a\", \"b\"]\nlocal = \"here\"\n", ); scratch.file( "main.json", r#"{"include": ["base.toml"], "name": "main", "token": {"file": "secret"}}"#, ); scratch.file("secret", "hush\n"); let layer = merged_of(&["--config", &path("main.json")]).unwrap(); assert_eq!(layer["name"].value, json!("main")); assert_eq!(layer["peers"].value, json!(["a", "b"])); assert_eq!(layer["token"].value, json!("hush")); assert_eq!(layer["token"].shown(SCHEMA.secret("token")), ""); assert!(layer["name"].origin.to_string().ends_with("main.json")); // Arguments over files, and an unset back to the default. let layer = merged_of(&[ "--config", &path("main.json"), "--name", "given", "--unset", "peers", ]) .unwrap(); assert_eq!(layer["name"].value, json!("given")); assert_eq!(layer["name"].origin.provenance, Provenance::Argument); assert!(layer["peers"].value.is_null() && layer["peers"].origin.unset); // What can't be combined: the later source's side stays. let layer = merged_of(&["--config", &path("main.json"), "--remote", "there"]).unwrap(); assert!(!layer.contains_key("local")); assert_eq!(layer["remote"].value, json!("there")); // Unknown, and gone. scratch.file("unknown.toml", "nmae = \"x\"\n"); let said = format!( "{:#}", merged_of(&["--config", &path("unknown.toml")]).unwrap_err() ); assert!(said.contains("unknown option"), "{said}"); scratch.file("gone.toml", "legacy = \"x\"\n"); let said = format!( "{:#}", merged_of(&["--config", &path("gone.toml")]).unwrap_err() ); assert!(said.contains("use name instead"), "{said}"); let said = refuse_gone(["--legacy=x".to_owned()], &SCHEMA).unwrap_err(); assert!(said.to_string().contains("use name instead")); assert!(refuse_gone(["--name".to_owned()], &SCHEMA).is_ok()); } }