//! Reading a program's arguments, described once for both parsing and `--help`. use std::collections::HashMap; use std::ffi::OsString; use std::fmt; use std::str::FromStr; use crate::help::Help; use crate::message::Report; /// A flag or an option, from a spec like `-q, --quiet` or `-r, --region `. #[derive(Clone, Debug)] struct Flag { spec: String, about: String, short: Option, long: Option, /// What its value is called, for options; flags have none. value: Option, } impl Flag { fn parse(spec: &str, about: &str) -> Flag { let mut flag = Flag { spec: spec.into(), about: about.into(), short: None, long: None, value: None, }; for word in spec.split([' ', ',']).filter(|w| !w.is_empty()) { if let Some(long) = word.strip_prefix("--") { // `--name=VALUE` names its value the way `--name ` does match long.split_once('=') { Some((name, value)) => { flag.long = Some(name.into()); flag.value = Some(value.trim_matches(['<', '>', '[', ']']).into()); } None => flag.long = Some(long.into()), } } else if let Some(short) = word.strip_prefix('-') { flag.short = short.chars().next(); } else { // ``, `[FILE]` or a bare `FILE`, as some help writes it flag.value = Some(word.trim_matches(['<', '>', '[', ']', '.']).into()); } } flag } /// Whether `name` (`quiet`, `--quiet`, `q` or `-q`) is this flag. fn is(&self, name: &str) -> bool { let name = name.trim_start_matches('-'); self.long.as_deref() == Some(name) || (name.chars().count() == 1 && self.short == name.chars().next()) } /// How it's written in messages: the long name if it has one. fn shown(&self) -> String { match &self.long { Some(long) => format!("--{long}"), None => format!("-{}", self.short.unwrap_or('?')), } } } /// A positional argument, from a spec like ``, `[TAG]` or `...`. #[derive(Clone, Debug)] struct Arg { spec: String, about: String, name: String, required: bool, many: bool, } impl Arg { fn parse(spec: &str, about: &str) -> Arg { Arg { spec: spec.into(), about: about.into(), name: spec.trim_matches(['<', '>', '[', ']', '.']).to_lowercase(), required: spec.starts_with('<'), many: spec.ends_with("..."), } } } /// A program's command line: its flags, options, arguments and subcommands, described once. /// [`parse`](Cli::parse) reads the arguments the program was started with, and the same /// description draws `--help` as a [`Help`]. /// /// Flags are written as they'd appear in help: `-q, --quiet` is a flag, and anything with a /// value after it, `-r, --region `, is an option that takes one. Arguments are `` /// when they're needed, `[TAG]` when they're not, and `...` for any number of them /// (only the last can be). `-h, --help` comes free, and so does `-V, --version` once there's /// a [`version`](Cli::version). /// /// ``` /// use tinsel::Cli; /// /// let cli = Cli::new("deploy", "ship an app to the cloud") /// .flag("-r, --region ", "where to deploy") /// .flag("-q, --quiet", "only print problems") /// .arg("", "what to ship"); /// /// let args = cli.try_parse_from(["my-app", "--region", "us-east-1"])?; /// assert_eq!(args.arg("app"), Some("my-app")); /// assert_eq!(args.value("region"), Some("us-east-1")); /// assert!(!args.flag("quiet")); /// # Ok::<(), tinsel::CliError>(()) /// ``` /// /// A mistake is drawn as a [`Report`], with the flag or command that was probably meant: /// /// ```text /// ✕ there's no --regon flag /// → did you mean --region? /// ``` /// /// This covers what most programs need and stops there: there are no rules between flags, /// no defaults from the environment, and subcommands go one level deep. A flag the /// subcommand doesn't have but the program does is the program's, so `deploy status -q` works. #[derive(Clone, Debug, Default)] pub struct Cli { name: String, about: String, version: Option, flags: Vec, args: Vec, commands: Vec, examples: Vec<(String, String)>, footer: Option, } impl Cli { /// A program called `name`, which does `about`. Also how a subcommand starts, for /// [`command`](Cli::command). pub fn new(name: impl Into, about: impl Into) -> Self { Cli { name: name.into(), about: about.into(), ..Self::default() } } /// The version, shown in help and printed by `-V` or `--version`. #[must_use] pub fn version(mut self, version: impl Into) -> Self { self.version = Some(version.into()); self } /// A flag, `-q, --quiet`, or an option that takes a value, `--region `. Either /// name can be left out. #[must_use] pub fn flag(mut self, spec: impl AsRef, about: impl AsRef) -> Self { self.flags.push(Flag::parse(spec.as_ref(), about.as_ref())); self } /// A positional argument: `` is needed, `[TAG]` isn't, and `...` takes the /// rest. They're filled in the order they're added. #[must_use] pub fn arg(mut self, spec: impl AsRef, about: impl AsRef) -> Self { self.args.push(Arg::parse(spec.as_ref(), about.as_ref())); self } /// A subcommand, described the same way. /// /// ``` /// use tinsel::Cli; /// /// let cli = Cli::new("deploy", "ship an app") /// .flag("-q, --quiet", "only print problems") /// .command(Cli::new("logs", "recent logs").flag("--since