clap/src/derive.rs

238 lines
7.3 KiB
Rust
Raw Normal View History

2020-04-29 02:30:04 +00:00
//! This module contains traits that are usable with the `#[derive(...)].`
//! macros in [`clap_derive`].
use crate::{App, ArgMatches, Error};
2020-04-27 18:47:08 +00:00
use std::ffi::OsString;
2020-04-29 02:30:04 +00:00
/// The primary one-stop-shop trait used to create an instance of a `clap`
/// [`App`], conduct the parsing, and turn the resulting [`ArgMatches`] back
/// into concrete instance of the user struct.
///
/// This trait is primarily a convenience on top of [`FromArgMatches`] +
2020-04-29 02:30:04 +00:00
/// [`IntoApp`] which uses those two underlying traits to build the two
/// fundamental functions `parse` which uses the `std::env::args_os` iterator,
/// and `parse_from` which allows the consumer to supply the iterator (along
/// with fallible options for each).
///
/// # Examples
///
/// The following example creates a `Context` struct that would be used
/// throughout the application representing the normalized values coming from
/// the CLI.
///
/// ```rust
/// # use clap::{Clap};
/// /// My super CLI
/// #[derive(Clap)]
/// #[clap(name = "demo")]
/// struct Context {
/// /// More verbose output
/// #[clap(long)]
/// verbose: bool,
/// /// An optional name
/// #[clap(short, long)]
/// name: Option<String>,
/// }
/// ```
///
/// The equivalent [`App`] struct + `From` implementation:
2020-04-29 02:30:04 +00:00
///
/// ```rust
/// # use clap::{App, Arg, ArgMatches};
/// App::new("demo")
/// .about("My super CLI")
2020-08-11 14:08:05 +00:00
/// .arg(Arg::new("verbose")
2020-04-29 02:30:04 +00:00
/// .long("verbose")
2020-08-11 14:08:05 +00:00
/// .about("More verbose output"))
/// .arg(Arg::new("name")
2020-04-29 02:30:04 +00:00
/// .long("name")
/// .long("n")
2020-08-11 14:08:05 +00:00
/// .about("An optional name")
2020-04-29 02:30:04 +00:00
/// .takes_value(true));
///
/// struct Context {
/// verbose: bool,
/// name: Option<String>,
/// }
///
/// impl From<ArgMatches> for Context {
/// fn from(m: ArgMatches) -> Self {
/// Context {
/// verbose: m.is_present("verbose"),
/// name: m.value_of("name").map(|n| n.to_owned()),
/// }
/// }
/// }
/// ```
2020-09-12 17:15:14 +00:00
///
/// [`App`]: ./struct.App.html
/// [`ArgMatches`]: ./struct.ArgMatches.html
/// [`FromArgMatches`]: ./trait.FromArgMatches.html
/// [`IntoApp`]: ./trait.IntoApp.html
pub trait Clap: FromArgMatches + IntoApp + Sized {
2020-04-29 02:30:04 +00:00
/// Parse from `std::env::args_os()`, exit on error
fn parse() -> Self {
let matches = <Self as IntoApp>::into_app().get_matches();
<Self as FromArgMatches>::from_arg_matches(&matches)
}
2020-04-29 02:30:04 +00:00
/// Parse from `std::env::args_os()`, return Err on error.
fn try_parse() -> Result<Self, Error> {
let matches = <Self as IntoApp>::into_app().try_get_matches()?;
Ok(<Self as FromArgMatches>::from_arg_matches(&matches))
}
/// Parse from iterator, exit on error
fn parse_from<I, T>(itr: I) -> Self
where
I: IntoIterator<Item = T>,
// TODO (@CreepySkeleton): discover a way to avoid cloning here
T: Into<OsString> + Clone,
{
let matches = <Self as IntoApp>::into_app().get_matches_from(itr);
<Self as FromArgMatches>::from_arg_matches(&matches)
}
2020-02-25 16:50:47 +00:00
/// Parse from iterator, return Err on error.
fn try_parse_from<I, T>(itr: I) -> Result<Self, Error>
where
I: IntoIterator<Item = T>,
// TODO (@CreepySkeleton): discover a way to avoid cloning here
T: Into<OsString> + Clone,
{
let matches = <Self as IntoApp>::into_app().try_get_matches_from(itr)?;
Ok(<Self as FromArgMatches>::from_arg_matches(&matches))
}
}
/// Build an App according to the struct
///
/// Also serves for flattening
pub trait IntoApp: Sized {
/// @TODO @release @docs
2020-07-19 17:11:29 +00:00
fn into_app<'help>() -> App<'help>;
/// @TODO @release @docs
fn augment_clap(app: App<'_>) -> App<'_>;
}
2020-04-29 02:42:54 +00:00
/// Converts an instance of [`ArgMatches`] to a consumer defined struct.
2020-09-12 17:15:14 +00:00
///
/// [`ArgMatches`]: ./struct.ArgMatches.html
pub trait FromArgMatches: Sized {
2020-04-29 02:42:54 +00:00
/// It's common to have an "application context" struct (sometimes called
/// config) that represents all the normalized values after being processed by
/// the CLI.
///
/// For instance, if an application we made had two CLI options, `--name
/// <STRING>` and a flag `--debug` to distinguish "debugging mode" for our made
/// up CLI, we may create a context struct as follows:
///
/// ```no_run
/// struct Context {
/// name: String,
/// debug: bool
/// }
/// ```
///
/// And after letting `clap` parse the CLI, we get back and instance of
/// `ArgMatches`, we may create a `From` implementation like so:
///
/// ```no_run
2020-08-11 14:08:05 +00:00
/// # use clap::ArgMatches;
/// # struct Context {
/// # name: String,
/// # debug: bool
/// # }
2020-04-29 02:42:54 +00:00
/// impl From<ArgMatches> for Context {
/// fn from(m: ArgMatches) -> Self {
/// Context {
2020-08-11 14:08:05 +00:00
/// name: m.value_of("name").unwrap().to_string(),
2020-04-29 02:42:54 +00:00
/// debug: m.is_present("debug"),
/// }
/// }
/// }
/// ```
fn from_arg_matches(matches: &ArgMatches) -> Self;
/// @TODO@ @release @docs
fn update_from_arg_matches(&mut self, matches: &ArgMatches);
}
/// @TODO @release @docs
pub trait Subcommand: Sized {
/// @TODO @release @docs
2020-08-05 12:14:22 +00:00
fn from_subcommand(subcommand: Option<(&str, &ArgMatches)>) -> Option<Self>;
/// @TODO @release @docs
fn update_from_subcommand(&mut self, name: &str, matches: Option<&ArgMatches>);
/// @TODO @release @docs
fn augment_subcommands(app: App<'_>) -> App<'_>;
}
/// @TODO @release @docs
2020-04-22 07:25:41 +00:00
pub trait ArgEnum: Sized {
/// @TODO @release @docs
const VARIANTS: &'static [&'static str];
/// @TODO @release @docs
fn from_str(input: &str, case_insensitive: bool) -> Result<Self, String>;
}
2020-02-13 15:21:01 +00:00
impl<T: Clap> Clap for Box<T> {
fn parse() -> Self {
Box::new(<T as Clap>::parse())
}
fn try_parse() -> Result<Self, Error> {
<T as Clap>::try_parse().map(Box::new)
}
fn parse_from<I, It>(itr: I) -> Self
where
I: IntoIterator<Item = It>,
// TODO (@CreepySkeleton): discover a way to avoid cloning here
It: Into<OsString> + Clone,
{
Box::new(<T as Clap>::parse_from(itr))
}
fn try_parse_from<I, It>(itr: I) -> Result<Self, Error>
where
I: IntoIterator<Item = It>,
// TODO (@CreepySkeleton): discover a way to avoid cloning here
It: Into<OsString> + Clone,
{
<T as Clap>::try_parse_from(itr).map(Box::new)
}
}
impl<T: IntoApp> IntoApp for Box<T> {
2020-07-19 17:11:29 +00:00
fn into_app<'help>() -> App<'help> {
2020-02-13 15:21:01 +00:00
<T as IntoApp>::into_app()
}
fn augment_clap(app: App<'_>) -> App<'_> {
<T as IntoApp>::augment_clap(app)
}
}
impl<T: FromArgMatches> FromArgMatches for Box<T> {
fn from_arg_matches(matches: &ArgMatches) -> Self {
Box::new(<T as FromArgMatches>::from_arg_matches(matches))
}
fn update_from_arg_matches(&mut self, matches: &ArgMatches) {
<T as FromArgMatches>::update_from_arg_matches(self, matches);
}
2020-02-13 15:21:01 +00:00
}
impl<T: Subcommand> Subcommand for Box<T> {
2020-08-05 12:14:22 +00:00
fn from_subcommand(subcommand: Option<(&str, &ArgMatches)>) -> Option<Self> {
<T as Subcommand>::from_subcommand(subcommand).map(Box::new)
2020-02-13 15:21:01 +00:00
}
fn update_from_subcommand(&mut self, name: &str, matches: Option<&ArgMatches>) {
<T as Subcommand>::update_from_subcommand(self, name, matches);
}
2020-02-13 15:21:01 +00:00
fn augment_subcommands(app: App<'_>) -> App<'_> {
<T as Subcommand>::augment_subcommands(app)
}
}