diff options
author | Valentin Popov <valentin@popov.link> | 2024-07-19 15:37:58 +0300 |
---|---|---|
committer | Valentin Popov <valentin@popov.link> | 2024-07-19 15:37:58 +0300 |
commit | a990de90fe41456a23e58bd087d2f107d321f3a1 (patch) | |
tree | 15afc392522a9e85dc3332235e311b7d39352ea9 /vendor/clap_builder/src/builder | |
parent | 3d48cd3f81164bbfc1a755dc1d4a9a02f98c8ddd (diff) | |
download | fparkan-a990de90fe41456a23e58bd087d2f107d321f3a1.tar.xz fparkan-a990de90fe41456a23e58bd087d2f107d321f3a1.zip |
Deleted vendor folder
Diffstat (limited to 'vendor/clap_builder/src/builder')
20 files changed, 0 insertions, 16682 deletions
diff --git a/vendor/clap_builder/src/builder/action.rs b/vendor/clap_builder/src/builder/action.rs deleted file mode 100644 index 2def801..0000000 --- a/vendor/clap_builder/src/builder/action.rs +++ /dev/null @@ -1,418 +0,0 @@ -#[cfg(debug_assertions)] -use crate::util::AnyValueId; - -/// Behavior of arguments when they are encountered while parsing -/// -/// # Examples -/// -/// ```rust -/// # #[cfg(feature = "help")] { -/// # use clap_builder as clap; -/// # use clap::Command; -/// # use clap::Arg; -/// let cmd = Command::new("mycmd") -/// .arg( -/// Arg::new("special-help") -/// .short('?') -/// .action(clap::ArgAction::Help) -/// ); -/// -/// // Existing help still exists -/// let err = cmd.clone().try_get_matches_from(["mycmd", "-h"]).unwrap_err(); -/// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); -/// -/// // New help available -/// let err = cmd.try_get_matches_from(["mycmd", "-?"]).unwrap_err(); -/// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); -/// # } -/// ``` -#[derive(Clone, Debug)] -#[non_exhaustive] -#[allow(missing_copy_implementations)] // In the future, we may accept `Box<dyn ...>` -pub enum ArgAction { - /// When encountered, store the associated value(s) in [`ArgMatches`][crate::ArgMatches] - /// - /// **NOTE:** If the argument has previously been seen, it will result in a - /// [`ArgumentConflict`][crate::error::ErrorKind::ArgumentConflict] unless - /// [`Command::args_override_self(true)`][crate::Command::args_override_self] is set. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::Set) - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_many::<String>("flag").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(), - /// vec!["value"] - /// ); - /// ``` - Set, - /// When encountered, store the associated value(s) in [`ArgMatches`][crate::ArgMatches] - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::Append) - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value1", "--flag", "value2"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_many::<String>("flag").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(), - /// vec!["value1", "value2"] - /// ); - /// ``` - Append, - /// When encountered, act as if `"true"` was encountered on the command-line - /// - /// If no [`default_value`][super::Arg::default_value] is set, it will be `false`. - /// - /// No value is allowed. To optionally accept a value, see - /// [`Arg::default_missing_value`][super::Arg::default_missing_value] - /// - /// **NOTE:** If the argument has previously been seen, it will result in a - /// [`ArgumentConflict`][crate::error::ErrorKind::ArgumentConflict] unless - /// [`Command::args_override_self(true)`][crate::Command::args_override_self] is set. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::SetTrue) - /// ); - /// - /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_flag("flag"), - /// true - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_flag("flag"), - /// false - /// ); - /// ``` - /// - /// You can use [`TypedValueParser::map`][crate::builder::TypedValueParser::map] to have the - /// flag control an application-specific type: - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// # use clap::Arg; - /// # use clap::builder::TypedValueParser as _; - /// # use clap::builder::BoolishValueParser; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::SetTrue) - /// .value_parser( - /// BoolishValueParser::new() - /// .map(|b| -> usize { - /// if b { 10 } else { 5 } - /// }) - /// ) - /// ); - /// - /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_one::<usize>("flag").copied(), - /// Some(10) - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_one::<usize>("flag").copied(), - /// Some(5) - /// ); - /// ``` - SetTrue, - /// When encountered, act as if `"false"` was encountered on the command-line - /// - /// If no [`default_value`][super::Arg::default_value] is set, it will be `true`. - /// - /// No value is allowed. To optionally accept a value, see - /// [`Arg::default_missing_value`][super::Arg::default_missing_value] - /// - /// **NOTE:** If the argument has previously been seen, it will result in a - /// [`ArgumentConflict`][crate::error::ErrorKind::ArgumentConflict] unless - /// [`Command::args_override_self(true)`][crate::Command::args_override_self] is set. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::SetFalse) - /// ); - /// - /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_flag("flag"), - /// false - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_flag("flag"), - /// true - /// ); - /// ``` - SetFalse, - /// When encountered, increment a `u8` counter - /// - /// If no [`default_value`][super::Arg::default_value] is set, it will be `0`. - /// - /// No value is allowed. To optionally accept a value, see - /// [`Arg::default_missing_value`][super::Arg::default_missing_value] - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::Count) - /// ); - /// - /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_count("flag"), - /// 2 - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_count("flag"), - /// 0 - /// ); - /// ``` - Count, - /// When encountered, display [`Command::print_help`][super::Command::print_help] - /// - /// Depending on the flag, [`Command::print_long_help`][super::Command::print_long_help] may be shown - /// - /// # Examples - /// - /// ```rust - /// # #[cfg(feature = "help")] { - /// # use clap_builder as clap; - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("special-help") - /// .short('?') - /// .action(clap::ArgAction::Help) - /// ); - /// - /// // Existing help still exists - /// let err = cmd.clone().try_get_matches_from(["mycmd", "-h"]).unwrap_err(); - /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); - /// - /// // New help available - /// let err = cmd.try_get_matches_from(["mycmd", "-?"]).unwrap_err(); - /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); - /// # } - /// ``` - Help, - /// When encountered, display [`Command::print_help`][super::Command::print_help] - /// - /// # Examples - /// - /// ```rust - /// # #[cfg(feature = "help")] { - /// # use clap_builder as clap; - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("special-help") - /// .short('?') - /// .action(clap::ArgAction::HelpShort) - /// ); - /// - /// // Existing help still exists - /// let err = cmd.clone().try_get_matches_from(["mycmd", "-h"]).unwrap_err(); - /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); - /// - /// // New help available - /// let err = cmd.try_get_matches_from(["mycmd", "-?"]).unwrap_err(); - /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); - /// # } - /// ``` - HelpShort, - /// When encountered, display [`Command::print_long_help`][super::Command::print_long_help] - /// - /// # Examples - /// - /// ```rust - /// # #[cfg(feature = "help")] { - /// # use clap_builder as clap; - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("special-help") - /// .short('?') - /// .action(clap::ArgAction::HelpLong) - /// ); - /// - /// // Existing help still exists - /// let err = cmd.clone().try_get_matches_from(["mycmd", "-h"]).unwrap_err(); - /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); - /// - /// // New help available - /// let err = cmd.try_get_matches_from(["mycmd", "-?"]).unwrap_err(); - /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); - /// # } - /// ``` - HelpLong, - /// When encountered, display [`Command::version`][super::Command::version] - /// - /// Depending on the flag, [`Command::long_version`][super::Command::long_version] may be shown - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .version("1.0.0") - /// .arg( - /// Arg::new("special-version") - /// .long("special-version") - /// .action(clap::ArgAction::Version) - /// ); - /// - /// // Existing help still exists - /// let err = cmd.clone().try_get_matches_from(["mycmd", "--version"]).unwrap_err(); - /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion); - /// - /// // New help available - /// let err = cmd.try_get_matches_from(["mycmd", "--special-version"]).unwrap_err(); - /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion); - /// ``` - Version, -} - -impl ArgAction { - /// Returns whether this action accepts values on the command-line - /// - /// [`default_values`][super::Arg::default_values] and [`env`][super::Arg::env] may still be - /// processed. - pub fn takes_values(&self) -> bool { - match self { - Self::Set => true, - Self::Append => true, - Self::SetTrue => false, - Self::SetFalse => false, - Self::Count => false, - Self::Help => false, - Self::HelpShort => false, - Self::HelpLong => false, - Self::Version => false, - } - } - - pub(crate) fn default_value(&self) -> Option<&'static std::ffi::OsStr> { - match self { - Self::Set => None, - Self::Append => None, - Self::SetTrue => Some(std::ffi::OsStr::new("false")), - Self::SetFalse => Some(std::ffi::OsStr::new("true")), - Self::Count => Some(std::ffi::OsStr::new("0")), - Self::Help => None, - Self::HelpShort => None, - Self::HelpLong => None, - Self::Version => None, - } - } - - pub(crate) fn default_missing_value(&self) -> Option<&'static std::ffi::OsStr> { - match self { - Self::Set => None, - Self::Append => None, - Self::SetTrue => Some(std::ffi::OsStr::new("true")), - Self::SetFalse => Some(std::ffi::OsStr::new("false")), - Self::Count => None, - Self::Help => None, - Self::HelpShort => None, - Self::HelpLong => None, - Self::Version => None, - } - } - - pub(crate) fn default_value_parser(&self) -> Option<super::ValueParser> { - match self { - Self::Set => None, - Self::Append => None, - Self::SetTrue => Some(super::ValueParser::bool()), - Self::SetFalse => Some(super::ValueParser::bool()), - Self::Count => Some(crate::value_parser!(u8).into()), - Self::Help => None, - Self::HelpShort => None, - Self::HelpLong => None, - Self::Version => None, - } - } - - #[cfg(debug_assertions)] - pub(crate) fn value_type_id(&self) -> Option<AnyValueId> { - match self { - Self::Set => None, - Self::Append => None, - Self::SetTrue => None, - Self::SetFalse => None, - Self::Count => Some(AnyValueId::of::<CountType>()), - Self::Help => None, - Self::HelpShort => None, - Self::HelpLong => None, - Self::Version => None, - } - } -} - -pub(crate) type CountType = u8; diff --git a/vendor/clap_builder/src/builder/app_settings.rs b/vendor/clap_builder/src/builder/app_settings.rs deleted file mode 100644 index f9a87da..0000000 --- a/vendor/clap_builder/src/builder/app_settings.rs +++ /dev/null @@ -1,84 +0,0 @@ -#[allow(unused)] -use crate::Arg; -#[allow(unused)] -use crate::Command; - -#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)] -pub(crate) struct AppFlags(u32); - -impl AppFlags { - pub(crate) fn set(&mut self, setting: AppSettings) { - self.0 |= setting.bit(); - } - - pub(crate) fn unset(&mut self, setting: AppSettings) { - self.0 &= !setting.bit(); - } - - pub(crate) fn is_set(&self, setting: AppSettings) -> bool { - self.0 & setting.bit() != 0 - } - - pub(crate) fn insert(&mut self, other: Self) { - self.0 |= other.0; - } -} - -impl std::ops::BitOr for AppFlags { - type Output = Self; - - fn bitor(mut self, rhs: Self) -> Self::Output { - self.insert(rhs); - self - } -} - -/// Application level settings, which affect how [`Command`] operates -/// -/// **NOTE:** When these settings are used, they apply only to current command, and are *not* -/// propagated down or up through child or parent subcommands -/// -/// [`Command`]: crate::Command -#[derive(Debug, PartialEq, Copy, Clone)] -#[repr(u8)] -pub(crate) enum AppSettings { - IgnoreErrors, - AllowHyphenValues, - AllowNegativeNumbers, - AllArgsOverrideSelf, - AllowMissingPositional, - TrailingVarArg, - DontDelimitTrailingValues, - InferLongArgs, - InferSubcommands, - SubcommandRequired, - AllowExternalSubcommands, - Multicall, - SubcommandsNegateReqs, - ArgsNegateSubcommands, - SubcommandPrecedenceOverArg, - FlattenHelp, - ArgRequiredElseHelp, - NextLineHelp, - DisableColoredHelp, - DisableHelpFlag, - DisableHelpSubcommand, - DisableVersionFlag, - PropagateVersion, - Hidden, - HidePossibleValues, - HelpExpected, - NoBinaryName, - #[allow(dead_code)] - ColorAuto, - ColorAlways, - ColorNever, - Built, - BinNameBuilt, -} - -impl AppSettings { - fn bit(self) -> u32 { - 1 << (self as u8) - } -} diff --git a/vendor/clap_builder/src/builder/arg.rs b/vendor/clap_builder/src/builder/arg.rs deleted file mode 100644 index f83b464..0000000 --- a/vendor/clap_builder/src/builder/arg.rs +++ /dev/null @@ -1,4800 +0,0 @@ -// Std -#[cfg(feature = "env")] -use std::env; -#[cfg(feature = "env")] -use std::ffi::OsString; -use std::{ - cmp::{Ord, Ordering}, - fmt::{self, Display, Formatter}, - str, -}; - -// Internal -use super::{ArgFlags, ArgSettings}; -use crate::builder::ArgPredicate; -use crate::builder::IntoResettable; -use crate::builder::OsStr; -use crate::builder::PossibleValue; -use crate::builder::Str; -use crate::builder::StyledStr; -use crate::builder::Styles; -use crate::builder::ValueRange; -use crate::util::AnyValueId; -use crate::ArgAction; -use crate::Id; -use crate::ValueHint; -use crate::INTERNAL_ERROR_MSG; - -/// The abstract representation of a command line argument. Used to set all the options and -/// relationships that define a valid argument for the program. -/// -/// There are two methods for constructing [`Arg`]s, using the builder pattern and setting options -/// manually, or using a usage string which is far less verbose but has fewer options. You can also -/// use a combination of the two methods to achieve the best of both worlds. -/// -/// - [Basic API][crate::Arg#basic-api] -/// - [Value Handling][crate::Arg#value-handling] -/// - [Help][crate::Arg#help-1] -/// - [Advanced Argument Relations][crate::Arg#advanced-argument-relations] -/// - [Reflection][crate::Arg#reflection] -/// -/// # Examples -/// -/// ```rust -/// # use clap_builder as clap; -/// # use clap::{Arg, arg, ArgAction}; -/// // Using the traditional builder pattern and setting each option manually -/// let cfg = Arg::new("config") -/// .short('c') -/// .long("config") -/// .action(ArgAction::Set) -/// .value_name("FILE") -/// .help("Provides a config file to myprog"); -/// // Using a usage string (setting a similar argument to the one above) -/// let input = arg!(-i --input <FILE> "Provides an input file to the program"); -/// ``` -#[derive(Default, Clone)] -pub struct Arg { - pub(crate) id: Id, - pub(crate) help: Option<StyledStr>, - pub(crate) long_help: Option<StyledStr>, - pub(crate) action: Option<ArgAction>, - pub(crate) value_parser: Option<super::ValueParser>, - pub(crate) blacklist: Vec<Id>, - pub(crate) settings: ArgFlags, - pub(crate) overrides: Vec<Id>, - pub(crate) groups: Vec<Id>, - pub(crate) requires: Vec<(ArgPredicate, Id)>, - pub(crate) r_ifs: Vec<(Id, OsStr)>, - pub(crate) r_ifs_all: Vec<(Id, OsStr)>, - pub(crate) r_unless: Vec<Id>, - pub(crate) r_unless_all: Vec<Id>, - pub(crate) short: Option<char>, - pub(crate) long: Option<Str>, - pub(crate) aliases: Vec<(Str, bool)>, // (name, visible) - pub(crate) short_aliases: Vec<(char, bool)>, // (name, visible) - pub(crate) disp_ord: Option<usize>, - pub(crate) val_names: Vec<Str>, - pub(crate) num_vals: Option<ValueRange>, - pub(crate) val_delim: Option<char>, - pub(crate) default_vals: Vec<OsStr>, - pub(crate) default_vals_ifs: Vec<(Id, ArgPredicate, Option<OsStr>)>, - pub(crate) default_missing_vals: Vec<OsStr>, - #[cfg(feature = "env")] - pub(crate) env: Option<(OsStr, Option<OsString>)>, - pub(crate) terminator: Option<Str>, - pub(crate) index: Option<usize>, - pub(crate) help_heading: Option<Option<Str>>, - pub(crate) value_hint: Option<ValueHint>, -} - -/// # Basic API -impl Arg { - /// Create a new [`Arg`] with a unique name. - /// - /// The name is used to check whether or not the argument was used at - /// runtime, get values, set relationships with other args, etc.. - /// - /// **NOTE:** In the case of arguments that take values (i.e. [`Arg::action(ArgAction::Set)`]) - /// and positional arguments (i.e. those without a preceding `-` or `--`) the name will also - /// be displayed when the user prints the usage/help information of the program. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// Arg::new("config") - /// # ; - /// ``` - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - pub fn new(id: impl Into<Id>) -> Self { - Arg::default().id(id) - } - - /// Set the identifier used for referencing this argument in the clap API. - /// - /// See [`Arg::new`] for more details. - #[must_use] - pub fn id(mut self, id: impl Into<Id>) -> Self { - self.id = id.into(); - self - } - - /// Sets the short version of the argument without the preceding `-`. - /// - /// By default `V` and `h` are used by the auto-generated `version` and `help` arguments, - /// respectively. You will need to disable the auto-generated flags - /// ([`disable_help_flag`][crate::Command::disable_help_flag], - /// [`disable_version_flag`][crate::Command::disable_version_flag]) and define your own. - /// - /// # Examples - /// - /// When calling `short`, use a single valid UTF-8 character which will allow using the - /// argument via a single hyphen (`-`) such as `-c`: - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("config") - /// .short('c') - /// .action(ArgAction::Set)) - /// .get_matches_from(vec![ - /// "prog", "-c", "file.toml" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("config").map(String::as_str), Some("file.toml")); - /// ``` - /// - /// To use `-h` for your own flag and still have help: - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .disable_help_flag(true) - /// .arg(Arg::new("host") - /// .short('h') - /// .long("host")) - /// .arg(Arg::new("help") - /// .long("help") - /// .global(true) - /// .action(ArgAction::Help)) - /// .get_matches_from(vec![ - /// "prog", "-h", "wikipedia.org" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("host").map(String::as_str), Some("wikipedia.org")); - /// ``` - #[inline] - #[must_use] - pub fn short(mut self, s: impl IntoResettable<char>) -> Self { - if let Some(s) = s.into_resettable().into_option() { - debug_assert!(s != '-', "short option name cannot be `-`"); - self.short = Some(s); - } else { - self.short = None; - } - self - } - - /// Sets the long version of the argument without the preceding `--`. - /// - /// By default `version` and `help` are used by the auto-generated `version` and `help` - /// arguments, respectively. You may use the word `version` or `help` for the long form of your - /// own arguments, in which case `clap` simply will not assign those to the auto-generated - /// `version` or `help` arguments. - /// - /// **NOTE:** Any leading `-` characters will be stripped - /// - /// # Examples - /// - /// To set `long` use a word containing valid UTF-8. If you supply a double leading - /// `--` such as `--config` they will be stripped. Hyphens in the middle of the word, however, - /// will *not* be stripped (i.e. `config-file` is allowed). - /// - /// Setting `long` allows using the argument via a double hyphen (`--`) such as `--config` - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .action(ArgAction::Set)) - /// .get_matches_from(vec![ - /// "prog", "--config", "file.toml" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("cfg").map(String::as_str), Some("file.toml")); - /// ``` - #[inline] - #[must_use] - pub fn long(mut self, l: impl IntoResettable<Str>) -> Self { - self.long = l.into_resettable().into_option(); - self - } - - /// Add an alias, which functions as a hidden long flag. - /// - /// This is more efficient, and easier than creating multiple hidden arguments as one only - /// needs to check for the existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .long("test") - /// .alias("alias") - /// .action(ArgAction::Set)) - /// .get_matches_from(vec![ - /// "prog", "--alias", "cool" - /// ]); - /// assert_eq!(m.get_one::<String>("test").unwrap(), "cool"); - /// ``` - #[must_use] - pub fn alias(mut self, name: impl IntoResettable<Str>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - self.aliases.push((name, false)); - } else { - self.aliases.clear(); - } - self - } - - /// Add an alias, which functions as a hidden short flag. - /// - /// This is more efficient, and easier than creating multiple hidden arguments as one only - /// needs to check for the existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .short('t') - /// .short_alias('e') - /// .action(ArgAction::Set)) - /// .get_matches_from(vec![ - /// "prog", "-e", "cool" - /// ]); - /// assert_eq!(m.get_one::<String>("test").unwrap(), "cool"); - /// ``` - #[must_use] - pub fn short_alias(mut self, name: impl IntoResettable<char>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - debug_assert!(name != '-', "short alias name cannot be `-`"); - self.short_aliases.push((name, false)); - } else { - self.short_aliases.clear(); - } - self - } - - /// Add aliases, which function as hidden long flags. - /// - /// This is more efficient, and easier than creating multiple hidden subcommands as one only - /// needs to check for the existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .long("test") - /// .aliases(["do-stuff", "do-tests", "tests"]) - /// .action(ArgAction::SetTrue) - /// .help("the file to add") - /// .required(false)) - /// .get_matches_from(vec![ - /// "prog", "--do-tests" - /// ]); - /// assert_eq!(m.get_flag("test"), true); - /// ``` - #[must_use] - pub fn aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { - self.aliases - .extend(names.into_iter().map(|x| (x.into(), false))); - self - } - - /// Add aliases, which functions as a hidden short flag. - /// - /// This is more efficient, and easier than creating multiple hidden subcommands as one only - /// needs to check for the existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .short('t') - /// .short_aliases(['e', 's']) - /// .action(ArgAction::SetTrue) - /// .help("the file to add") - /// .required(false)) - /// .get_matches_from(vec![ - /// "prog", "-s" - /// ]); - /// assert_eq!(m.get_flag("test"), true); - /// ``` - #[must_use] - pub fn short_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self { - for s in names { - debug_assert!(s != '-', "short alias name cannot be `-`"); - self.short_aliases.push((s, false)); - } - self - } - - /// Add an alias, which functions as a visible long flag. - /// - /// Like [`Arg::alias`], except that they are visible inside the help message. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .visible_alias("something-awesome") - /// .long("test") - /// .action(ArgAction::Set)) - /// .get_matches_from(vec![ - /// "prog", "--something-awesome", "coffee" - /// ]); - /// assert_eq!(m.get_one::<String>("test").unwrap(), "coffee"); - /// ``` - /// [`Command::alias`]: Arg::alias() - #[must_use] - pub fn visible_alias(mut self, name: impl IntoResettable<Str>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - self.aliases.push((name, true)); - } else { - self.aliases.clear(); - } - self - } - - /// Add an alias, which functions as a visible short flag. - /// - /// Like [`Arg::short_alias`], except that they are visible inside the help message. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .long("test") - /// .visible_short_alias('t') - /// .action(ArgAction::Set)) - /// .get_matches_from(vec![ - /// "prog", "-t", "coffee" - /// ]); - /// assert_eq!(m.get_one::<String>("test").unwrap(), "coffee"); - /// ``` - #[must_use] - pub fn visible_short_alias(mut self, name: impl IntoResettable<char>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - debug_assert!(name != '-', "short alias name cannot be `-`"); - self.short_aliases.push((name, true)); - } else { - self.short_aliases.clear(); - } - self - } - - /// Add aliases, which function as visible long flags. - /// - /// Like [`Arg::aliases`], except that they are visible inside the help message. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .long("test") - /// .action(ArgAction::SetTrue) - /// .visible_aliases(["something", "awesome", "cool"])) - /// .get_matches_from(vec![ - /// "prog", "--awesome" - /// ]); - /// assert_eq!(m.get_flag("test"), true); - /// ``` - /// [`Command::aliases`]: Arg::aliases() - #[must_use] - pub fn visible_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { - self.aliases - .extend(names.into_iter().map(|n| (n.into(), true))); - self - } - - /// Add aliases, which function as visible short flags. - /// - /// Like [`Arg::short_aliases`], except that they are visible inside the help message. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .long("test") - /// .action(ArgAction::SetTrue) - /// .visible_short_aliases(['t', 'e'])) - /// .get_matches_from(vec![ - /// "prog", "-t" - /// ]); - /// assert_eq!(m.get_flag("test"), true); - /// ``` - #[must_use] - pub fn visible_short_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self { - for n in names { - debug_assert!(n != '-', "short alias name cannot be `-`"); - self.short_aliases.push((n, true)); - } - self - } - - /// Specifies the index of a positional argument **starting at** 1. - /// - /// **NOTE:** The index refers to position according to **other positional argument**. It does - /// not define position in the argument list as a whole. - /// - /// **NOTE:** You can optionally leave off the `index` method, and the index will be - /// assigned in order of evaluation. Utilizing the `index` method allows for setting - /// indexes out of order - /// - /// **NOTE:** This is only meant to be used for positional arguments and shouldn't to be used - /// with [`Arg::short`] or [`Arg::long`]. - /// - /// **NOTE:** When utilized with [`Arg::num_args(1..)`], only the **last** positional argument - /// may be defined as having a variable number of arguments (i.e. with the highest index) - /// - /// # Panics - /// - /// [`Command`] will [`panic!`] if indexes are skipped (such as defining `index(1)` and `index(3)` - /// but not `index(2)`, or a positional argument is defined as multiple and is not the highest - /// index (debug builds) - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// Arg::new("config") - /// .index(1) - /// # ; - /// ``` - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("mode") - /// .index(1)) - /// .arg(Arg::new("debug") - /// .long("debug") - /// .action(ArgAction::SetTrue)) - /// .get_matches_from(vec![ - /// "prog", "--debug", "fast" - /// ]); - /// - /// assert!(m.contains_id("mode")); - /// assert_eq!(m.get_one::<String>("mode").unwrap(), "fast"); // notice index(1) means "first positional" - /// // *not* first argument - /// ``` - /// [`Arg::short`]: Arg::short() - /// [`Arg::long`]: Arg::long() - /// [`Arg::num_args(true)`]: Arg::num_args() - /// [`Command`]: crate::Command - #[inline] - #[must_use] - pub fn index(mut self, idx: impl IntoResettable<usize>) -> Self { - self.index = idx.into_resettable().into_option(); - self - } - - /// This is a "VarArg" and everything that follows should be captured by it, as if the user had - /// used a `--`. - /// - /// **NOTE:** To start the trailing "VarArg" on unknown flags (and not just a positional - /// value), set [`allow_hyphen_values`][Arg::allow_hyphen_values]. Either way, users still - /// have the option to explicitly escape ambiguous arguments with `--`. - /// - /// **NOTE:** [`Arg::value_delimiter`] still applies if set. - /// - /// **NOTE:** Setting this requires [`Arg::num_args(..)`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, arg}; - /// let m = Command::new("myprog") - /// .arg(arg!(<cmd> ... "commands to run").trailing_var_arg(true)) - /// .get_matches_from(vec!["myprog", "arg1", "-r", "val1"]); - /// - /// let trail: Vec<_> = m.get_many::<String>("cmd").unwrap().collect(); - /// assert_eq!(trail, ["arg1", "-r", "val1"]); - /// ``` - /// [`Arg::num_args(..)`]: crate::Arg::num_args() - pub fn trailing_var_arg(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::TrailingVarArg) - } else { - self.unset_setting(ArgSettings::TrailingVarArg) - } - } - - /// This arg is the last, or final, positional argument (i.e. has the highest - /// index) and is *only* able to be accessed via the `--` syntax (i.e. `$ prog args -- - /// last_arg`). - /// - /// Even, if no other arguments are left to parse, if the user omits the `--` syntax - /// they will receive an [`UnknownArgument`] error. Setting an argument to `.last(true)` also - /// allows one to access this arg early using the `--` syntax. Accessing an arg early, even with - /// the `--` syntax is otherwise not possible. - /// - /// **NOTE:** This will change the usage string to look like `$ prog [OPTIONS] [-- <ARG>]` if - /// `ARG` is marked as `.last(true)`. - /// - /// **NOTE:** This setting will imply [`crate::Command::dont_collapse_args_in_usage`] because failing - /// to set this can make the usage string very confusing. - /// - /// **NOTE**: This setting only applies to positional arguments, and has no effect on OPTIONS - /// - /// **NOTE:** Setting this requires [taking values][Arg::num_args] - /// - /// **CAUTION:** Using this setting *and* having child subcommands is not - /// recommended with the exception of *also* using - /// [`crate::Command::args_conflicts_with_subcommands`] - /// (or [`crate::Command::subcommand_negates_reqs`] if the argument marked `Last` is also - /// marked [`Arg::required`]) - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Arg, ArgAction}; - /// Arg::new("args") - /// .action(ArgAction::Set) - /// .last(true) - /// # ; - /// ``` - /// - /// Setting `last` ensures the arg has the highest [index] of all positional args - /// and requires that the `--` syntax be used to access it early. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("first")) - /// .arg(Arg::new("second")) - /// .arg(Arg::new("third") - /// .action(ArgAction::Set) - /// .last(true)) - /// .try_get_matches_from(vec![ - /// "prog", "one", "--", "three" - /// ]); - /// - /// assert!(res.is_ok()); - /// let m = res.unwrap(); - /// assert_eq!(m.get_one::<String>("third").unwrap(), "three"); - /// assert_eq!(m.get_one::<String>("second"), None); - /// ``` - /// - /// Even if the positional argument marked `Last` is the only argument left to parse, - /// failing to use the `--` syntax results in an error. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("first")) - /// .arg(Arg::new("second")) - /// .arg(Arg::new("third") - /// .action(ArgAction::Set) - /// .last(true)) - /// .try_get_matches_from(vec![ - /// "prog", "one", "two", "three" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// ``` - /// [index]: Arg::index() - /// [`UnknownArgument`]: crate::error::ErrorKind::UnknownArgument - #[inline] - #[must_use] - pub fn last(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::Last) - } else { - self.unset_setting(ArgSettings::Last) - } - } - - /// Specifies that the argument must be present. - /// - /// Required by default means it is required, when no other conflicting rules or overrides have - /// been evaluated. Conflicting rules take precedence over being required. - /// - /// **Pro tip:** Flags (i.e. not positional, or arguments that take values) shouldn't be - /// required by default. This is because if a flag were to be required, it should simply be - /// implied. No additional information is required from user. Flags by their very nature are - /// simply boolean on/off switches. The only time a user *should* be required to use a flag - /// is if the operation is destructive in nature, and the user is essentially proving to you, - /// "Yes, I know what I'm doing." - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Arg; - /// Arg::new("config") - /// .required(true) - /// # ; - /// ``` - /// - /// Setting required requires that the argument be used at runtime. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required(true) - /// .action(ArgAction::Set) - /// .long("config")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "file.conf", - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting required and then *not* supplying that argument at runtime is an error. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required(true) - /// .action(ArgAction::Set) - /// .long("config")) - /// .try_get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - #[inline] - #[must_use] - pub fn required(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::Required) - } else { - self.unset_setting(ArgSettings::Required) - } - } - - /// Sets an argument that is required when this one is present - /// - /// i.e. when using this argument, the following argument *must* be present. - /// - /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Arg; - /// Arg::new("config") - /// .requires("input") - /// # ; - /// ``` - /// - /// Setting [`Arg::requires(name)`] requires that the argument be used at runtime if the - /// defining argument is used. If the defining argument isn't used, the other argument isn't - /// required - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .requires("input") - /// .long("config")) - /// .arg(Arg::new("input")) - /// .try_get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use cfg, so input wasn't required - /// ``` - /// - /// Setting [`Arg::requires(name)`] and *not* supplying that argument is an error. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .requires("input") - /// .long("config")) - /// .arg(Arg::new("input")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "file.conf" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: Arg::requires() - /// [Conflicting]: Arg::conflicts_with() - /// [override]: Arg::overrides_with() - #[must_use] - pub fn requires(mut self, arg_id: impl IntoResettable<Id>) -> Self { - if let Some(arg_id) = arg_id.into_resettable().into_option() { - self.requires.push((ArgPredicate::IsPresent, arg_id)); - } else { - self.requires.clear(); - } - self - } - - /// This argument must be passed alone; it conflicts with all other arguments. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Arg; - /// Arg::new("config") - /// .exclusive(true) - /// # ; - /// ``` - /// - /// Setting an exclusive argument and having any other arguments present at runtime - /// is an error. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("exclusive") - /// .action(ArgAction::Set) - /// .exclusive(true) - /// .long("exclusive")) - /// .arg(Arg::new("debug") - /// .long("debug")) - /// .arg(Arg::new("input")) - /// .try_get_matches_from(vec![ - /// "prog", "--exclusive", "file.conf", "file.txt" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); - /// ``` - #[inline] - #[must_use] - pub fn exclusive(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::Exclusive) - } else { - self.unset_setting(ArgSettings::Exclusive) - } - } - - /// Specifies that an argument can be matched to all child [`Subcommand`]s. - /// - /// **NOTE:** Global arguments *only* propagate down, **not** up (to parent commands), however - /// their values once a user uses them will be propagated back up to parents. In effect, this - /// means one should *define* all global arguments at the top level, however it doesn't matter - /// where the user *uses* the global argument. - /// - /// # Examples - /// - /// Assume an application with two subcommands, and you'd like to define a - /// `--verbose` flag that can be called on any of the subcommands and parent, but you don't - /// want to clutter the source with three duplicate [`Arg`] definitions. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("verb") - /// .long("verbose") - /// .short('v') - /// .action(ArgAction::SetTrue) - /// .global(true)) - /// .subcommand(Command::new("test")) - /// .subcommand(Command::new("do-stuff")) - /// .get_matches_from(vec![ - /// "prog", "do-stuff", "--verbose" - /// ]); - /// - /// assert_eq!(m.subcommand_name(), Some("do-stuff")); - /// let sub_m = m.subcommand_matches("do-stuff").unwrap(); - /// assert_eq!(sub_m.get_flag("verb"), true); - /// ``` - /// - /// [`Subcommand`]: crate::Subcommand - #[inline] - #[must_use] - pub fn global(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::Global) - } else { - self.unset_setting(ArgSettings::Global) - } - } - - #[inline] - pub(crate) fn is_set(&self, s: ArgSettings) -> bool { - self.settings.is_set(s) - } - - #[inline] - #[must_use] - pub(crate) fn setting(mut self, setting: ArgSettings) -> Self { - self.settings.set(setting); - self - } - - #[inline] - #[must_use] - pub(crate) fn unset_setting(mut self, setting: ArgSettings) -> Self { - self.settings.unset(setting); - self - } -} - -/// # Value Handling -impl Arg { - /// Specify how to react to an argument when parsing it. - /// - /// [ArgAction] controls things like - /// - Overwriting previous values with new ones - /// - Appending new values to all previous ones - /// - Counting how many times a flag occurs - /// - /// The default action is `ArgAction::Set` - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::Append) - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_many::<String>("flag").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(), - /// vec!["value"] - /// ); - /// ``` - #[inline] - #[must_use] - pub fn action(mut self, action: impl IntoResettable<ArgAction>) -> Self { - self.action = action.into_resettable().into_option(); - self - } - - /// Specify the typed behavior of the argument. - /// - /// This allows parsing and validating a value before storing it into - /// [`ArgMatches`][crate::ArgMatches] as the given type. - /// - /// Possible value parsers include: - /// - [`value_parser!(T)`][crate::value_parser!] for auto-selecting a value parser for a given type - /// - Or [range expressions like `0..=1`][std::ops::RangeBounds] as a shorthand for [`RangedI64ValueParser`][crate::builder::RangedI64ValueParser] - /// - `Fn(&str) -> Result<T, E>` - /// - `[&str]` and [`PossibleValuesParser`][crate::builder::PossibleValuesParser] for static enumerated values - /// - [`BoolishValueParser`][crate::builder::BoolishValueParser], and [`FalseyValueParser`][crate::builder::FalseyValueParser] for alternative `bool` implementations - /// - [`NonEmptyStringValueParser`][crate::builder::NonEmptyStringValueParser] for basic validation for strings - /// - or any other [`TypedValueParser`][crate::builder::TypedValueParser] implementation - /// - /// The default value is [`ValueParser::string`][crate::builder::ValueParser::string]. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::ArgAction; - /// let mut cmd = clap::Command::new("raw") - /// .arg( - /// clap::Arg::new("color") - /// .long("color") - /// .value_parser(["always", "auto", "never"]) - /// .default_value("auto") - /// ) - /// .arg( - /// clap::Arg::new("hostname") - /// .long("hostname") - /// .value_parser(clap::builder::NonEmptyStringValueParser::new()) - /// .action(ArgAction::Set) - /// .required(true) - /// ) - /// .arg( - /// clap::Arg::new("port") - /// .long("port") - /// .value_parser(clap::value_parser!(u16).range(3000..)) - /// .action(ArgAction::Set) - /// .required(true) - /// ); - /// - /// let m = cmd.try_get_matches_from_mut( - /// ["cmd", "--hostname", "rust-lang.org", "--port", "3001"] - /// ).unwrap(); - /// - /// let color: &String = m.get_one("color") - /// .expect("default"); - /// assert_eq!(color, "auto"); - /// - /// let hostname: &String = m.get_one("hostname") - /// .expect("required"); - /// assert_eq!(hostname, "rust-lang.org"); - /// - /// let port: u16 = *m.get_one("port") - /// .expect("required"); - /// assert_eq!(port, 3001); - /// ``` - pub fn value_parser(mut self, parser: impl IntoResettable<super::ValueParser>) -> Self { - self.value_parser = parser.into_resettable().into_option(); - self - } - - /// Specifies the number of arguments parsed per occurrence - /// - /// For example, if you had a `-f <file>` argument where you wanted exactly 3 'files' you would - /// set `.num_args(3)`, and this argument wouldn't be satisfied unless the user - /// provided 3 and only 3 values. - /// - /// Users may specify values for arguments in any of the following methods - /// - /// - Using a space such as `-o value` or `--option value` - /// - Using an equals and no space such as `-o=value` or `--option=value` - /// - Use a short and no space such as `-ovalue` - /// - /// **WARNING:** - /// - /// Setting a variable number of values (e.g. `1..=10`) for an argument without - /// other details can be dangerous in some circumstances. Because multiple values are - /// allowed, `--option val1 val2 val3` is perfectly valid. Be careful when designing a CLI - /// where **positional arguments** or **subcommands** are *also* expected as `clap` will continue - /// parsing *values* until one of the following happens: - /// - /// - It reaches the maximum number of values - /// - It reaches a specific number of values - /// - It finds another flag or option (i.e. something that starts with a `-`) - /// - It reaches the [`Arg::value_terminator`] if set - /// - /// Alternatively, - /// - Use a delimiter between values with [Arg::value_delimiter] - /// - Require a flag occurrence per value with [`ArgAction::Append`] - /// - Require positional arguments to appear after `--` with [`Arg::last`] - /// - /// # Examples - /// - /// Option: - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("mode") - /// .long("mode") - /// .num_args(1)) - /// .get_matches_from(vec![ - /// "prog", "--mode", "fast" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("mode").unwrap(), "fast"); - /// ``` - /// - /// Flag/option hybrid (see also [default_missing_value][Arg::default_missing_value]) - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let cmd = Command::new("prog") - /// .arg(Arg::new("mode") - /// .long("mode") - /// .default_missing_value("slow") - /// .default_value("plaid") - /// .num_args(0..=1)); - /// - /// let m = cmd.clone() - /// .get_matches_from(vec![ - /// "prog", "--mode", "fast" - /// ]); - /// assert_eq!(m.get_one::<String>("mode").unwrap(), "fast"); - /// - /// let m = cmd.clone() - /// .get_matches_from(vec![ - /// "prog", "--mode", - /// ]); - /// assert_eq!(m.get_one::<String>("mode").unwrap(), "slow"); - /// - /// let m = cmd.clone() - /// .get_matches_from(vec![ - /// "prog", - /// ]); - /// assert_eq!(m.get_one::<String>("mode").unwrap(), "plaid"); - /// ``` - /// - /// Tuples - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let cmd = Command::new("prog") - /// .arg(Arg::new("file") - /// .action(ArgAction::Set) - /// .num_args(2) - /// .short('F')); - /// - /// let m = cmd.clone() - /// .get_matches_from(vec![ - /// "prog", "-F", "in-file", "out-file" - /// ]); - /// assert_eq!( - /// m.get_many::<String>("file").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(), - /// vec!["in-file", "out-file"] - /// ); - /// - /// let res = cmd.clone() - /// .try_get_matches_from(vec![ - /// "prog", "-F", "file1" - /// ]); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::WrongNumberOfValues); - /// ``` - /// - /// A common mistake is to define an option which allows multiple values and a positional - /// argument. - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let cmd = Command::new("prog") - /// .arg(Arg::new("file") - /// .action(ArgAction::Set) - /// .num_args(0..) - /// .short('F')) - /// .arg(Arg::new("word")); - /// - /// let m = cmd.clone().get_matches_from(vec![ - /// "prog", "-F", "file1", "file2", "file3", "word" - /// ]); - /// let files: Vec<_> = m.get_many::<String>("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?! - /// assert!(!m.contains_id("word")); // but we clearly used word! - /// - /// // but this works - /// let m = cmd.clone().get_matches_from(vec![ - /// "prog", "word", "-F", "file1", "file2", "file3", - /// ]); - /// let files: Vec<_> = m.get_many::<String>("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3"]); - /// assert_eq!(m.get_one::<String>("word").unwrap(), "word"); - /// ``` - /// The problem is `clap` doesn't know when to stop parsing values for "file". - /// - /// A solution for the example above is to limit how many values with a maximum, or specific - /// number, or to say [`ArgAction::Append`] is ok, but multiple values are not. - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("file") - /// .action(ArgAction::Append) - /// .short('F')) - /// .arg(Arg::new("word")) - /// .get_matches_from(vec![ - /// "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word" - /// ]); - /// - /// let files: Vec<_> = m.get_many::<String>("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3"]); - /// assert_eq!(m.get_one::<String>("word").unwrap(), "word"); - /// ``` - #[inline] - #[must_use] - pub fn num_args(mut self, qty: impl IntoResettable<ValueRange>) -> Self { - self.num_vals = qty.into_resettable().into_option(); - self - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::num_args`") - )] - pub fn number_of_values(self, qty: usize) -> Self { - self.num_args(qty) - } - - /// Placeholder for the argument's value in the help message / usage. - /// - /// This name is cosmetic only; the name is **not** used to access arguments. - /// This setting can be very helpful when describing the type of input the user should be - /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to - /// use all capital letters for the value name. - /// - /// **NOTE:** implicitly sets [`Arg::action(ArgAction::Set)`] - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// Arg::new("cfg") - /// .long("config") - /// .value_name("FILE") - /// # ; - /// ``` - /// - /// ```rust - /// # use clap_builder as clap; - /// # #[cfg(feature = "help")] { - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("config") - /// .long("config") - /// .value_name("FILE") - /// .help("Some help text")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// # } - /// ``` - /// Running the above program produces the following output - /// - /// ```text - /// valnames - /// - /// Usage: valnames [OPTIONS] - /// - /// Options: - /// --config <FILE> Some help text - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - /// [positional]: Arg::index() - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - #[inline] - #[must_use] - pub fn value_name(mut self, name: impl IntoResettable<Str>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - self.value_names([name]) - } else { - self.val_names.clear(); - self - } - } - - /// Placeholders for the argument's values in the help message / usage. - /// - /// These names are cosmetic only, used for help and usage strings only. The names are **not** - /// used to access arguments. The values of the arguments are accessed in numeric order (i.e. - /// if you specify two names `one` and `two` `one` will be the first matched value, `two` will - /// be the second). - /// - /// This setting can be very helpful when describing the type of input the user should be - /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to - /// use all capital letters for the value name. - /// - /// **Pro Tip:** It may help to use [`Arg::next_line_help(true)`] if there are long, or - /// multiple value names in order to not throw off the help text alignment of all options. - /// - /// **NOTE:** implicitly sets [`Arg::action(ArgAction::Set)`] and [`Arg::num_args(1..)`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// Arg::new("speed") - /// .short('s') - /// .value_names(["fast", "slow"]); - /// ``` - /// - /// ```rust - /// # use clap_builder as clap; - /// # #[cfg(feature = "help")] { - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("io") - /// .long("io-files") - /// .value_names(["INFILE", "OUTFILE"])) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// # } - /// ``` - /// - /// Running the above program produces the following output - /// - /// ```text - /// valnames - /// - /// Usage: valnames [OPTIONS] - /// - /// Options: - /// -h, --help Print help information - /// --io-files <INFILE> <OUTFILE> Some help text - /// -V, --version Print version information - /// ``` - /// [`Arg::next_line_help(true)`]: Arg::next_line_help() - /// [`Arg::num_args`]: Arg::num_args() - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - /// [`Arg::num_args(1..)`]: Arg::num_args() - #[must_use] - pub fn value_names(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { - self.val_names = names.into_iter().map(|s| s.into()).collect(); - self - } - - /// Provide the shell a hint about how to complete this argument. - /// - /// See [`ValueHint`] for more information. - /// - /// **NOTE:** implicitly sets [`Arg::action(ArgAction::Set)`]. - /// - /// For example, to take a username as argument: - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Arg, ValueHint}; - /// Arg::new("user") - /// .short('u') - /// .long("user") - /// .value_hint(ValueHint::Username); - /// ``` - /// - /// To take a full command line and its arguments (for example, when writing a command wrapper): - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ValueHint, ArgAction}; - /// Command::new("prog") - /// .trailing_var_arg(true) - /// .arg( - /// Arg::new("command") - /// .action(ArgAction::Set) - /// .num_args(1..) - /// .value_hint(ValueHint::CommandWithArguments) - /// ); - /// ``` - #[must_use] - pub fn value_hint(mut self, value_hint: impl IntoResettable<ValueHint>) -> Self { - self.value_hint = value_hint.into_resettable().into_option(); - self - } - - /// Match values against [`PossibleValuesParser`][crate::builder::PossibleValuesParser] without matching case. - /// - /// When other arguments are conditionally required based on the - /// value of a case-insensitive argument, the equality check done - /// by [`Arg::required_if_eq`], [`Arg::required_if_eq_any`], or - /// [`Arg::required_if_eq_all`] is case-insensitive. - /// - /// - /// **NOTE:** Setting this requires [taking values][Arg::num_args] - /// - /// **NOTE:** To do unicode case folding, enable the `unicode` feature flag. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("pv") - /// .arg(Arg::new("option") - /// .long("option") - /// .action(ArgAction::Set) - /// .ignore_case(true) - /// .value_parser(["test123"])) - /// .get_matches_from(vec![ - /// "pv", "--option", "TeSt123", - /// ]); - /// - /// assert!(m.get_one::<String>("option").unwrap().eq_ignore_ascii_case("test123")); - /// ``` - /// - /// This setting also works when multiple values can be defined: - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("pv") - /// .arg(Arg::new("option") - /// .short('o') - /// .long("option") - /// .action(ArgAction::Set) - /// .ignore_case(true) - /// .num_args(1..) - /// .value_parser(["test123", "test321"])) - /// .get_matches_from(vec![ - /// "pv", "--option", "TeSt123", "teST123", "tESt321" - /// ]); - /// - /// let matched_vals = m.get_many::<String>("option").unwrap().collect::<Vec<_>>(); - /// assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]); - /// ``` - #[inline] - #[must_use] - pub fn ignore_case(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::IgnoreCase) - } else { - self.unset_setting(ArgSettings::IgnoreCase) - } - } - - /// Allows values which start with a leading hyphen (`-`) - /// - /// To limit values to just numbers, see - /// [`allow_negative_numbers`][Arg::allow_negative_numbers]. - /// - /// See also [`trailing_var_arg`][Arg::trailing_var_arg]. - /// - /// **NOTE:** Setting this requires [taking values][Arg::num_args] - /// - /// **WARNING:** Prior arguments with `allow_hyphen_values(true)` get precedence over known - /// flags but known flags get precedence over the next possible positional argument with - /// `allow_hyphen_values(true)`. When combined with [`Arg::num_args(..)`], - /// [`Arg::value_terminator`] is one way to ensure processing stops. - /// - /// **WARNING**: Take caution when using this setting combined with another argument using - /// [`Arg::num_args`], as this becomes ambiguous `$ prog --arg -- -- val`. All - /// three `--, --, val` will be values when the user may have thought the second `--` would - /// constitute the normal, "Only positional args follow" idiom. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("pat") - /// .action(ArgAction::Set) - /// .allow_hyphen_values(true) - /// .long("pattern")) - /// .get_matches_from(vec![ - /// "prog", "--pattern", "-file" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("pat").unwrap(), "-file"); - /// ``` - /// - /// Not setting `Arg::allow_hyphen_values(true)` and supplying a value which starts with a - /// hyphen is an error. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("pat") - /// .action(ArgAction::Set) - /// .long("pattern")) - /// .try_get_matches_from(vec![ - /// "prog", "--pattern", "-file" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// ``` - /// [`Arg::num_args(1)`]: Arg::num_args() - #[inline] - #[must_use] - pub fn allow_hyphen_values(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::AllowHyphenValues) - } else { - self.unset_setting(ArgSettings::AllowHyphenValues) - } - } - - /// Allows negative numbers to pass as values. - /// - /// This is similar to [`Arg::allow_hyphen_values`] except that it only allows numbers, - /// all other undefined leading hyphens will fail to parse. - /// - /// **NOTE:** Setting this requires [taking values][Arg::num_args] - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// let res = Command::new("myprog") - /// .arg(Arg::new("num").allow_negative_numbers(true)) - /// .try_get_matches_from(vec![ - /// "myprog", "-20" - /// ]); - /// assert!(res.is_ok()); - /// let m = res.unwrap(); - /// assert_eq!(m.get_one::<String>("num").unwrap(), "-20"); - /// ``` - #[inline] - pub fn allow_negative_numbers(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::AllowNegativeNumbers) - } else { - self.unset_setting(ArgSettings::AllowNegativeNumbers) - } - } - - /// Requires that options use the `--option=val` syntax - /// - /// i.e. an equals between the option and associated value. - /// - /// **NOTE:** Setting this requires [taking values][Arg::num_args] - /// - /// # Examples - /// - /// Setting `require_equals` requires that the option have an equals sign between - /// it and the associated value. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .require_equals(true) - /// .long("config")) - /// .try_get_matches_from(vec![ - /// "prog", "--config=file.conf" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting `require_equals` and *not* supplying the equals will cause an - /// error. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .require_equals(true) - /// .long("config")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "file.conf" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::NoEquals); - /// ``` - #[inline] - #[must_use] - pub fn require_equals(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::RequireEquals) - } else { - self.unset_setting(ArgSettings::RequireEquals) - } - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::value_delimiter`") - )] - pub fn use_value_delimiter(mut self, yes: bool) -> Self { - if yes { - self.val_delim.get_or_insert(','); - } else { - self.val_delim = None; - } - self - } - - /// Allow grouping of multiple values via a delimiter. - /// - /// i.e. should `--option=val1,val2,val3` be parsed as three values (`val1`, `val2`, - /// and `val3`) or as a single value (`val1,val2,val3`). Defaults to using `,` (comma) as the - /// value delimiter for all arguments that accept values (options and positional arguments) - /// - /// **NOTE:** implicitly sets [`Arg::action(ArgAction::Set)`] - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("config") - /// .short('c') - /// .long("config") - /// .value_delimiter(',')) - /// .get_matches_from(vec![ - /// "prog", "--config=val1,val2,val3" - /// ]); - /// - /// assert_eq!(m.get_many::<String>("config").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]) - /// ``` - /// [`Arg::value_delimiter(',')`]: Arg::value_delimiter() - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - #[inline] - #[must_use] - pub fn value_delimiter(mut self, d: impl IntoResettable<char>) -> Self { - self.val_delim = d.into_resettable().into_option(); - self - } - - /// Sentinel to **stop** parsing multiple values of a given argument. - /// - /// By default when - /// one sets [`num_args(1..)`] on an argument, clap will continue parsing values for that - /// argument until it reaches another valid argument, or one of the other more specific settings - /// for multiple values is used (such as [`num_args`]). - /// - /// **NOTE:** This setting only applies to [options] and [positional arguments] - /// - /// **NOTE:** When the terminator is passed in on the command line, it is **not** stored as one - /// of the values - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// Arg::new("vals") - /// .action(ArgAction::Set) - /// .num_args(1..) - /// .value_terminator(";") - /// # ; - /// ``` - /// - /// The following example uses two arguments, a sequence of commands, and the location in which - /// to perform them - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cmds") - /// .action(ArgAction::Set) - /// .num_args(1..) - /// .allow_hyphen_values(true) - /// .value_terminator(";")) - /// .arg(Arg::new("location")) - /// .get_matches_from(vec![ - /// "prog", "find", "-type", "f", "-name", "special", ";", "/home/clap" - /// ]); - /// let cmds: Vec<_> = m.get_many::<String>("cmds").unwrap().collect(); - /// assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]); - /// assert_eq!(m.get_one::<String>("location").unwrap(), "/home/clap"); - /// ``` - /// [options]: Arg::action - /// [positional arguments]: Arg::index() - /// [`num_args(1..)`]: Arg::num_args() - /// [`num_args`]: Arg::num_args() - #[inline] - #[must_use] - pub fn value_terminator(mut self, term: impl IntoResettable<Str>) -> Self { - self.terminator = term.into_resettable().into_option(); - self - } - - /// Consume all following arguments. - /// - /// Do not be parse them individually, but rather pass them in entirety. - /// - /// It is worth noting that setting this requires all values to come after a `--` to indicate - /// they should all be captured. For example: - /// - /// ```text - /// --foo something -- -v -v -v -b -b -b --baz -q -u -x - /// ``` - /// - /// Will result in everything after `--` to be considered one raw argument. This behavior - /// may not be exactly what you are expecting and using [`Arg::trailing_var_arg`] - /// may be more appropriate. - /// - /// **NOTE:** Implicitly sets [`Arg::action(ArgAction::Set)`] [`Arg::num_args(1..)`], - /// [`Arg::allow_hyphen_values(true)`], and [`Arg::last(true)`] when set to `true`. - /// - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - /// [`Arg::num_args(1..)`]: Arg::num_args() - /// [`Arg::allow_hyphen_values(true)`]: Arg::allow_hyphen_values() - /// [`Arg::last(true)`]: Arg::last() - #[inline] - #[must_use] - pub fn raw(mut self, yes: bool) -> Self { - if yes { - self.num_vals.get_or_insert_with(|| (1..).into()); - } - self.allow_hyphen_values(yes).last(yes) - } - - /// Value for the argument when not present. - /// - /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::contains_id`] will - /// still return `true`. If you wish to determine whether the argument was used at runtime or - /// not, consider [`ArgMatches::value_source`][crate::ArgMatches::value_source]. - /// - /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value_if`] but slightly - /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg - /// at runtime. `Arg::default_value_if` however only takes effect when the user has not provided - /// a value at runtime **and** these other conditions are met as well. If you have set - /// `Arg::default_value` and `Arg::default_value_if`, and the user **did not** provide this arg - /// at runtime, nor were the conditions met for `Arg::default_value_if`, the `Arg::default_value` - /// will be applied. - /// - /// Like with command-line values, this will be split by [`Arg::value_delimiter`]. - /// - /// # Examples - /// - /// First we use the default value without providing any value at runtime. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, parser::ValueSource}; - /// let m = Command::new("prog") - /// .arg(Arg::new("opt") - /// .long("myopt") - /// .default_value("myval")) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("opt").unwrap(), "myval"); - /// assert!(m.contains_id("opt")); - /// assert_eq!(m.value_source("opt"), Some(ValueSource::DefaultValue)); - /// ``` - /// - /// Next we provide a value at runtime to override the default. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, parser::ValueSource}; - /// let m = Command::new("prog") - /// .arg(Arg::new("opt") - /// .long("myopt") - /// .default_value("myval")) - /// .get_matches_from(vec![ - /// "prog", "--myopt=non_default" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("opt").unwrap(), "non_default"); - /// assert!(m.contains_id("opt")); - /// assert_eq!(m.value_source("opt"), Some(ValueSource::CommandLine)); - /// ``` - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - /// [`ArgMatches::contains_id`]: crate::ArgMatches::contains_id() - /// [`Arg::default_value_if`]: Arg::default_value_if() - #[inline] - #[must_use] - pub fn default_value(mut self, val: impl IntoResettable<OsStr>) -> Self { - if let Some(val) = val.into_resettable().into_option() { - self.default_values([val]) - } else { - self.default_vals.clear(); - self - } - } - - #[inline] - #[must_use] - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value`") - )] - pub fn default_value_os(self, val: impl Into<OsStr>) -> Self { - self.default_values([val]) - } - - /// Value for the argument when not present. - /// - /// See [`Arg::default_value`]. - /// - /// [`Arg::default_value`]: Arg::default_value() - #[inline] - #[must_use] - pub fn default_values(mut self, vals: impl IntoIterator<Item = impl Into<OsStr>>) -> Self { - self.default_vals = vals.into_iter().map(|s| s.into()).collect(); - self - } - - #[inline] - #[must_use] - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::default_values`") - )] - pub fn default_values_os(self, vals: impl IntoIterator<Item = impl Into<OsStr>>) -> Self { - self.default_values(vals) - } - - /// Value for the argument when the flag is present but no value is specified. - /// - /// This configuration option is often used to give the user a shortcut and allow them to - /// efficiently specify an option argument without requiring an explicitly value. The `--color` - /// argument is a common example. By, supplying an default, such as `default_missing_value("always")`, - /// the user can quickly just add `--color` to the command line to produce the desired color output. - /// - /// **NOTE:** using this configuration option requires the use of the - /// [`.num_args(0..N)`][Arg::num_args] and the - /// [`.require_equals(true)`][Arg::require_equals] configuration option. These are required in - /// order to unambiguously determine what, if any, value was supplied for the argument. - /// - /// Like with command-line values, this will be split by [`Arg::value_delimiter`]. - /// - /// # Examples - /// - /// For POSIX style `--color`: - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, parser::ValueSource}; - /// fn cli() -> Command { - /// Command::new("prog") - /// .arg(Arg::new("color").long("color") - /// .value_name("WHEN") - /// .value_parser(["always", "auto", "never"]) - /// .default_value("auto") - /// .num_args(0..=1) - /// .require_equals(true) - /// .default_missing_value("always") - /// .help("Specify WHEN to colorize output.") - /// ) - /// } - /// - /// // first, we'll provide no arguments - /// let m = cli().get_matches_from(vec![ - /// "prog" - /// ]); - /// assert_eq!(m.get_one::<String>("color").unwrap(), "auto"); - /// assert_eq!(m.value_source("color"), Some(ValueSource::DefaultValue)); - /// - /// // next, we'll provide a runtime value to override the default (as usually done). - /// let m = cli().get_matches_from(vec![ - /// "prog", "--color=never" - /// ]); - /// assert_eq!(m.get_one::<String>("color").unwrap(), "never"); - /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine)); - /// - /// // finally, we will use the shortcut and only provide the argument without a value. - /// let m = cli().get_matches_from(vec![ - /// "prog", "--color" - /// ]); - /// assert_eq!(m.get_one::<String>("color").unwrap(), "always"); - /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine)); - /// ``` - /// - /// For bool literals: - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, parser::ValueSource, value_parser}; - /// fn cli() -> Command { - /// Command::new("prog") - /// .arg(Arg::new("create").long("create") - /// .value_name("BOOL") - /// .value_parser(value_parser!(bool)) - /// .num_args(0..=1) - /// .require_equals(true) - /// .default_missing_value("true") - /// ) - /// } - /// - /// // first, we'll provide no arguments - /// let m = cli().get_matches_from(vec![ - /// "prog" - /// ]); - /// assert_eq!(m.get_one::<bool>("create").copied(), None); - /// - /// // next, we'll provide a runtime value to override the default (as usually done). - /// let m = cli().get_matches_from(vec![ - /// "prog", "--create=false" - /// ]); - /// assert_eq!(m.get_one::<bool>("create").copied(), Some(false)); - /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine)); - /// - /// // finally, we will use the shortcut and only provide the argument without a value. - /// let m = cli().get_matches_from(vec![ - /// "prog", "--create" - /// ]); - /// assert_eq!(m.get_one::<bool>("create").copied(), Some(true)); - /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine)); - /// ``` - /// - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - /// [`Arg::default_value`]: Arg::default_value() - #[inline] - #[must_use] - pub fn default_missing_value(mut self, val: impl IntoResettable<OsStr>) -> Self { - if let Some(val) = val.into_resettable().into_option() { - self.default_missing_values_os([val]) - } else { - self.default_missing_vals.clear(); - self - } - } - - /// Value for the argument when the flag is present but no value is specified. - /// - /// See [`Arg::default_missing_value`]. - /// - /// [`Arg::default_missing_value`]: Arg::default_missing_value() - /// [`OsStr`]: std::ffi::OsStr - #[inline] - #[must_use] - pub fn default_missing_value_os(self, val: impl Into<OsStr>) -> Self { - self.default_missing_values_os([val]) - } - - /// Value for the argument when the flag is present but no value is specified. - /// - /// See [`Arg::default_missing_value`]. - /// - /// [`Arg::default_missing_value`]: Arg::default_missing_value() - #[inline] - #[must_use] - pub fn default_missing_values(self, vals: impl IntoIterator<Item = impl Into<OsStr>>) -> Self { - self.default_missing_values_os(vals) - } - - /// Value for the argument when the flag is present but no value is specified. - /// - /// See [`Arg::default_missing_values`]. - /// - /// [`Arg::default_missing_values`]: Arg::default_missing_values() - /// [`OsStr`]: std::ffi::OsStr - #[inline] - #[must_use] - pub fn default_missing_values_os( - mut self, - vals: impl IntoIterator<Item = impl Into<OsStr>>, - ) -> Self { - self.default_missing_vals = vals.into_iter().map(|s| s.into()).collect(); - self - } - - /// Read from `name` environment variable when argument is not present. - /// - /// If it is not present in the environment, then default - /// rules will apply. - /// - /// If user sets the argument in the environment: - /// - When [`Arg::action(ArgAction::Set)`] is not set, the flag is considered raised. - /// - When [`Arg::action(ArgAction::Set)`] is set, - /// [`ArgMatches::get_one`][crate::ArgMatches::get_one] will - /// return value of the environment variable. - /// - /// If user doesn't set the argument in the environment: - /// - When [`Arg::action(ArgAction::Set)`] is not set, the flag is considered off. - /// - When [`Arg::action(ArgAction::Set)`] is set, - /// [`ArgMatches::get_one`][crate::ArgMatches::get_one] will - /// return the default specified. - /// - /// Like with command-line values, this will be split by [`Arg::value_delimiter`]. - /// - /// # Examples - /// - /// In this example, we show the variable coming from the environment: - /// - /// ```rust - /// # use clap_builder as clap; - /// # use std::env; - /// # use clap::{Command, Arg, ArgAction}; - /// - /// env::set_var("MY_FLAG", "env"); - /// - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .env("MY_FLAG") - /// .action(ArgAction::Set)) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("flag").unwrap(), "env"); - /// ``` - /// - /// In this example, because `prog` is a flag that accepts an optional, case-insensitive - /// boolean literal. - /// - /// Note that the value parser controls how flags are parsed. In this case we've selected - /// [`FalseyValueParser`][crate::builder::FalseyValueParser]. A `false` literal is `n`, `no`, - /// `f`, `false`, `off` or `0`. An absent environment variable will also be considered as - /// `false`. Anything else will considered as `true`. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use std::env; - /// # use clap::{Command, Arg, ArgAction}; - /// # use clap::builder::FalseyValueParser; - /// - /// env::set_var("TRUE_FLAG", "true"); - /// env::set_var("FALSE_FLAG", "0"); - /// - /// let m = Command::new("prog") - /// .arg(Arg::new("true_flag") - /// .long("true_flag") - /// .action(ArgAction::SetTrue) - /// .value_parser(FalseyValueParser::new()) - /// .env("TRUE_FLAG")) - /// .arg(Arg::new("false_flag") - /// .long("false_flag") - /// .action(ArgAction::SetTrue) - /// .value_parser(FalseyValueParser::new()) - /// .env("FALSE_FLAG")) - /// .arg(Arg::new("absent_flag") - /// .long("absent_flag") - /// .action(ArgAction::SetTrue) - /// .value_parser(FalseyValueParser::new()) - /// .env("ABSENT_FLAG")) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert!(m.get_flag("true_flag")); - /// assert!(!m.get_flag("false_flag")); - /// assert!(!m.get_flag("absent_flag")); - /// ``` - /// - /// In this example, we show the variable coming from an option on the CLI: - /// - /// ```rust - /// # use clap_builder as clap; - /// # use std::env; - /// # use clap::{Command, Arg, ArgAction}; - /// - /// env::set_var("MY_FLAG", "env"); - /// - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .env("MY_FLAG") - /// .action(ArgAction::Set)) - /// .get_matches_from(vec![ - /// "prog", "--flag", "opt" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("flag").unwrap(), "opt"); - /// ``` - /// - /// In this example, we show the variable coming from the environment even with the - /// presence of a default: - /// - /// ```rust - /// # use clap_builder as clap; - /// # use std::env; - /// # use clap::{Command, Arg, ArgAction}; - /// - /// env::set_var("MY_FLAG", "env"); - /// - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .env("MY_FLAG") - /// .action(ArgAction::Set) - /// .default_value("default")) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("flag").unwrap(), "env"); - /// ``` - /// - /// In this example, we show the use of multiple values in a single environment variable: - /// - /// ```rust - /// # use clap_builder as clap; - /// # use std::env; - /// # use clap::{Command, Arg, ArgAction}; - /// - /// env::set_var("MY_FLAG_MULTI", "env1,env2"); - /// - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .env("MY_FLAG_MULTI") - /// .action(ArgAction::Set) - /// .num_args(1..) - /// .value_delimiter(',')) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.get_many::<String>("flag").unwrap().collect::<Vec<_>>(), vec!["env1", "env2"]); - /// ``` - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - /// [`Arg::value_delimiter(',')`]: Arg::value_delimiter() - #[cfg(feature = "env")] - #[inline] - #[must_use] - pub fn env(mut self, name: impl IntoResettable<OsStr>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - let value = env::var_os(&name); - self.env = Some((name, value)); - } else { - self.env = None; - } - self - } - - #[cfg(feature = "env")] - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::env`") - )] - pub fn env_os(self, name: impl Into<OsStr>) -> Self { - self.env(name) - } -} - -/// # Help -impl Arg { - /// Sets the description of the argument for short help (`-h`). - /// - /// Typically, this is a short (one line) description of the arg. - /// - /// If [`Arg::long_help`] is not specified, this message will be displayed for `--help`. - /// - /// **NOTE:** Only `Arg::help` is used in completion script generation in order to be concise - /// - /// # Examples - /// - /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to - /// include a newline in the help text and have the following text be properly aligned with all - /// the other help text. - /// - /// Setting `help` displays a short message to the side of the argument when the user passes - /// `-h` or `--help` (by default). - /// - /// ```rust - /// # #[cfg(feature = "help")] { - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// # } - /// ``` - /// - /// The above example displays - /// - /// ```notrust - /// helptest - /// - /// Usage: helptest [OPTIONS] - /// - /// Options: - /// --config Some help text describing the --config arg - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - /// [`Arg::long_help`]: Arg::long_help() - #[inline] - #[must_use] - pub fn help(mut self, h: impl IntoResettable<StyledStr>) -> Self { - self.help = h.into_resettable().into_option(); - self - } - - /// Sets the description of the argument for long help (`--help`). - /// - /// Typically this a more detailed (multi-line) message - /// that describes the arg. - /// - /// If [`Arg::help`] is not specified, this message will be displayed for `-h`. - /// - /// **NOTE:** Only [`Arg::help`] is used in completion script generation in order to be concise - /// - /// # Examples - /// - /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to - /// include a newline in the help text and have the following text be properly aligned with all - /// the other help text. - /// - /// Setting `help` displays a short message to the side of the argument when the user passes - /// `-h` or `--help` (by default). - /// - /// ```rust - /// # #[cfg(feature = "help")] { - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .long_help( - /// "The config file used by the myprog must be in JSON format - /// with only valid keys and may not contain other nonsense - /// that cannot be read by this program. Obviously I'm going on - /// and on, so I'll stop now.")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// # } - /// ``` - /// - /// The above example displays - /// - /// ```text - /// prog - /// - /// Usage: prog [OPTIONS] - /// - /// Options: - /// --config - /// The config file used by the myprog must be in JSON format - /// with only valid keys and may not contain other nonsense - /// that cannot be read by this program. Obviously I'm going on - /// and on, so I'll stop now. - /// - /// -h, --help - /// Print help information - /// - /// -V, --version - /// Print version information - /// ``` - /// [`Arg::help`]: Arg::help() - #[inline] - #[must_use] - pub fn long_help(mut self, h: impl IntoResettable<StyledStr>) -> Self { - self.long_help = h.into_resettable().into_option(); - self - } - - /// Allows custom ordering of args within the help message. - /// - /// `Arg`s with a lower value will be displayed first in the help message. - /// Those with the same display order will be sorted. - /// - /// `Arg`s are automatically assigned a display order based on the order they are added to the - /// [`Command`][crate::Command]. - /// Overriding this is helpful when the order arguments are added in isn't the same as the - /// display order, whether in one-off cases or to automatically sort arguments. - /// - /// To change, see [`Command::next_display_order`][crate::Command::next_display_order]. - /// - /// **NOTE:** This setting is ignored for [positional arguments] which are always displayed in - /// [index] order. - /// - /// # Examples - /// - /// ```rust - /// # #[cfg(feature = "help")] { - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("boat") - /// .short('b') - /// .long("boat") - /// .action(ArgAction::Set) - /// .display_order(0) // Sort - /// .help("Some help and text")) - /// .arg(Arg::new("airplane") - /// .short('a') - /// .long("airplane") - /// .action(ArgAction::Set) - /// .display_order(0) // Sort - /// .help("I should be first!")) - /// .arg(Arg::new("custom-help") - /// .short('?') - /// .action(ArgAction::Help) - /// .display_order(100) // Don't sort - /// .help("Alt help")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// # } - /// ``` - /// - /// The above example displays the following help message - /// - /// ```text - /// cust-ord - /// - /// Usage: cust-ord [OPTIONS] - /// - /// Options: - /// -a, --airplane <airplane> I should be first! - /// -b, --boat <boar> Some help and text - /// -h, --help Print help information - /// -? Alt help - /// ``` - /// [positional arguments]: Arg::index() - /// [index]: Arg::index() - #[inline] - #[must_use] - pub fn display_order(mut self, ord: impl IntoResettable<usize>) -> Self { - self.disp_ord = ord.into_resettable().into_option(); - self - } - - /// Override the [current] help section. - /// - /// [current]: crate::Command::next_help_heading - #[inline] - #[must_use] - pub fn help_heading(mut self, heading: impl IntoResettable<Str>) -> Self { - self.help_heading = Some(heading.into_resettable().into_option()); - self - } - - /// Render the [help][Arg::help] on the line after the argument. - /// - /// This can be helpful for arguments with very long or complex help messages. - /// This can also be helpful for arguments with very long flag names, or many/long value names. - /// - /// **NOTE:** To apply this setting to all arguments and subcommands, consider using - /// [`crate::Command::next_line_help`] - /// - /// # Examples - /// - /// ```rust - /// # #[cfg(feature = "help")] { - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("opt") - /// .long("long-option-flag") - /// .short('o') - /// .action(ArgAction::Set) - /// .next_line_help(true) - /// .value_names(["value1", "value2"]) - /// .help("Some really long help and complex\n\ - /// help that makes more sense to be\n\ - /// on a line after the option")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// # } - /// ``` - /// - /// The above example displays the following help message - /// - /// ```text - /// nlh - /// - /// Usage: nlh [OPTIONS] - /// - /// Options: - /// -h, --help Print help information - /// -V, --version Print version information - /// -o, --long-option-flag <value1> <value2> - /// Some really long help and complex - /// help that makes more sense to be - /// on a line after the option - /// ``` - #[inline] - #[must_use] - pub fn next_line_help(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::NextLineHelp) - } else { - self.unset_setting(ArgSettings::NextLineHelp) - } - } - - /// Do not display the argument in help message. - /// - /// **NOTE:** This does **not** hide the argument from usage strings on error - /// - /// # Examples - /// - /// Setting `Hidden` will hide the argument when displaying help text - /// - /// ```rust - /// # #[cfg(feature = "help")] { - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .hide(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// # } - /// ``` - /// - /// The above example displays - /// - /// ```text - /// helptest - /// - /// Usage: helptest [OPTIONS] - /// - /// Options: - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - #[inline] - #[must_use] - pub fn hide(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::Hidden) - } else { - self.unset_setting(ArgSettings::Hidden) - } - } - - /// Do not display the [possible values][crate::builder::ValueParser::possible_values] in the help message. - /// - /// This is useful for args with many values, or ones which are explained elsewhere in the - /// help text. - /// - /// **NOTE:** Setting this requires [taking values][Arg::num_args] - /// - /// To set this for all arguments, see - /// [`Command::hide_possible_values`][crate::Command::hide_possible_values]. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("mode") - /// .long("mode") - /// .value_parser(["fast", "slow"]) - /// .action(ArgAction::Set) - /// .hide_possible_values(true)); - /// ``` - /// If we were to run the above program with `--help` the `[values: fast, slow]` portion of - /// the help text would be omitted. - #[inline] - #[must_use] - pub fn hide_possible_values(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::HidePossibleValues) - } else { - self.unset_setting(ArgSettings::HidePossibleValues) - } - } - - /// Do not display the default value of the argument in the help message. - /// - /// This is useful when default behavior of an arg is explained elsewhere in the help text. - /// - /// **NOTE:** Setting this requires [taking values][Arg::num_args] - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("connect") - /// .arg(Arg::new("host") - /// .long("host") - /// .default_value("localhost") - /// .action(ArgAction::Set) - /// .hide_default_value(true)); - /// - /// ``` - /// - /// If we were to run the above program with `--help` the `[default: localhost]` portion of - /// the help text would be omitted. - #[inline] - #[must_use] - pub fn hide_default_value(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::HideDefaultValue) - } else { - self.unset_setting(ArgSettings::HideDefaultValue) - } - } - - /// Do not display in help the environment variable name. - /// - /// This is useful when the variable option is explained elsewhere in the help text. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("mode") - /// .long("mode") - /// .env("MODE") - /// .action(ArgAction::Set) - /// .hide_env(true)); - /// ``` - /// - /// If we were to run the above program with `--help` the `[env: MODE]` portion of the help - /// text would be omitted. - #[cfg(feature = "env")] - #[inline] - #[must_use] - pub fn hide_env(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::HideEnv) - } else { - self.unset_setting(ArgSettings::HideEnv) - } - } - - /// Do not display in help any values inside the associated ENV variables for the argument. - /// - /// This is useful when ENV vars contain sensitive values. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("connect") - /// .arg(Arg::new("host") - /// .long("host") - /// .env("CONNECT") - /// .action(ArgAction::Set) - /// .hide_env_values(true)); - /// - /// ``` - /// - /// If we were to run the above program with `$ CONNECT=super_secret connect --help` the - /// `[default: CONNECT=super_secret]` portion of the help text would be omitted. - #[cfg(feature = "env")] - #[inline] - #[must_use] - pub fn hide_env_values(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::HideEnvValues) - } else { - self.unset_setting(ArgSettings::HideEnvValues) - } - } - - /// Hides an argument from short help (`-h`). - /// - /// **NOTE:** This does **not** hide the argument from usage strings on error - /// - /// **NOTE:** Setting this option will cause next-line-help output style to be used - /// when long help (`--help`) is called. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// Arg::new("debug") - /// .hide_short_help(true); - /// ``` - /// - /// Setting `hide_short_help(true)` will hide the argument when displaying short help text - /// - /// ```rust - /// # #[cfg(feature = "help")] { - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .hide_short_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "-h" - /// ]); - /// # } - /// ``` - /// - /// The above example displays - /// - /// ```text - /// helptest - /// - /// Usage: helptest [OPTIONS] - /// - /// Options: - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - /// - /// However, when --help is called - /// - /// ```rust - /// # #[cfg(feature = "help")] { - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .hide_short_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// # } - /// ``` - /// - /// Then the following would be displayed - /// - /// ```text - /// helptest - /// - /// Usage: helptest [OPTIONS] - /// - /// Options: - /// --config Some help text describing the --config arg - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - #[inline] - #[must_use] - pub fn hide_short_help(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::HiddenShortHelp) - } else { - self.unset_setting(ArgSettings::HiddenShortHelp) - } - } - - /// Hides an argument from long help (`--help`). - /// - /// **NOTE:** This does **not** hide the argument from usage strings on error - /// - /// **NOTE:** Setting this option will cause next-line-help output style to be used - /// when long help (`--help`) is called. - /// - /// # Examples - /// - /// Setting `hide_long_help(true)` will hide the argument when displaying long help text - /// - /// ```rust - /// # #[cfg(feature = "help")] { - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .hide_long_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// # } - /// ``` - /// - /// The above example displays - /// - /// ```text - /// helptest - /// - /// Usage: helptest [OPTIONS] - /// - /// Options: - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - /// - /// However, when -h is called - /// - /// ```rust - /// # #[cfg(feature = "help")] { - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .hide_long_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "-h" - /// ]); - /// # } - /// ``` - /// - /// Then the following would be displayed - /// - /// ```text - /// helptest - /// - /// Usage: helptest [OPTIONS] - /// - /// OPTIONS: - /// --config Some help text describing the --config arg - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - #[inline] - #[must_use] - pub fn hide_long_help(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::HiddenLongHelp) - } else { - self.unset_setting(ArgSettings::HiddenLongHelp) - } - } -} - -/// # Advanced Argument Relations -impl Arg { - /// The name of the [`ArgGroup`] the argument belongs to. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// Arg::new("debug") - /// .long("debug") - /// .action(ArgAction::SetTrue) - /// .group("mode") - /// # ; - /// ``` - /// - /// Multiple arguments can be a member of a single group and then the group checked as if it - /// was one of said arguments. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("debug") - /// .long("debug") - /// .action(ArgAction::SetTrue) - /// .group("mode")) - /// .arg(Arg::new("verbose") - /// .long("verbose") - /// .action(ArgAction::SetTrue) - /// .group("mode")) - /// .get_matches_from(vec![ - /// "prog", "--debug" - /// ]); - /// assert!(m.contains_id("mode")); - /// ``` - /// - /// [`ArgGroup`]: crate::ArgGroup - #[must_use] - pub fn group(mut self, group_id: impl IntoResettable<Id>) -> Self { - if let Some(group_id) = group_id.into_resettable().into_option() { - self.groups.push(group_id); - } else { - self.groups.clear(); - } - self - } - - /// The names of [`ArgGroup`]'s the argument belongs to. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// Arg::new("debug") - /// .long("debug") - /// .action(ArgAction::SetTrue) - /// .groups(["mode", "verbosity"]) - /// # ; - /// ``` - /// - /// Arguments can be members of multiple groups and then the group checked as if it - /// was one of said arguments. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("debug") - /// .long("debug") - /// .action(ArgAction::SetTrue) - /// .groups(["mode", "verbosity"])) - /// .arg(Arg::new("verbose") - /// .long("verbose") - /// .action(ArgAction::SetTrue) - /// .groups(["mode", "verbosity"])) - /// .get_matches_from(vec![ - /// "prog", "--debug" - /// ]); - /// assert!(m.contains_id("mode")); - /// assert!(m.contains_id("verbosity")); - /// ``` - /// - /// [`ArgGroup`]: crate::ArgGroup - #[must_use] - pub fn groups(mut self, group_ids: impl IntoIterator<Item = impl Into<Id>>) -> Self { - self.groups.extend(group_ids.into_iter().map(Into::into)); - self - } - - /// Specifies the value of the argument if `arg` has been used at runtime. - /// - /// If `default` is set to `None`, `default_value` will be removed. - /// - /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value`] but slightly - /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg - /// at runtime. This setting however only takes effect when the user has not provided a value at - /// runtime **and** these other conditions are met as well. If you have set `Arg::default_value` - /// and `Arg::default_value_if`, and the user **did not** provide this arg at runtime, nor were - /// the conditions met for `Arg::default_value_if`, the `Arg::default_value` will be applied. - /// - /// Like with command-line values, this will be split by [`Arg::value_delimiter`]. - /// - /// # Examples - /// - /// First we use the default value only if another arg is present at runtime. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// # use clap::builder::{ArgPredicate}; - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_if("flag", ArgPredicate::IsPresent, Some("default"))) - /// .get_matches_from(vec![ - /// "prog", "--flag" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("other").unwrap(), "default"); - /// ``` - /// - /// Next we run the same test, but without providing `--flag`. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_if("flag", "true", Some("default"))) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("other"), None); - /// ``` - /// - /// Now lets only use the default value if `--opt` contains the value `special`. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("opt") - /// .action(ArgAction::Set) - /// .long("opt")) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_if("opt", "special", Some("default"))) - /// .get_matches_from(vec![ - /// "prog", "--opt", "special" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("other").unwrap(), "default"); - /// ``` - /// - /// We can run the same test and provide any value *other than* `special` and we won't get a - /// default value. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("opt") - /// .action(ArgAction::Set) - /// .long("opt")) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_if("opt", "special", Some("default"))) - /// .get_matches_from(vec![ - /// "prog", "--opt", "hahaha" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("other"), None); - /// ``` - /// - /// If we want to unset the default value for an Arg based on the presence or - /// value of some other Arg. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value("default") - /// .default_value_if("flag", "true", None)) - /// .get_matches_from(vec![ - /// "prog", "--flag" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("other"), None); - /// ``` - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - /// [`Arg::default_value`]: Arg::default_value() - #[must_use] - pub fn default_value_if( - mut self, - arg_id: impl Into<Id>, - predicate: impl Into<ArgPredicate>, - default: impl IntoResettable<OsStr>, - ) -> Self { - self.default_vals_ifs.push(( - arg_id.into(), - predicate.into(), - default.into_resettable().into_option(), - )); - self - } - - #[must_use] - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value_if`") - )] - pub fn default_value_if_os( - self, - arg_id: impl Into<Id>, - predicate: impl Into<ArgPredicate>, - default: impl IntoResettable<OsStr>, - ) -> Self { - self.default_value_if(arg_id, predicate, default) - } - - /// Specifies multiple values and conditions in the same manner as [`Arg::default_value_if`]. - /// - /// The method takes a slice of tuples in the `(arg, predicate, default)` format. - /// - /// **NOTE**: The conditions are stored in order and evaluated in the same order. I.e. the first - /// if multiple conditions are true, the first one found will be applied and the ultimate value. - /// - /// Like with command-line values, this will be split by [`Arg::value_delimiter`]. - /// - /// # Examples - /// - /// First we use the default value only if another arg is present at runtime. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("opt") - /// .long("opt") - /// .action(ArgAction::Set)) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_ifs([ - /// ("flag", "true", Some("default")), - /// ("opt", "channal", Some("chan")), - /// ])) - /// .get_matches_from(vec![ - /// "prog", "--opt", "channal" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("other").unwrap(), "chan"); - /// ``` - /// - /// Next we run the same test, but without providing `--flag`. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_ifs([ - /// ("flag", "true", Some("default")), - /// ("opt", "channal", Some("chan")), - /// ])) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("other"), None); - /// ``` - /// - /// We can also see that these values are applied in order, and if more than one condition is - /// true, only the first evaluated "wins" - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// # use clap::builder::ArgPredicate; - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("opt") - /// .long("opt") - /// .action(ArgAction::Set)) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_ifs([ - /// ("flag", ArgPredicate::IsPresent, Some("default")), - /// ("opt", ArgPredicate::Equals("channal".into()), Some("chan")), - /// ])) - /// .get_matches_from(vec![ - /// "prog", "--opt", "channal", "--flag" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("other").unwrap(), "default"); - /// ``` - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - /// [`Arg::default_value_if`]: Arg::default_value_if() - #[must_use] - pub fn default_value_ifs( - mut self, - ifs: impl IntoIterator< - Item = ( - impl Into<Id>, - impl Into<ArgPredicate>, - impl IntoResettable<OsStr>, - ), - >, - ) -> Self { - for (arg, predicate, default) in ifs { - self = self.default_value_if(arg, predicate, default); - } - self - } - - #[must_use] - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value_ifs`") - )] - pub fn default_value_ifs_os( - self, - ifs: impl IntoIterator< - Item = ( - impl Into<Id>, - impl Into<ArgPredicate>, - impl IntoResettable<OsStr>, - ), - >, - ) -> Self { - self.default_value_ifs(ifs) - } - - /// Set this arg as [required] as long as the specified argument is not present at runtime. - /// - /// **Pro Tip:** Using `Arg::required_unless_present` implies [`Arg::required`] and is therefore not - /// mandatory to also set. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Arg; - /// Arg::new("config") - /// .required_unless_present("debug") - /// # ; - /// ``` - /// - /// In the following example, the required argument is *not* provided, - /// but it's not an error because the `unless` arg has been supplied. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_unless_present("dbg") - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("dbg") - /// .long("debug") - /// .action(ArgAction::SetTrue)) - /// .try_get_matches_from(vec![ - /// "prog", "--debug" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting `Arg::required_unless_present(name)` and *not* supplying `name` or this arg is an error. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_unless_present("dbg") - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("dbg") - /// .long("debug")) - /// .try_get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [required]: Arg::required() - #[must_use] - pub fn required_unless_present(mut self, arg_id: impl IntoResettable<Id>) -> Self { - if let Some(arg_id) = arg_id.into_resettable().into_option() { - self.r_unless.push(arg_id); - } else { - self.r_unless.clear(); - } - self - } - - /// Sets this arg as [required] unless *all* of the specified arguments are present at runtime. - /// - /// In other words, parsing will succeed only if user either - /// * supplies the `self` arg. - /// * supplies *all* of the `names` arguments. - /// - /// **NOTE:** If you wish for this argument to only be required unless *any of* these args are - /// present see [`Arg::required_unless_present_any`] - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Arg; - /// Arg::new("config") - /// .required_unless_present_all(["cfg", "dbg"]) - /// # ; - /// ``` - /// - /// In the following example, the required argument is *not* provided, but it's not an error - /// because *all* of the `names` args have been supplied. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_unless_present_all(["dbg", "infile"]) - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("dbg") - /// .long("debug") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("infile") - /// .short('i') - /// .action(ArgAction::Set)) - /// .try_get_matches_from(vec![ - /// "prog", "--debug", "-i", "file" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting [`Arg::required_unless_present_all(names)`] and *not* supplying - /// either *all* of `unless` args or the `self` arg is an error. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_unless_present_all(["dbg", "infile"]) - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("dbg") - /// .long("debug") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("infile") - /// .short('i') - /// .action(ArgAction::Set)) - /// .try_get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [required]: Arg::required() - /// [`Arg::required_unless_present_any`]: Arg::required_unless_present_any() - /// [`Arg::required_unless_present_all(names)`]: Arg::required_unless_present_all() - #[must_use] - pub fn required_unless_present_all( - mut self, - names: impl IntoIterator<Item = impl Into<Id>>, - ) -> Self { - self.r_unless_all.extend(names.into_iter().map(Into::into)); - self - } - - /// Sets this arg as [required] unless *any* of the specified arguments are present at runtime. - /// - /// In other words, parsing will succeed only if user either - /// * supplies the `self` arg. - /// * supplies *one or more* of the `unless` arguments. - /// - /// **NOTE:** If you wish for this argument to be required unless *all of* these args are - /// present see [`Arg::required_unless_present_all`] - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Arg; - /// Arg::new("config") - /// .required_unless_present_any(["cfg", "dbg"]) - /// # ; - /// ``` - /// - /// Setting [`Arg::required_unless_present_any(names)`] requires that the argument be used at runtime - /// *unless* *at least one of* the args in `names` are present. In the following example, the - /// required argument is *not* provided, but it's not an error because one the `unless` args - /// have been supplied. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_unless_present_any(["dbg", "infile"]) - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("dbg") - /// .long("debug") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("infile") - /// .short('i') - /// .action(ArgAction::Set)) - /// .try_get_matches_from(vec![ - /// "prog", "--debug" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting [`Arg::required_unless_present_any(names)`] and *not* supplying *at least one of* `names` - /// or this arg is an error. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_unless_present_any(["dbg", "infile"]) - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("dbg") - /// .long("debug") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("infile") - /// .short('i') - /// .action(ArgAction::Set)) - /// .try_get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [required]: Arg::required() - /// [`Arg::required_unless_present_any(names)`]: Arg::required_unless_present_any() - /// [`Arg::required_unless_present_all`]: Arg::required_unless_present_all() - #[must_use] - pub fn required_unless_present_any( - mut self, - names: impl IntoIterator<Item = impl Into<Id>>, - ) -> Self { - self.r_unless.extend(names.into_iter().map(Into::into)); - self - } - - /// This argument is [required] only if the specified `arg` is present at runtime and its value - /// equals `val`. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Arg; - /// Arg::new("config") - /// .required_if_eq("other_arg", "value") - /// # ; - /// ``` - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .required_if_eq("other", "special") - /// .long("config")) - /// .arg(Arg::new("other") - /// .long("other") - /// .action(ArgAction::Set)) - /// .try_get_matches_from(vec![ - /// "prog", "--other", "not-special" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required - /// - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .required_if_eq("other", "special") - /// .long("config")) - /// .arg(Arg::new("other") - /// .long("other") - /// .action(ArgAction::Set)) - /// .try_get_matches_from(vec![ - /// "prog", "--other", "special" - /// ]); - /// - /// // We did use --other=special so "cfg" had become required but was missing. - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .required_if_eq("other", "special") - /// .long("config")) - /// .arg(Arg::new("other") - /// .long("other") - /// .action(ArgAction::Set)) - /// .try_get_matches_from(vec![ - /// "prog", "--other", "SPECIAL" - /// ]); - /// - /// // By default, the comparison is case-sensitive, so "cfg" wasn't required - /// assert!(res.is_ok()); - /// - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .required_if_eq("other", "special") - /// .long("config")) - /// .arg(Arg::new("other") - /// .long("other") - /// .ignore_case(true) - /// .action(ArgAction::Set)) - /// .try_get_matches_from(vec![ - /// "prog", "--other", "SPECIAL" - /// ]); - /// - /// // However, case-insensitive comparisons can be enabled. This typically occurs when using Arg::possible_values(). - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: Arg::requires() - /// [Conflicting]: Arg::conflicts_with() - /// [required]: Arg::required() - #[must_use] - pub fn required_if_eq(mut self, arg_id: impl Into<Id>, val: impl Into<OsStr>) -> Self { - self.r_ifs.push((arg_id.into(), val.into())); - self - } - - /// Specify this argument is [required] based on multiple conditions. - /// - /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become - /// valid if one of the specified `arg`'s value equals its corresponding `val`. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Arg; - /// Arg::new("config") - /// .required_if_eq_any([ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// # ; - /// ``` - /// - /// Setting `Arg::required_if_eq_any([(arg, val)])` makes this arg required if any of the `arg`s - /// are used at runtime and it's corresponding value is equal to `val`. If the `arg`'s value is - /// anything other than `val`, this argument isn't required. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_if_eq_any([ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("extra") - /// .action(ArgAction::Set) - /// .long("extra")) - /// .arg(Arg::new("option") - /// .action(ArgAction::Set) - /// .long("option")) - /// .try_get_matches_from(vec![ - /// "prog", "--option", "other" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required - /// ``` - /// - /// Setting `Arg::required_if_eq_any([(arg, val)])` and having any of the `arg`s used with its - /// value of `val` but *not* using this arg is an error. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_if_eq_any([ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("extra") - /// .action(ArgAction::Set) - /// .long("extra")) - /// .arg(Arg::new("option") - /// .action(ArgAction::Set) - /// .long("option")) - /// .try_get_matches_from(vec![ - /// "prog", "--option", "spec" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: Arg::requires() - /// [Conflicting]: Arg::conflicts_with() - /// [required]: Arg::required() - #[must_use] - pub fn required_if_eq_any( - mut self, - ifs: impl IntoIterator<Item = (impl Into<Id>, impl Into<OsStr>)>, - ) -> Self { - self.r_ifs - .extend(ifs.into_iter().map(|(id, val)| (id.into(), val.into()))); - self - } - - /// Specify this argument is [required] based on multiple conditions. - /// - /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become - /// valid if every one of the specified `arg`'s value equals its corresponding `val`. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Arg; - /// Arg::new("config") - /// .required_if_eq_all([ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// # ; - /// ``` - /// - /// Setting `Arg::required_if_eq_all([(arg, val)])` makes this arg required if all of the `arg`s - /// are used at runtime and every value is equal to its corresponding `val`. If the `arg`'s value is - /// anything other than `val`, this argument isn't required. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_if_eq_all([ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("extra") - /// .action(ArgAction::Set) - /// .long("extra")) - /// .arg(Arg::new("option") - /// .action(ArgAction::Set) - /// .long("option")) - /// .try_get_matches_from(vec![ - /// "prog", "--option", "spec" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use --option=spec --extra=val so "cfg" isn't required - /// ``` - /// - /// Setting `Arg::required_if_eq_all([(arg, val)])` and having all of the `arg`s used with its - /// value of `val` but *not* using this arg is an error. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_if_eq_all([ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("extra") - /// .action(ArgAction::Set) - /// .long("extra")) - /// .arg(Arg::new("option") - /// .action(ArgAction::Set) - /// .long("option")) - /// .try_get_matches_from(vec![ - /// "prog", "--extra", "val", "--option", "spec" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [required]: Arg::required() - #[must_use] - pub fn required_if_eq_all( - mut self, - ifs: impl IntoIterator<Item = (impl Into<Id>, impl Into<OsStr>)>, - ) -> Self { - self.r_ifs_all - .extend(ifs.into_iter().map(|(id, val)| (id.into(), val.into()))); - self - } - - /// Require another argument if this arg matches the [`ArgPredicate`] - /// - /// This method takes `value, another_arg` pair. At runtime, clap will check - /// if this arg (`self`) matches the [`ArgPredicate`]. - /// If it does, `another_arg` will be marked as required. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Arg; - /// Arg::new("config") - /// .requires_if("val", "arg") - /// # ; - /// ``` - /// - /// Setting `Arg::requires_if(val, arg)` requires that the `arg` be used at runtime if the - /// defining argument's value is equal to `val`. If the defining argument is anything other than - /// `val`, the other argument isn't required. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .requires_if("my.cfg", "other") - /// .long("config")) - /// .arg(Arg::new("other")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "some.cfg" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required - /// ``` - /// - /// Setting `Arg::requires_if(val, arg)` and setting the value to `val` but *not* supplying - /// `arg` is an error. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .requires_if("my.cfg", "input") - /// .long("config")) - /// .arg(Arg::new("input")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "my.cfg" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: Arg::requires() - /// [Conflicting]: Arg::conflicts_with() - /// [override]: Arg::overrides_with() - #[must_use] - pub fn requires_if(mut self, val: impl Into<ArgPredicate>, arg_id: impl Into<Id>) -> Self { - self.requires.push((val.into(), arg_id.into())); - self - } - - /// Allows multiple conditional requirements. - /// - /// The requirement will only become valid if this arg's value matches the - /// [`ArgPredicate`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Arg; - /// Arg::new("config") - /// .requires_ifs([ - /// ("val", "arg"), - /// ("other_val", "arg2"), - /// ]) - /// # ; - /// ``` - /// - /// Setting `Arg::requires_ifs(["val", "arg"])` requires that the `arg` be used at runtime if the - /// defining argument's value is equal to `val`. If the defining argument's value is anything other - /// than `val`, `arg` isn't required. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .requires_ifs([ - /// ("special.conf", "opt"), - /// ("other.conf", "other"), - /// ]) - /// .long("config")) - /// .arg(Arg::new("opt") - /// .long("option") - /// .action(ArgAction::Set)) - /// .arg(Arg::new("other")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "special.conf" - /// ]); - /// - /// assert!(res.is_err()); // We used --config=special.conf so --option <val> is required - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// - /// Setting `Arg::requires_ifs` with [`ArgPredicate::IsPresent`] and *not* supplying all the - /// arguments is an error. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction, builder::ArgPredicate}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .requires_ifs([ - /// (ArgPredicate::IsPresent, "input"), - /// (ArgPredicate::IsPresent, "output"), - /// ]) - /// .long("config")) - /// .arg(Arg::new("input")) - /// .arg(Arg::new("output")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "file.conf", "in.txt" - /// ]); - /// - /// assert!(res.is_err()); - /// // We didn't use output - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// - /// [`Arg::requires(name)`]: Arg::requires() - /// [Conflicting]: Arg::conflicts_with() - /// [override]: Arg::overrides_with() - #[must_use] - pub fn requires_ifs( - mut self, - ifs: impl IntoIterator<Item = (impl Into<ArgPredicate>, impl Into<Id>)>, - ) -> Self { - self.requires - .extend(ifs.into_iter().map(|(val, arg)| (val.into(), arg.into()))); - self - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::requires_ifs`") - )] - pub fn requires_all(self, ids: impl IntoIterator<Item = impl Into<Id>>) -> Self { - self.requires_ifs(ids.into_iter().map(|id| (ArgPredicate::IsPresent, id))) - } - - /// This argument is mutually exclusive with the specified argument. - /// - /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules - /// only need to be set for one of the two arguments, they do not need to be set for each. - /// - /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments - /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not - /// need to also do B.conflicts_with(A)) - /// - /// **NOTE:** [`Arg::conflicts_with_all(names)`] allows specifying an argument which conflicts with more than one argument. - /// - /// **NOTE** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument. - /// - /// **NOTE:** All arguments implicitly conflict with themselves. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Arg; - /// Arg::new("config") - /// .conflicts_with("debug") - /// # ; - /// ``` - /// - /// Setting conflicting argument, and having both arguments present at runtime is an error. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .conflicts_with("debug") - /// .long("config")) - /// .arg(Arg::new("debug") - /// .long("debug") - /// .action(ArgAction::SetTrue)) - /// .try_get_matches_from(vec![ - /// "prog", "--debug", "--config", "file.conf" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); - /// ``` - /// - /// [`Arg::conflicts_with_all(names)`]: Arg::conflicts_with_all() - /// [`Arg::exclusive(true)`]: Arg::exclusive() - #[must_use] - pub fn conflicts_with(mut self, arg_id: impl IntoResettable<Id>) -> Self { - if let Some(arg_id) = arg_id.into_resettable().into_option() { - self.blacklist.push(arg_id); - } else { - self.blacklist.clear(); - } - self - } - - /// This argument is mutually exclusive with the specified arguments. - /// - /// See [`Arg::conflicts_with`]. - /// - /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules - /// only need to be set for one of the two arguments, they do not need to be set for each. - /// - /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments - /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need - /// need to also do B.conflicts_with(A)) - /// - /// **NOTE:** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Arg; - /// Arg::new("config") - /// .conflicts_with_all(["debug", "input"]) - /// # ; - /// ``` - /// - /// Setting conflicting argument, and having any of the arguments present at runtime with a - /// conflicting argument is an error. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .conflicts_with_all(["debug", "input"]) - /// .long("config")) - /// .arg(Arg::new("debug") - /// .long("debug")) - /// .arg(Arg::new("input")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "file.conf", "file.txt" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); - /// ``` - /// [`Arg::conflicts_with`]: Arg::conflicts_with() - /// [`Arg::exclusive(true)`]: Arg::exclusive() - #[must_use] - pub fn conflicts_with_all(mut self, names: impl IntoIterator<Item = impl Into<Id>>) -> Self { - self.blacklist.extend(names.into_iter().map(Into::into)); - self - } - - /// Sets an overridable argument. - /// - /// i.e. this argument and the following argument - /// will override each other in POSIX style (whichever argument was specified at runtime - /// **last** "wins") - /// - /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any - /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed - /// - /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, arg}; - /// let m = Command::new("prog") - /// .arg(arg!(-f --flag "some flag") - /// .conflicts_with("debug")) - /// .arg(arg!(-d --debug "other flag")) - /// .arg(arg!(-c --color "third flag") - /// .overrides_with("flag")) - /// .get_matches_from(vec![ - /// "prog", "-f", "-d", "-c"]); - /// // ^~~~~~~~~~~~^~~~~ flag is overridden by color - /// - /// assert!(m.get_flag("color")); - /// assert!(m.get_flag("debug")); // even though flag conflicts with debug, it's as if flag - /// // was never used because it was overridden with color - /// assert!(!m.get_flag("flag")); - /// ``` - #[must_use] - pub fn overrides_with(mut self, arg_id: impl IntoResettable<Id>) -> Self { - if let Some(arg_id) = arg_id.into_resettable().into_option() { - self.overrides.push(arg_id); - } else { - self.overrides.clear(); - } - self - } - - /// Sets multiple mutually overridable arguments by name. - /// - /// i.e. this argument and the following argument will override each other in POSIX style - /// (whichever argument was specified at runtime **last** "wins") - /// - /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any - /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed - /// - /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with_all`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, arg}; - /// let m = Command::new("prog") - /// .arg(arg!(-f --flag "some flag") - /// .conflicts_with("color")) - /// .arg(arg!(-d --debug "other flag")) - /// .arg(arg!(-c --color "third flag") - /// .overrides_with_all(["flag", "debug"])) - /// .get_matches_from(vec![ - /// "prog", "-f", "-d", "-c"]); - /// // ^~~~~~^~~~~~~~~ flag and debug are overridden by color - /// - /// assert!(m.get_flag("color")); // even though flag conflicts with color, it's as if flag - /// // and debug were never used because they were overridden - /// // with color - /// assert!(!m.get_flag("debug")); - /// assert!(!m.get_flag("flag")); - /// ``` - #[must_use] - pub fn overrides_with_all(mut self, names: impl IntoIterator<Item = impl Into<Id>>) -> Self { - self.overrides.extend(names.into_iter().map(Into::into)); - self - } -} - -/// # Reflection -impl Arg { - /// Get the name of the argument - #[inline] - pub fn get_id(&self) -> &Id { - &self.id - } - - /// Get the help specified for this argument, if any - #[inline] - pub fn get_help(&self) -> Option<&StyledStr> { - self.help.as_ref() - } - - /// Get the long help specified for this argument, if any - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Arg; - /// let arg = Arg::new("foo").long_help("long help"); - /// assert_eq!(Some("long help".to_owned()), arg.get_long_help().map(|s| s.to_string())); - /// ``` - /// - #[inline] - pub fn get_long_help(&self) -> Option<&StyledStr> { - self.long_help.as_ref() - } - - /// Get the help heading specified for this argument, if any - #[inline] - pub fn get_help_heading(&self) -> Option<&str> { - self.help_heading - .as_ref() - .map(|s| s.as_deref()) - .unwrap_or_default() - } - - /// Get the short option name for this argument, if any - #[inline] - pub fn get_short(&self) -> Option<char> { - self.short - } - - /// Get visible short aliases for this argument, if any - #[inline] - pub fn get_visible_short_aliases(&self) -> Option<Vec<char>> { - if self.short_aliases.is_empty() { - None - } else { - Some( - self.short_aliases - .iter() - .filter_map(|(c, v)| if *v { Some(c) } else { None }) - .copied() - .collect(), - ) - } - } - - /// Get *all* short aliases for this argument, if any, both visible and hidden. - #[inline] - pub fn get_all_short_aliases(&self) -> Option<Vec<char>> { - if self.short_aliases.is_empty() { - None - } else { - Some(self.short_aliases.iter().map(|(s, _)| s).copied().collect()) - } - } - - /// Get the short option name and its visible aliases, if any - #[inline] - pub fn get_short_and_visible_aliases(&self) -> Option<Vec<char>> { - let mut shorts = match self.short { - Some(short) => vec![short], - None => return None, - }; - if let Some(aliases) = self.get_visible_short_aliases() { - shorts.extend(aliases); - } - Some(shorts) - } - - /// Get the long option name for this argument, if any - #[inline] - pub fn get_long(&self) -> Option<&str> { - self.long.as_deref() - } - - /// Get visible aliases for this argument, if any - #[inline] - pub fn get_visible_aliases(&self) -> Option<Vec<&str>> { - if self.aliases.is_empty() { - None - } else { - Some( - self.aliases - .iter() - .filter_map(|(s, v)| if *v { Some(s.as_str()) } else { None }) - .collect(), - ) - } - } - - /// Get *all* aliases for this argument, if any, both visible and hidden. - #[inline] - pub fn get_all_aliases(&self) -> Option<Vec<&str>> { - if self.aliases.is_empty() { - None - } else { - Some(self.aliases.iter().map(|(s, _)| s.as_str()).collect()) - } - } - - /// Get the long option name and its visible aliases, if any - #[inline] - pub fn get_long_and_visible_aliases(&self) -> Option<Vec<&str>> { - let mut longs = match self.get_long() { - Some(long) => vec![long], - None => return None, - }; - if let Some(aliases) = self.get_visible_aliases() { - longs.extend(aliases); - } - Some(longs) - } - - /// Get the names of possible values for this argument. Only useful for user - /// facing applications, such as building help messages or man files - pub fn get_possible_values(&self) -> Vec<PossibleValue> { - if !self.is_takes_value_set() { - vec![] - } else { - self.get_value_parser() - .possible_values() - .map(|pvs| pvs.collect()) - .unwrap_or_default() - } - } - - /// Get the names of values for this argument. - #[inline] - pub fn get_value_names(&self) -> Option<&[Str]> { - if self.val_names.is_empty() { - None - } else { - Some(&self.val_names) - } - } - - /// Get the number of values for this argument. - #[inline] - pub fn get_num_args(&self) -> Option<ValueRange> { - self.num_vals - } - - #[inline] - pub(crate) fn get_min_vals(&self) -> usize { - self.get_num_args().expect(INTERNAL_ERROR_MSG).min_values() - } - - /// Get the delimiter between multiple values - #[inline] - pub fn get_value_delimiter(&self) -> Option<char> { - self.val_delim - } - - /// Get the value terminator for this argument. The value_terminator is a value - /// that terminates parsing of multi-valued arguments. - #[inline] - pub fn get_value_terminator(&self) -> Option<&Str> { - self.terminator.as_ref() - } - - /// Get the index of this argument, if any - #[inline] - pub fn get_index(&self) -> Option<usize> { - self.index - } - - /// Get the value hint of this argument - pub fn get_value_hint(&self) -> ValueHint { - self.value_hint.unwrap_or_else(|| { - if self.is_takes_value_set() { - let type_id = self.get_value_parser().type_id(); - if type_id == AnyValueId::of::<std::path::PathBuf>() { - ValueHint::AnyPath - } else { - ValueHint::default() - } - } else { - ValueHint::default() - } - }) - } - - /// Get the environment variable name specified for this argument, if any - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use std::ffi::OsStr; - /// # use clap::Arg; - /// let arg = Arg::new("foo").env("ENVIRONMENT"); - /// assert_eq!(arg.get_env(), Some(OsStr::new("ENVIRONMENT"))); - /// ``` - #[cfg(feature = "env")] - pub fn get_env(&self) -> Option<&std::ffi::OsStr> { - self.env.as_ref().map(|x| x.0.as_os_str()) - } - - /// Get the default values specified for this argument, if any - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Arg; - /// let arg = Arg::new("foo").default_value("default value"); - /// assert_eq!(arg.get_default_values(), &["default value"]); - /// ``` - pub fn get_default_values(&self) -> &[OsStr] { - &self.default_vals - } - - /// Checks whether this argument is a positional or not. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Arg; - /// let arg = Arg::new("foo"); - /// assert_eq!(arg.is_positional(), true); - /// - /// let arg = Arg::new("foo").long("foo"); - /// assert_eq!(arg.is_positional(), false); - /// ``` - pub fn is_positional(&self) -> bool { - self.get_long().is_none() && self.get_short().is_none() - } - - /// Reports whether [`Arg::required`] is set - pub fn is_required_set(&self) -> bool { - self.is_set(ArgSettings::Required) - } - - pub(crate) fn is_multiple_values_set(&self) -> bool { - self.get_num_args().unwrap_or_default().is_multiple() - } - - pub(crate) fn is_takes_value_set(&self) -> bool { - self.get_action().takes_values() - } - - /// Report whether [`Arg::allow_hyphen_values`] is set - pub fn is_allow_hyphen_values_set(&self) -> bool { - self.is_set(ArgSettings::AllowHyphenValues) - } - - /// Report whether [`Arg::allow_negative_numbers`] is set - pub fn is_allow_negative_numbers_set(&self) -> bool { - self.is_set(ArgSettings::AllowNegativeNumbers) - } - - /// Behavior when parsing the argument - pub fn get_action(&self) -> &super::ArgAction { - const DEFAULT: super::ArgAction = super::ArgAction::Set; - self.action.as_ref().unwrap_or(&DEFAULT) - } - - /// Configured parser for argument values - /// - /// # Example - /// - /// ```rust - /// # use clap_builder as clap; - /// let cmd = clap::Command::new("raw") - /// .arg( - /// clap::Arg::new("port") - /// .value_parser(clap::value_parser!(usize)) - /// ); - /// let value_parser = cmd.get_arguments() - /// .find(|a| a.get_id() == "port").unwrap() - /// .get_value_parser(); - /// println!("{value_parser:?}"); - /// ``` - pub fn get_value_parser(&self) -> &super::ValueParser { - if let Some(value_parser) = self.value_parser.as_ref() { - value_parser - } else { - static DEFAULT: super::ValueParser = super::ValueParser::string(); - &DEFAULT - } - } - - /// Report whether [`Arg::global`] is set - pub fn is_global_set(&self) -> bool { - self.is_set(ArgSettings::Global) - } - - /// Report whether [`Arg::next_line_help`] is set - pub fn is_next_line_help_set(&self) -> bool { - self.is_set(ArgSettings::NextLineHelp) - } - - /// Report whether [`Arg::hide`] is set - pub fn is_hide_set(&self) -> bool { - self.is_set(ArgSettings::Hidden) - } - - /// Report whether [`Arg::hide_default_value`] is set - pub fn is_hide_default_value_set(&self) -> bool { - self.is_set(ArgSettings::HideDefaultValue) - } - - /// Report whether [`Arg::hide_possible_values`] is set - pub fn is_hide_possible_values_set(&self) -> bool { - self.is_set(ArgSettings::HidePossibleValues) - } - - /// Report whether [`Arg::hide_env`] is set - #[cfg(feature = "env")] - pub fn is_hide_env_set(&self) -> bool { - self.is_set(ArgSettings::HideEnv) - } - - /// Report whether [`Arg::hide_env_values`] is set - #[cfg(feature = "env")] - pub fn is_hide_env_values_set(&self) -> bool { - self.is_set(ArgSettings::HideEnvValues) - } - - /// Report whether [`Arg::hide_short_help`] is set - pub fn is_hide_short_help_set(&self) -> bool { - self.is_set(ArgSettings::HiddenShortHelp) - } - - /// Report whether [`Arg::hide_long_help`] is set - pub fn is_hide_long_help_set(&self) -> bool { - self.is_set(ArgSettings::HiddenLongHelp) - } - - /// Report whether [`Arg::require_equals`] is set - pub fn is_require_equals_set(&self) -> bool { - self.is_set(ArgSettings::RequireEquals) - } - - /// Reports whether [`Arg::exclusive`] is set - pub fn is_exclusive_set(&self) -> bool { - self.is_set(ArgSettings::Exclusive) - } - - /// Report whether [`Arg::trailing_var_arg`] is set - pub fn is_trailing_var_arg_set(&self) -> bool { - self.is_set(ArgSettings::TrailingVarArg) - } - - /// Reports whether [`Arg::last`] is set - pub fn is_last_set(&self) -> bool { - self.is_set(ArgSettings::Last) - } - - /// Reports whether [`Arg::ignore_case`] is set - pub fn is_ignore_case_set(&self) -> bool { - self.is_set(ArgSettings::IgnoreCase) - } -} - -/// # Internally used only -impl Arg { - pub(crate) fn _build(&mut self) { - if self.action.is_none() { - if self.num_vals == Some(ValueRange::EMPTY) { - let action = super::ArgAction::SetTrue; - self.action = Some(action); - } else { - let action = - if self.is_positional() && self.num_vals.unwrap_or_default().is_unbounded() { - // Allow collecting arguments interleaved with flags - // - // Bounded values are probably a group and the user should explicitly opt-in to - // Append - super::ArgAction::Append - } else { - super::ArgAction::Set - }; - self.action = Some(action); - } - } - if let Some(action) = self.action.as_ref() { - if let Some(default_value) = action.default_value() { - if self.default_vals.is_empty() { - self.default_vals = vec![default_value.into()]; - } - } - if let Some(default_value) = action.default_missing_value() { - if self.default_missing_vals.is_empty() { - self.default_missing_vals = vec![default_value.into()]; - } - } - } - - if self.value_parser.is_none() { - if let Some(default) = self.action.as_ref().and_then(|a| a.default_value_parser()) { - self.value_parser = Some(default); - } else { - self.value_parser = Some(super::ValueParser::string()); - } - } - - let val_names_len = self.val_names.len(); - if val_names_len > 1 { - self.num_vals.get_or_insert(val_names_len.into()); - } else { - let nargs = if self.get_action().takes_values() { - ValueRange::SINGLE - } else { - ValueRange::EMPTY - }; - self.num_vals.get_or_insert(nargs); - } - } - - // Used for positionals when printing - pub(crate) fn name_no_brackets(&self) -> String { - debug!("Arg::name_no_brackets:{}", self.get_id()); - let delim = " "; - if !self.val_names.is_empty() { - debug!("Arg::name_no_brackets: val_names={:#?}", self.val_names); - - if self.val_names.len() > 1 { - self.val_names - .iter() - .map(|n| format!("<{n}>")) - .collect::<Vec<_>>() - .join(delim) - } else { - self.val_names - .first() - .expect(INTERNAL_ERROR_MSG) - .as_str() - .to_owned() - } - } else { - debug!("Arg::name_no_brackets: just name"); - self.get_id().as_str().to_owned() - } - } - - pub(crate) fn stylized(&self, styles: &Styles, required: Option<bool>) -> StyledStr { - use std::fmt::Write as _; - let literal = styles.get_literal(); - - let mut styled = StyledStr::new(); - // Write the name such --long or -l - if let Some(l) = self.get_long() { - let _ = write!( - styled, - "{}--{l}{}", - literal.render(), - literal.render_reset() - ); - } else if let Some(s) = self.get_short() { - let _ = write!(styled, "{}-{s}{}", literal.render(), literal.render_reset()); - } - styled.push_styled(&self.stylize_arg_suffix(styles, required)); - styled - } - - pub(crate) fn stylize_arg_suffix(&self, styles: &Styles, required: Option<bool>) -> StyledStr { - use std::fmt::Write as _; - let literal = styles.get_literal(); - let placeholder = styles.get_placeholder(); - let mut styled = StyledStr::new(); - - let mut need_closing_bracket = false; - if self.is_takes_value_set() && !self.is_positional() { - let is_optional_val = self.get_min_vals() == 0; - let (style, start) = if self.is_require_equals_set() { - if is_optional_val { - need_closing_bracket = true; - (placeholder, "[=") - } else { - (literal, "=") - } - } else if is_optional_val { - need_closing_bracket = true; - (placeholder, " [") - } else { - (placeholder, " ") - }; - let _ = write!(styled, "{}{start}{}", style.render(), style.render_reset()); - } - if self.is_takes_value_set() || self.is_positional() { - let required = required.unwrap_or_else(|| self.is_required_set()); - let arg_val = self.render_arg_val(required); - let _ = write!( - styled, - "{}{arg_val}{}", - placeholder.render(), - placeholder.render_reset() - ); - } else if matches!(*self.get_action(), ArgAction::Count) { - let _ = write!( - styled, - "{}...{}", - placeholder.render(), - placeholder.render_reset() - ); - } - if need_closing_bracket { - let _ = write!( - styled, - "{}]{}", - placeholder.render(), - placeholder.render_reset() - ); - } - - styled - } - - /// Write the values such as `<name1> <name2>` - fn render_arg_val(&self, required: bool) -> String { - let mut rendered = String::new(); - - let num_vals = self.get_num_args().unwrap_or_else(|| 1.into()); - - let mut val_names = if self.val_names.is_empty() { - vec![self.id.as_internal_str().to_owned()] - } else { - self.val_names.clone() - }; - if val_names.len() == 1 { - let min = num_vals.min_values().max(1); - let val_name = val_names.pop().unwrap(); - val_names = vec![val_name; min]; - } - - debug_assert!(self.is_takes_value_set()); - for (n, val_name) in val_names.iter().enumerate() { - let arg_name = if self.is_positional() && (num_vals.min_values() == 0 || !required) { - format!("[{val_name}]") - } else { - format!("<{val_name}>") - }; - - if n != 0 { - rendered.push(' '); - } - rendered.push_str(&arg_name); - } - - let mut extra_values = false; - extra_values |= val_names.len() < num_vals.max_values(); - if self.is_positional() && matches!(*self.get_action(), ArgAction::Append) { - extra_values = true; - } - if extra_values { - rendered.push_str("..."); - } - - rendered - } - - /// Either multiple values or occurrences - pub(crate) fn is_multiple(&self) -> bool { - self.is_multiple_values_set() || matches!(*self.get_action(), ArgAction::Append) - } - - #[cfg(feature = "help")] - pub(crate) fn get_display_order(&self) -> usize { - self.disp_ord.unwrap_or(999) - } -} - -impl From<&'_ Arg> for Arg { - fn from(a: &Arg) -> Self { - a.clone() - } -} - -impl PartialEq for Arg { - fn eq(&self, other: &Arg) -> bool { - self.get_id() == other.get_id() - } -} - -impl PartialOrd for Arg { - fn partial_cmp(&self, other: &Self) -> Option<Ordering> { - Some(self.cmp(other)) - } -} - -impl Ord for Arg { - fn cmp(&self, other: &Arg) -> Ordering { - self.get_id().cmp(other.get_id()) - } -} - -impl Eq for Arg {} - -impl Display for Arg { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - let plain = Styles::plain(); - self.stylized(&plain, None).fmt(f) - } -} - -impl fmt::Debug for Arg { - fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { - let mut ds = f.debug_struct("Arg"); - - #[allow(unused_mut)] - let mut ds = ds - .field("id", &self.id) - .field("help", &self.help) - .field("long_help", &self.long_help) - .field("action", &self.action) - .field("value_parser", &self.value_parser) - .field("blacklist", &self.blacklist) - .field("settings", &self.settings) - .field("overrides", &self.overrides) - .field("groups", &self.groups) - .field("requires", &self.requires) - .field("r_ifs", &self.r_ifs) - .field("r_unless", &self.r_unless) - .field("short", &self.short) - .field("long", &self.long) - .field("aliases", &self.aliases) - .field("short_aliases", &self.short_aliases) - .field("disp_ord", &self.disp_ord) - .field("val_names", &self.val_names) - .field("num_vals", &self.num_vals) - .field("val_delim", &self.val_delim) - .field("default_vals", &self.default_vals) - .field("default_vals_ifs", &self.default_vals_ifs) - .field("terminator", &self.terminator) - .field("index", &self.index) - .field("help_heading", &self.help_heading) - .field("value_hint", &self.value_hint) - .field("default_missing_vals", &self.default_missing_vals); - - #[cfg(feature = "env")] - { - ds = ds.field("env", &self.env); - } - - ds.finish() - } -} - -// Flags -#[cfg(test)] -mod test { - use super::Arg; - use super::ArgAction; - - #[test] - fn flag_display_long() { - let mut f = Arg::new("flg").long("flag").action(ArgAction::SetTrue); - f._build(); - - assert_eq!(f.to_string(), "--flag"); - } - - #[test] - fn flag_display_short() { - let mut f2 = Arg::new("flg").short('f').action(ArgAction::SetTrue); - f2._build(); - - assert_eq!(f2.to_string(), "-f"); - } - - #[test] - fn flag_display_count() { - let mut f2 = Arg::new("flg").long("flag").action(ArgAction::Count); - f2._build(); - - assert_eq!(f2.to_string(), "--flag..."); - } - - #[test] - fn flag_display_single_alias() { - let mut f = Arg::new("flg") - .long("flag") - .visible_alias("als") - .action(ArgAction::SetTrue); - f._build(); - - assert_eq!(f.to_string(), "--flag") - } - - #[test] - fn flag_display_multiple_aliases() { - let mut f = Arg::new("flg").short('f').action(ArgAction::SetTrue); - f.aliases = vec![ - ("alias_not_visible".into(), false), - ("f2".into(), true), - ("f3".into(), true), - ("f4".into(), true), - ]; - f._build(); - - assert_eq!(f.to_string(), "-f"); - } - - #[test] - fn flag_display_single_short_alias() { - let mut f = Arg::new("flg").short('a').action(ArgAction::SetTrue); - f.short_aliases = vec![('b', true)]; - f._build(); - - assert_eq!(f.to_string(), "-a") - } - - #[test] - fn flag_display_multiple_short_aliases() { - let mut f = Arg::new("flg").short('a').action(ArgAction::SetTrue); - f.short_aliases = vec![('b', false), ('c', true), ('d', true), ('e', true)]; - f._build(); - - assert_eq!(f.to_string(), "-a"); - } - - // Options - - #[test] - fn option_display_multiple_occurrences() { - let mut o = Arg::new("opt").long("option").action(ArgAction::Append); - o._build(); - - assert_eq!(o.to_string(), "--option <opt>"); - } - - #[test] - fn option_display_multiple_values() { - let mut o = Arg::new("opt") - .long("option") - .action(ArgAction::Set) - .num_args(1..); - o._build(); - - assert_eq!(o.to_string(), "--option <opt>..."); - } - - #[test] - fn option_display_zero_or_more_values() { - let mut o = Arg::new("opt") - .long("option") - .action(ArgAction::Set) - .num_args(0..); - o._build(); - - assert_eq!(o.to_string(), "--option [<opt>...]"); - } - - #[test] - fn option_display_one_or_more_values() { - let mut o = Arg::new("opt") - .long("option") - .action(ArgAction::Set) - .num_args(1..); - o._build(); - - assert_eq!(o.to_string(), "--option <opt>..."); - } - - #[test] - fn option_display_zero_or_more_values_with_value_name() { - let mut o = Arg::new("opt") - .short('o') - .action(ArgAction::Set) - .num_args(0..) - .value_names(["file"]); - o._build(); - - assert_eq!(o.to_string(), "-o [<file>...]"); - } - - #[test] - fn option_display_one_or_more_values_with_value_name() { - let mut o = Arg::new("opt") - .short('o') - .action(ArgAction::Set) - .num_args(1..) - .value_names(["file"]); - o._build(); - - assert_eq!(o.to_string(), "-o <file>..."); - } - - #[test] - fn option_display_optional_value() { - let mut o = Arg::new("opt") - .long("option") - .action(ArgAction::Set) - .num_args(0..=1); - o._build(); - - assert_eq!(o.to_string(), "--option [<opt>]"); - } - - #[test] - fn option_display_value_names() { - let mut o = Arg::new("opt") - .short('o') - .action(ArgAction::Set) - .value_names(["file", "name"]); - o._build(); - - assert_eq!(o.to_string(), "-o <file> <name>"); - } - - #[test] - fn option_display3() { - let mut o = Arg::new("opt") - .short('o') - .num_args(1..) - .action(ArgAction::Set) - .value_names(["file", "name"]); - o._build(); - - assert_eq!(o.to_string(), "-o <file> <name>..."); - } - - #[test] - fn option_display_single_alias() { - let mut o = Arg::new("opt") - .long("option") - .action(ArgAction::Set) - .visible_alias("als"); - o._build(); - - assert_eq!(o.to_string(), "--option <opt>"); - } - - #[test] - fn option_display_multiple_aliases() { - let mut o = Arg::new("opt") - .long("option") - .action(ArgAction::Set) - .visible_aliases(["als2", "als3", "als4"]) - .alias("als_not_visible"); - o._build(); - - assert_eq!(o.to_string(), "--option <opt>"); - } - - #[test] - fn option_display_single_short_alias() { - let mut o = Arg::new("opt") - .short('a') - .action(ArgAction::Set) - .visible_short_alias('b'); - o._build(); - - assert_eq!(o.to_string(), "-a <opt>"); - } - - #[test] - fn option_display_multiple_short_aliases() { - let mut o = Arg::new("opt") - .short('a') - .action(ArgAction::Set) - .visible_short_aliases(['b', 'c', 'd']) - .short_alias('e'); - o._build(); - - assert_eq!(o.to_string(), "-a <opt>"); - } - - // Positionals - - #[test] - fn positional_display_multiple_values() { - let mut p = Arg::new("pos").index(1).num_args(1..); - p._build(); - - assert_eq!(p.to_string(), "[pos]..."); - } - - #[test] - fn positional_display_multiple_values_required() { - let mut p = Arg::new("pos").index(1).num_args(1..).required(true); - p._build(); - - assert_eq!(p.to_string(), "<pos>..."); - } - - #[test] - fn positional_display_zero_or_more_values() { - let mut p = Arg::new("pos").index(1).num_args(0..); - p._build(); - - assert_eq!(p.to_string(), "[pos]..."); - } - - #[test] - fn positional_display_one_or_more_values() { - let mut p = Arg::new("pos").index(1).num_args(1..); - p._build(); - - assert_eq!(p.to_string(), "[pos]..."); - } - - #[test] - fn positional_display_one_or_more_values_required() { - let mut p = Arg::new("pos").index(1).num_args(1..).required(true); - p._build(); - - assert_eq!(p.to_string(), "<pos>..."); - } - - #[test] - fn positional_display_optional_value() { - let mut p = Arg::new("pos") - .index(1) - .num_args(0..=1) - .action(ArgAction::Set); - p._build(); - - assert_eq!(p.to_string(), "[pos]"); - } - - #[test] - fn positional_display_multiple_occurrences() { - let mut p = Arg::new("pos").index(1).action(ArgAction::Append); - p._build(); - - assert_eq!(p.to_string(), "[pos]..."); - } - - #[test] - fn positional_display_multiple_occurrences_required() { - let mut p = Arg::new("pos") - .index(1) - .action(ArgAction::Append) - .required(true); - p._build(); - - assert_eq!(p.to_string(), "<pos>..."); - } - - #[test] - fn positional_display_required() { - let mut p = Arg::new("pos").index(1).required(true); - p._build(); - - assert_eq!(p.to_string(), "<pos>"); - } - - #[test] - fn positional_display_val_names() { - let mut p = Arg::new("pos").index(1).value_names(["file1", "file2"]); - p._build(); - - assert_eq!(p.to_string(), "[file1] [file2]"); - } - - #[test] - fn positional_display_val_names_required() { - let mut p = Arg::new("pos") - .index(1) - .value_names(["file1", "file2"]) - .required(true); - p._build(); - - assert_eq!(p.to_string(), "<file1> <file2>"); - } -} diff --git a/vendor/clap_builder/src/builder/arg_group.rs b/vendor/clap_builder/src/builder/arg_group.rs deleted file mode 100644 index d3a37c1..0000000 --- a/vendor/clap_builder/src/builder/arg_group.rs +++ /dev/null @@ -1,611 +0,0 @@ -// Internal -use crate::builder::IntoResettable; -use crate::util::Id; - -/// Family of related [arguments]. -/// -/// By placing arguments in a logical group, you can create easier requirement and -/// exclusion rules instead of having to list each argument individually, or when you want a rule -/// to apply "any but not all" arguments. -/// -/// For instance, you can make an entire `ArgGroup` required. If [`ArgGroup::multiple(true)`] is -/// set, this means that at least one argument from that group must be present. If -/// [`ArgGroup::multiple(false)`] is set (the default), one and *only* one must be present. -/// -/// You can also do things such as name an entire `ArgGroup` as a [conflict] or [requirement] for -/// another argument, meaning any of the arguments that belong to that group will cause a failure -/// if present, or must be present respectively. -/// -/// Perhaps the most common use of `ArgGroup`s is to require one and *only* one argument to be -/// present out of a given set. Imagine that you had multiple arguments, and you want one of them -/// to be required, but making all of them required isn't feasible because perhaps they conflict -/// with each other. For example, lets say that you were building an application where one could -/// set a given version number by supplying a string with an option argument, i.e. -/// `--set-ver v1.2.3`, you also wanted to support automatically using a previous version number -/// and simply incrementing one of the three numbers. So you create three flags `--major`, -/// `--minor`, and `--patch`. All of these arguments shouldn't be used at one time but you want to -/// specify that *at least one* of them is used. For this, you can create a group. -/// -/// Finally, you may use `ArgGroup`s to pull a value from a group of arguments when you don't care -/// exactly which argument was actually used at runtime. -/// -/// # Examples -/// -/// The following example demonstrates using an `ArgGroup` to ensure that one, and only one, of -/// the arguments from the specified group is present at runtime. -/// -/// ```rust -/// # use clap_builder as clap; -/// # use clap::{Command, arg, ArgGroup, error::ErrorKind}; -/// let result = Command::new("cmd") -/// .arg(arg!(--"set-ver" <ver> "set the version manually")) -/// .arg(arg!(--major "auto increase major")) -/// .arg(arg!(--minor "auto increase minor")) -/// .arg(arg!(--patch "auto increase patch")) -/// .group(ArgGroup::new("vers") -/// .args(["set-ver", "major", "minor", "patch"]) -/// .required(true)) -/// .try_get_matches_from(vec!["cmd", "--major", "--patch"]); -/// // Because we used two args in the group it's an error -/// assert!(result.is_err()); -/// let err = result.unwrap_err(); -/// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); -/// ``` -/// -/// This next example shows a passing parse of the same scenario -/// ```rust -/// # use clap_builder as clap; -/// # use clap::{Command, arg, ArgGroup, Id}; -/// let result = Command::new("cmd") -/// .arg(arg!(--"set-ver" <ver> "set the version manually")) -/// .arg(arg!(--major "auto increase major")) -/// .arg(arg!(--minor "auto increase minor")) -/// .arg(arg!(--patch "auto increase patch")) -/// .group(ArgGroup::new("vers") -/// .args(["set-ver", "major", "minor","patch"]) -/// .required(true)) -/// .try_get_matches_from(vec!["cmd", "--major"]); -/// assert!(result.is_ok()); -/// let matches = result.unwrap(); -/// // We may not know which of the args was used, so we can test for the group... -/// assert!(matches.contains_id("vers")); -/// // We can also ask the group which arg was used -/// assert_eq!(matches -/// .get_one::<Id>("vers") -/// .expect("`vers` is required") -/// .as_str(), -/// "major" -/// ); -/// // we could also alternatively check each arg individually (not shown here) -/// ``` -/// [`ArgGroup::multiple(true)`]: ArgGroup::multiple() -/// -/// [`ArgGroup::multiple(false)`]: ArgGroup::multiple() -/// [arguments]: crate::Arg -/// [conflict]: crate::Arg::conflicts_with() -/// [requirement]: crate::Arg::requires() -#[derive(Default, Clone, Debug, PartialEq, Eq)] -pub struct ArgGroup { - pub(crate) id: Id, - pub(crate) args: Vec<Id>, - pub(crate) required: bool, - pub(crate) requires: Vec<Id>, - pub(crate) conflicts: Vec<Id>, - pub(crate) multiple: bool, -} - -/// # Builder -impl ArgGroup { - /// Create a `ArgGroup` using a unique name. - /// - /// The name will be used to get values from the group or refer to the group inside of conflict - /// and requirement rules. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, ArgGroup}; - /// ArgGroup::new("config") - /// # ; - /// ``` - pub fn new(id: impl Into<Id>) -> Self { - ArgGroup::default().id(id) - } - - /// Sets the group name. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, ArgGroup}; - /// ArgGroup::default().id("config") - /// # ; - /// ``` - #[must_use] - pub fn id(mut self, id: impl Into<Id>) -> Self { - self.id = id.into(); - self - } - - /// Adds an [argument] to this group by name - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgGroup, ArgAction}; - /// let m = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("color") - /// .short('c') - /// .action(ArgAction::SetTrue)) - /// .group(ArgGroup::new("req_flags") - /// .arg("flag") - /// .arg("color")) - /// .get_matches_from(vec!["myprog", "-f"]); - /// // maybe we don't know which of the two flags was used... - /// assert!(m.contains_id("req_flags")); - /// // but we can also check individually if needed - /// assert!(m.contains_id("flag")); - /// ``` - /// [argument]: crate::Arg - #[must_use] - pub fn arg(mut self, arg_id: impl IntoResettable<Id>) -> Self { - if let Some(arg_id) = arg_id.into_resettable().into_option() { - self.args.push(arg_id); - } else { - self.args.clear(); - } - self - } - - /// Adds multiple [arguments] to this group by name - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgGroup, ArgAction}; - /// let m = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("color") - /// .short('c') - /// .action(ArgAction::SetTrue)) - /// .group(ArgGroup::new("req_flags") - /// .args(["flag", "color"])) - /// .get_matches_from(vec!["myprog", "-f"]); - /// // maybe we don't know which of the two flags was used... - /// assert!(m.contains_id("req_flags")); - /// // but we can also check individually if needed - /// assert!(m.contains_id("flag")); - /// ``` - /// [arguments]: crate::Arg - #[must_use] - pub fn args(mut self, ns: impl IntoIterator<Item = impl Into<Id>>) -> Self { - for n in ns { - self = self.arg(n); - } - self - } - - /// Getters for all args. It will return a vector of `Id` - /// - /// # Example - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{ArgGroup}; - /// let args: Vec<&str> = vec!["a1".into(), "a4".into()]; - /// let grp = ArgGroup::new("program").args(&args); - /// - /// for (pos, arg) in grp.get_args().enumerate() { - /// assert_eq!(*arg, args[pos]); - /// } - /// ``` - pub fn get_args(&self) -> impl Iterator<Item = &Id> { - self.args.iter() - } - - /// Allows more than one of the [`Arg`]s in this group to be used. (Default: `false`) - /// - /// # Examples - /// - /// Notice in this example we use *both* the `-f` and `-c` flags which are both part of the - /// group - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgGroup, ArgAction}; - /// let m = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("color") - /// .short('c') - /// .action(ArgAction::SetTrue)) - /// .group(ArgGroup::new("req_flags") - /// .args(["flag", "color"]) - /// .multiple(true)) - /// .get_matches_from(vec!["myprog", "-f", "-c"]); - /// // maybe we don't know which of the two flags was used... - /// assert!(m.contains_id("req_flags")); - /// ``` - /// In this next example, we show the default behavior (i.e. `multiple(false)) which will throw - /// an error if more than one of the args in the group was used. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; - /// let result = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("color") - /// .short('c') - /// .action(ArgAction::SetTrue)) - /// .group(ArgGroup::new("req_flags") - /// .args(["flag", "color"])) - /// .try_get_matches_from(vec!["myprog", "-f", "-c"]); - /// // Because we used both args in the group it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); - /// ``` - /// - /// [`Arg`]: crate::Arg - #[inline] - #[must_use] - pub fn multiple(mut self, yes: bool) -> Self { - self.multiple = yes; - self - } - - /// Return true if the group allows more than one of the arguments - /// in this group to be used. (Default: `false`) - /// - /// # Example - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{ArgGroup}; - /// let mut group = ArgGroup::new("myprog") - /// .args(["f", "c"]) - /// .multiple(true); - /// - /// assert!(group.is_multiple()); - /// ``` - pub fn is_multiple(&mut self) -> bool { - self.multiple - } - - /// Require an argument from the group to be present when parsing. - /// - /// This is unless conflicting with another argument. A required group will be displayed in - /// the usage string of the application in the format `<arg|arg2|arg3>`. - /// - /// **NOTE:** This setting only applies to the current [`Command`] / [`Subcommand`]s, and not - /// globally. - /// - /// **NOTE:** By default, [`ArgGroup::multiple`] is set to `false` which when combined with - /// `ArgGroup::required(true)` states, "One and *only one* arg must be used from this group. - /// Use of more than one arg is an error." Vice setting `ArgGroup::multiple(true)` which - /// states, '*At least* one arg from this group must be used. Using multiple is OK." - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; - /// let result = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("color") - /// .short('c') - /// .action(ArgAction::SetTrue)) - /// .group(ArgGroup::new("req_flags") - /// .args(["flag", "color"]) - /// .required(true)) - /// .try_get_matches_from(vec!["myprog"]); - /// // Because we didn't use any of the args in the group, it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// - /// [`Subcommand`]: crate::Subcommand - /// [`ArgGroup::multiple`]: ArgGroup::multiple() - /// [`Command`]: crate::Command - #[inline] - #[must_use] - pub fn required(mut self, yes: bool) -> Self { - self.required = yes; - self - } - - /// Specify an argument or group that must be present when this group is. - /// - /// This is not to be confused with a [required group]. Requirement rules function just like - /// [argument requirement rules], you can name other arguments or groups that must be present - /// when any one of the arguments from this group is used. - /// - /// **NOTE:** The name provided may be an argument or group name - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; - /// let result = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("color") - /// .short('c') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("debug") - /// .short('d') - /// .action(ArgAction::SetTrue)) - /// .group(ArgGroup::new("req_flags") - /// .args(["flag", "color"]) - /// .requires("debug")) - /// .try_get_matches_from(vec!["myprog", "-c"]); - /// // because we used an arg from the group, and the group requires "-d" to be used, it's an - /// // error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [required group]: ArgGroup::required() - /// [argument requirement rules]: crate::Arg::requires() - #[must_use] - pub fn requires(mut self, id: impl IntoResettable<Id>) -> Self { - if let Some(id) = id.into_resettable().into_option() { - self.requires.push(id); - } else { - self.requires.clear(); - } - self - } - - /// Specify arguments or groups that must be present when this group is. - /// - /// This is not to be confused with a [required group]. Requirement rules function just like - /// [argument requirement rules], you can name other arguments or groups that must be present - /// when one of the arguments from this group is used. - /// - /// **NOTE:** The names provided may be an argument or group name - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; - /// let result = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("color") - /// .short('c') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("debug") - /// .short('d') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("verb") - /// .short('v') - /// .action(ArgAction::SetTrue)) - /// .group(ArgGroup::new("req_flags") - /// .args(["flag", "color"]) - /// .requires_all(["debug", "verb"])) - /// .try_get_matches_from(vec!["myprog", "-c", "-d"]); - /// // because we used an arg from the group, and the group requires "-d" and "-v" to be used, - /// // yet we only used "-d" it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [required group]: ArgGroup::required() - /// [argument requirement rules]: crate::Arg::requires_ifs() - #[must_use] - pub fn requires_all(mut self, ns: impl IntoIterator<Item = impl Into<Id>>) -> Self { - for n in ns { - self = self.requires(n); - } - self - } - - /// Specify an argument or group that must **not** be present when this group is. - /// - /// Exclusion (aka conflict) rules function just like [argument exclusion rules], you can name - /// other arguments or groups that must *not* be present when one of the arguments from this - /// group are used. - /// - /// **NOTE:** The name provided may be an argument, or group name - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; - /// let result = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("color") - /// .short('c') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("debug") - /// .short('d') - /// .action(ArgAction::SetTrue)) - /// .group(ArgGroup::new("req_flags") - /// .args(["flag", "color"]) - /// .conflicts_with("debug")) - /// .try_get_matches_from(vec!["myprog", "-c", "-d"]); - /// // because we used an arg from the group, and the group conflicts with "-d", it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); - /// ``` - /// [argument exclusion rules]: crate::Arg::conflicts_with() - #[must_use] - pub fn conflicts_with(mut self, id: impl IntoResettable<Id>) -> Self { - if let Some(id) = id.into_resettable().into_option() { - self.conflicts.push(id); - } else { - self.conflicts.clear(); - } - self - } - - /// Specify arguments or groups that must **not** be present when this group is. - /// - /// Exclusion rules function just like [argument exclusion rules], you can name other arguments - /// or groups that must *not* be present when one of the arguments from this group are used. - /// - /// **NOTE:** The names provided may be an argument, or group name - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; - /// let result = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("color") - /// .short('c') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("debug") - /// .short('d') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("verb") - /// .short('v') - /// .action(ArgAction::SetTrue)) - /// .group(ArgGroup::new("req_flags") - /// .args(["flag", "color"]) - /// .conflicts_with_all(["debug", "verb"])) - /// .try_get_matches_from(vec!["myprog", "-c", "-v"]); - /// // because we used an arg from the group, and the group conflicts with either "-v" or "-d" - /// // it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); - /// ``` - /// - /// [argument exclusion rules]: crate::Arg::conflicts_with_all() - #[must_use] - pub fn conflicts_with_all(mut self, ns: impl IntoIterator<Item = impl Into<Id>>) -> Self { - for n in ns { - self = self.conflicts_with(n); - } - self - } -} - -/// # Reflection -impl ArgGroup { - /// Get the name of the group - #[inline] - pub fn get_id(&self) -> &Id { - &self.id - } - - /// Reports whether [`ArgGroup::required`] is set - #[inline] - pub fn is_required_set(&self) -> bool { - self.required - } -} - -impl From<&'_ ArgGroup> for ArgGroup { - fn from(g: &ArgGroup) -> Self { - g.clone() - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn groups() { - let g = ArgGroup::new("test") - .arg("a1") - .arg("a4") - .args(["a2", "a3"]) - .required(true) - .conflicts_with("c1") - .conflicts_with_all(["c2", "c3"]) - .conflicts_with("c4") - .requires("r1") - .requires_all(["r2", "r3"]) - .requires("r4"); - - let args: Vec<Id> = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()]; - let reqs: Vec<Id> = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()]; - let confs: Vec<Id> = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()]; - - assert_eq!(g.args, args); - assert_eq!(g.requires, reqs); - assert_eq!(g.conflicts, confs); - } - - #[test] - fn test_from() { - let g = ArgGroup::new("test") - .arg("a1") - .arg("a4") - .args(["a2", "a3"]) - .required(true) - .conflicts_with("c1") - .conflicts_with_all(["c2", "c3"]) - .conflicts_with("c4") - .requires("r1") - .requires_all(["r2", "r3"]) - .requires("r4"); - - let args: Vec<Id> = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()]; - let reqs: Vec<Id> = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()]; - let confs: Vec<Id> = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()]; - - let g2 = ArgGroup::from(&g); - assert_eq!(g2.args, args); - assert_eq!(g2.requires, reqs); - assert_eq!(g2.conflicts, confs); - } - - // This test will *fail to compile* if ArgGroup is not Send + Sync - #[test] - fn arg_group_send_sync() { - fn foo<T: Send + Sync>(_: T) {} - foo(ArgGroup::new("test")) - } - - #[test] - fn arg_group_expose_is_multiple_helper() { - let args: Vec<Id> = vec!["a1".into(), "a4".into()]; - - let mut grp_multiple = ArgGroup::new("test_multiple").args(&args).multiple(true); - assert!(grp_multiple.is_multiple()); - - let mut grp_not_multiple = ArgGroup::new("test_multiple").args(&args).multiple(false); - assert!(!grp_not_multiple.is_multiple()); - } - - #[test] - fn arg_group_expose_get_args_helper() { - let args: Vec<Id> = vec!["a1".into(), "a4".into()]; - let grp = ArgGroup::new("program").args(&args); - - for (pos, arg) in grp.get_args().enumerate() { - assert_eq!(*arg, args[pos]); - } - } -} diff --git a/vendor/clap_builder/src/builder/arg_predicate.rs b/vendor/clap_builder/src/builder/arg_predicate.rs deleted file mode 100644 index bc79a11..0000000 --- a/vendor/clap_builder/src/builder/arg_predicate.rs +++ /dev/null @@ -1,19 +0,0 @@ -use crate::builder::OsStr; - -/// Operations to perform on argument values -/// -/// These do not apply to [`ValueSource::DefaultValue`][crate::parser::ValueSource::DefaultValue] -#[derive(Clone, Debug, PartialEq, Eq)] -#[cfg_attr(feature = "unstable-v5", non_exhaustive)] -pub enum ArgPredicate { - /// Is the argument present? - IsPresent, - /// Does the argument match the specified value? - Equals(OsStr), -} - -impl<S: Into<OsStr>> From<S> for ArgPredicate { - fn from(other: S) -> Self { - Self::Equals(other.into()) - } -} diff --git a/vendor/clap_builder/src/builder/arg_settings.rs b/vendor/clap_builder/src/builder/arg_settings.rs deleted file mode 100644 index fd47504..0000000 --- a/vendor/clap_builder/src/builder/arg_settings.rs +++ /dev/null @@ -1,91 +0,0 @@ -#[allow(unused)] -use crate::Arg; - -#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)] -pub(crate) struct ArgFlags(u32); - -impl ArgFlags { - pub(crate) fn set(&mut self, setting: ArgSettings) { - self.0 |= setting.bit(); - } - - pub(crate) fn unset(&mut self, setting: ArgSettings) { - self.0 &= !setting.bit(); - } - - pub(crate) fn is_set(&self, setting: ArgSettings) -> bool { - self.0 & setting.bit() != 0 - } - - pub(crate) fn insert(&mut self, other: Self) { - self.0 |= other.0; - } -} - -impl std::ops::BitOr for ArgFlags { - type Output = Self; - - fn bitor(mut self, rhs: Self) -> Self::Output { - self.insert(rhs); - self - } -} - -/// Various settings that apply to arguments and may be set, unset, and checked via getter/setter -/// methods [`Arg::setting`], [`Arg::unset_setting`], and [`Arg::is_set`]. This is what the -/// [`Arg`] methods which accept a `bool` use internally. -/// -/// [`Arg`]: crate::Arg -/// [`Arg::setting`]: crate::Arg::setting() -/// [`Arg::unset_setting`]: crate::Arg::unset_setting() -/// [`Arg::is_set`]: crate::Arg::is_set() -#[derive(Debug, PartialEq, Copy, Clone)] -#[repr(u8)] -pub(crate) enum ArgSettings { - Required, - Global, - Hidden, - NextLineHelp, - HidePossibleValues, - AllowHyphenValues, - AllowNegativeNumbers, - RequireEquals, - Last, - TrailingVarArg, - HideDefaultValue, - IgnoreCase, - #[cfg(feature = "env")] - HideEnv, - #[cfg(feature = "env")] - HideEnvValues, - HiddenShortHelp, - HiddenLongHelp, - Exclusive, -} - -impl ArgSettings { - fn bit(self) -> u32 { - 1 << (self as u8) - } -} - -#[cfg(test)] -mod test { - use super::*; - use crate::Arg; - - #[test] - fn setting() { - let m = Arg::new("setting").setting(ArgSettings::Required); - assert!(m.is_required_set()); - } - - #[test] - fn unset_setting() { - let m = Arg::new("unset_setting").setting(ArgSettings::Required); - assert!(m.is_required_set()); - - let m = m.unset_setting(ArgSettings::Required); - assert!(!m.is_required_set(), "{m:#?}"); - } -} diff --git a/vendor/clap_builder/src/builder/command.rs b/vendor/clap_builder/src/builder/command.rs deleted file mode 100644 index 6e56b18..0000000 --- a/vendor/clap_builder/src/builder/command.rs +++ /dev/null @@ -1,4916 +0,0 @@ -#![cfg_attr(not(feature = "usage"), allow(unused_mut))] - -// Std -use std::env; -use std::ffi::OsString; -use std::fmt; -use std::io; -use std::ops::Index; -use std::path::Path; - -// Internal -use crate::builder::app_settings::{AppFlags, AppSettings}; -use crate::builder::arg_settings::ArgSettings; -use crate::builder::ext::Extensions; -use crate::builder::ArgAction; -use crate::builder::IntoResettable; -use crate::builder::PossibleValue; -use crate::builder::Str; -use crate::builder::StyledStr; -use crate::builder::Styles; -use crate::builder::{Arg, ArgGroup, ArgPredicate}; -use crate::error::ErrorKind; -use crate::error::Result as ClapResult; -use crate::mkeymap::MKeyMap; -use crate::output::fmt::Stream; -use crate::output::{fmt::Colorizer, write_help, Usage}; -use crate::parser::{ArgMatcher, ArgMatches, Parser}; -use crate::util::ChildGraph; -use crate::util::{color::ColorChoice, Id}; -use crate::{Error, INTERNAL_ERROR_MSG}; - -#[cfg(debug_assertions)] -use crate::builder::debug_asserts::assert_app; - -/// Build a command-line interface. -/// -/// This includes defining arguments, subcommands, parser behavior, and help output. -/// Once all configuration is complete, -/// the [`Command::get_matches`] family of methods starts the runtime-parsing -/// process. These methods then return information about the user supplied -/// arguments (or lack thereof). -/// -/// When deriving a [`Parser`][crate::Parser], you can use -/// [`CommandFactory::command`][crate::CommandFactory::command] to access the -/// `Command`. -/// -/// - [Basic API][crate::Command#basic-api] -/// - [Application-wide Settings][crate::Command#application-wide-settings] -/// - [Command-specific Settings][crate::Command#command-specific-settings] -/// - [Subcommand-specific Settings][crate::Command#subcommand-specific-settings] -/// - [Reflection][crate::Command#reflection] -/// -/// # Examples -/// -/// ```no_run -/// # use clap_builder as clap; -/// # use clap::{Command, Arg}; -/// let m = Command::new("My Program") -/// .author("Me, me@mail.com") -/// .version("1.0.2") -/// .about("Explains in brief what the program does") -/// .arg( -/// Arg::new("in_file") -/// ) -/// .after_help("Longer explanation to appear after the options when \ -/// displaying the help information from --help or -h") -/// .get_matches(); -/// -/// // Your program logic starts here... -/// ``` -/// [`Command::get_matches`]: Command::get_matches() -#[derive(Debug, Clone)] -pub struct Command { - name: Str, - long_flag: Option<Str>, - short_flag: Option<char>, - display_name: Option<String>, - bin_name: Option<String>, - author: Option<Str>, - version: Option<Str>, - long_version: Option<Str>, - about: Option<StyledStr>, - long_about: Option<StyledStr>, - before_help: Option<StyledStr>, - before_long_help: Option<StyledStr>, - after_help: Option<StyledStr>, - after_long_help: Option<StyledStr>, - aliases: Vec<(Str, bool)>, // (name, visible) - short_flag_aliases: Vec<(char, bool)>, // (name, visible) - long_flag_aliases: Vec<(Str, bool)>, // (name, visible) - usage_str: Option<StyledStr>, - usage_name: Option<String>, - help_str: Option<StyledStr>, - disp_ord: Option<usize>, - #[cfg(feature = "help")] - template: Option<StyledStr>, - settings: AppFlags, - g_settings: AppFlags, - args: MKeyMap, - subcommands: Vec<Command>, - groups: Vec<ArgGroup>, - current_help_heading: Option<Str>, - current_disp_ord: Option<usize>, - subcommand_value_name: Option<Str>, - subcommand_heading: Option<Str>, - external_value_parser: Option<super::ValueParser>, - long_help_exists: bool, - deferred: Option<fn(Command) -> Command>, - app_ext: Extensions, -} - -/// # Basic API -impl Command { - /// Creates a new instance of an `Command`. - /// - /// It is common, but not required, to use binary name as the `name`. This - /// name will only be displayed to the user when they request to print - /// version or help and usage information. - /// - /// See also [`command!`](crate::command!) and [`crate_name!`](crate::crate_name!). - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// Command::new("My Program") - /// # ; - /// ``` - pub fn new(name: impl Into<Str>) -> Self { - /// The actual implementation of `new`, non-generic to save code size. - /// - /// If we don't do this rustc will unnecessarily generate multiple versions - /// of this code. - fn new_inner(name: Str) -> Command { - Command { - name, - ..Default::default() - } - } - - new_inner(name.into()) - } - - /// Adds an [argument] to the list of valid possibilities. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, arg, Arg}; - /// Command::new("myprog") - /// // Adding a single "flag" argument with a short and help text, using Arg::new() - /// .arg( - /// Arg::new("debug") - /// .short('d') - /// .help("turns on debugging mode") - /// ) - /// // Adding a single "option" argument with a short, a long, and help text using the less - /// // verbose Arg::from() - /// .arg( - /// arg!(-c --config <CONFIG> "Optionally sets a config file to use") - /// ) - /// # ; - /// ``` - /// [argument]: Arg - #[must_use] - pub fn arg(mut self, a: impl Into<Arg>) -> Self { - let arg = a.into(); - self.arg_internal(arg); - self - } - - fn arg_internal(&mut self, mut arg: Arg) { - if let Some(current_disp_ord) = self.current_disp_ord.as_mut() { - if !arg.is_positional() { - let current = *current_disp_ord; - arg.disp_ord.get_or_insert(current); - *current_disp_ord = current + 1; - } - } - - arg.help_heading - .get_or_insert_with(|| self.current_help_heading.clone()); - self.args.push(arg); - } - - /// Adds multiple [arguments] to the list of valid possibilities. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, arg, Arg}; - /// Command::new("myprog") - /// .args([ - /// arg!(-d --debug "turns on debugging info"), - /// Arg::new("input").help("the input file to use") - /// ]) - /// # ; - /// ``` - /// [arguments]: Arg - #[must_use] - pub fn args(mut self, args: impl IntoIterator<Item = impl Into<Arg>>) -> Self { - for arg in args { - self = self.arg(arg); - } - self - } - - /// Allows one to mutate an [`Arg`] after it's been added to a [`Command`]. - /// - /// # Panics - /// - /// If the argument is undefined - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// - /// let mut cmd = Command::new("foo") - /// .arg(Arg::new("bar") - /// .short('b') - /// .action(ArgAction::SetTrue)) - /// .mut_arg("bar", |a| a.short('B')); - /// - /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-b"]); - /// - /// // Since we changed `bar`'s short to "B" this should err as there - /// // is no `-b` anymore, only `-B` - /// - /// assert!(res.is_err()); - /// - /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-B"]); - /// assert!(res.is_ok()); - /// ``` - #[must_use] - #[cfg_attr(debug_assertions, track_caller)] - pub fn mut_arg<F>(mut self, arg_id: impl AsRef<str>, f: F) -> Self - where - F: FnOnce(Arg) -> Arg, - { - let id = arg_id.as_ref(); - let a = self - .args - .remove_by_name(id) - .unwrap_or_else(|| panic!("Argument `{id}` is undefined")); - - self.args.push(f(a)); - self - } - - /// Allows one to mutate all [`Arg`]s after they've been added to a [`Command`]. - /// - /// This does not affect the built-in `--help` or `--version` arguments. - /// - /// # Examples - /// - #[cfg_attr(feature = "string", doc = "```")] - #[cfg_attr(not(feature = "string"), doc = "```ignore")] - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// - /// let mut cmd = Command::new("foo") - /// .arg(Arg::new("bar") - /// .long("bar") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("baz") - /// .long("baz") - /// .action(ArgAction::SetTrue)) - /// .mut_args(|a| { - /// if let Some(l) = a.get_long().map(|l| format!("prefix-{l}")) { - /// a.long(l) - /// } else { - /// a - /// } - /// }); - /// - /// let res = cmd.try_get_matches_from_mut(vec!["foo", "--bar"]); - /// - /// // Since we changed `bar`'s long to "prefix-bar" this should err as there - /// // is no `--bar` anymore, only `--prefix-bar`. - /// - /// assert!(res.is_err()); - /// - /// let res = cmd.try_get_matches_from_mut(vec!["foo", "--prefix-bar"]); - /// assert!(res.is_ok()); - /// ``` - #[must_use] - #[cfg_attr(debug_assertions, track_caller)] - pub fn mut_args<F>(mut self, f: F) -> Self - where - F: FnMut(Arg) -> Arg, - { - self.args.mut_args(f); - self - } - - /// Allows one to mutate an [`ArgGroup`] after it's been added to a [`Command`]. - /// - /// # Panics - /// - /// If the argument is undefined - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, arg, ArgGroup}; - /// - /// Command::new("foo") - /// .arg(arg!(--"set-ver" <ver> "set the version manually").required(false)) - /// .arg(arg!(--major "auto increase major")) - /// .arg(arg!(--minor "auto increase minor")) - /// .arg(arg!(--patch "auto increase patch")) - /// .group(ArgGroup::new("vers") - /// .args(["set-ver", "major", "minor","patch"]) - /// .required(true)) - /// .mut_group("vers", |a| a.required(false)); - /// ``` - #[must_use] - #[cfg_attr(debug_assertions, track_caller)] - pub fn mut_group<F>(mut self, arg_id: impl AsRef<str>, f: F) -> Self - where - F: FnOnce(ArgGroup) -> ArgGroup, - { - let id = arg_id.as_ref(); - let index = self - .groups - .iter() - .position(|g| g.get_id() == id) - .unwrap_or_else(|| panic!("Group `{id}` is undefined")); - let a = self.groups.remove(index); - - self.groups.push(f(a)); - self - } - /// Allows one to mutate a [`Command`] after it's been added as a subcommand. - /// - /// This can be useful for modifying auto-generated arguments of nested subcommands with - /// [`Command::mut_arg`]. - /// - /// # Panics - /// - /// If the subcommand is undefined - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// - /// let mut cmd = Command::new("foo") - /// .subcommand(Command::new("bar")) - /// .mut_subcommand("bar", |subcmd| subcmd.disable_help_flag(true)); - /// - /// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar", "--help"]); - /// - /// // Since we disabled the help flag on the "bar" subcommand, this should err. - /// - /// assert!(res.is_err()); - /// - /// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar"]); - /// assert!(res.is_ok()); - /// ``` - #[must_use] - pub fn mut_subcommand<F>(mut self, name: impl AsRef<str>, f: F) -> Self - where - F: FnOnce(Self) -> Self, - { - let name = name.as_ref(); - let pos = self.subcommands.iter().position(|s| s.name == name); - - let subcmd = if let Some(idx) = pos { - self.subcommands.remove(idx) - } else { - panic!("Command `{name}` is undefined") - }; - - self.subcommands.push(f(subcmd)); - self - } - - /// Adds an [`ArgGroup`] to the application. - /// - /// [`ArgGroup`]s are a family of related arguments. - /// By placing them in a logical group, you can build easier requirement and exclusion rules. - /// - /// Example use cases: - /// - Make an entire [`ArgGroup`] required, meaning that one (and *only* - /// one) argument from that group must be present at runtime. - /// - Name an [`ArgGroup`] as a conflict to another argument. - /// Meaning any of the arguments that belong to that group will cause a failure if present with - /// the conflicting argument. - /// - Ensure exclusion between arguments. - /// - Extract a value from a group instead of determining exactly which argument was used. - /// - /// # Examples - /// - /// The following example demonstrates using an [`ArgGroup`] to ensure that one, and only one, - /// of the arguments from the specified group is present at runtime. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, arg, ArgGroup}; - /// Command::new("cmd") - /// .arg(arg!(--"set-ver" <ver> "set the version manually").required(false)) - /// .arg(arg!(--major "auto increase major")) - /// .arg(arg!(--minor "auto increase minor")) - /// .arg(arg!(--patch "auto increase patch")) - /// .group(ArgGroup::new("vers") - /// .args(["set-ver", "major", "minor","patch"]) - /// .required(true)) - /// # ; - /// ``` - #[inline] - #[must_use] - pub fn group(mut self, group: impl Into<ArgGroup>) -> Self { - self.groups.push(group.into()); - self - } - - /// Adds multiple [`ArgGroup`]s to the [`Command`] at once. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, arg, ArgGroup}; - /// Command::new("cmd") - /// .arg(arg!(--"set-ver" <ver> "set the version manually").required(false)) - /// .arg(arg!(--major "auto increase major")) - /// .arg(arg!(--minor "auto increase minor")) - /// .arg(arg!(--patch "auto increase patch")) - /// .arg(arg!(-c <FILE> "a config file").required(false)) - /// .arg(arg!(-i <IFACE> "an interface").required(false)) - /// .groups([ - /// ArgGroup::new("vers") - /// .args(["set-ver", "major", "minor","patch"]) - /// .required(true), - /// ArgGroup::new("input") - /// .args(["c", "i"]) - /// ]) - /// # ; - /// ``` - #[must_use] - pub fn groups(mut self, groups: impl IntoIterator<Item = impl Into<ArgGroup>>) -> Self { - for g in groups.into_iter() { - self = self.group(g.into()); - } - self - } - - /// Adds a subcommand to the list of valid possibilities. - /// - /// Subcommands are effectively sub-[`Command`]s, because they can contain their own arguments, - /// subcommands, version, usage, etc. They also function just like [`Command`]s, in that they get - /// their own auto generated help, version, and usage. - /// - /// A subcommand's [`Command::name`] will be used for: - /// - The argument the user passes in - /// - Programmatically looking up the subcommand - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, arg}; - /// Command::new("myprog") - /// .subcommand(Command::new("config") - /// .about("Controls configuration features") - /// .arg(arg!(<config> "Required configuration file to use"))) - /// # ; - /// ``` - #[inline] - #[must_use] - pub fn subcommand(self, subcmd: impl Into<Command>) -> Self { - let subcmd = subcmd.into(); - self.subcommand_internal(subcmd) - } - - fn subcommand_internal(mut self, mut subcmd: Self) -> Self { - if let Some(current_disp_ord) = self.current_disp_ord.as_mut() { - let current = *current_disp_ord; - subcmd.disp_ord.get_or_insert(current); - *current_disp_ord = current + 1; - } - self.subcommands.push(subcmd); - self - } - - /// Adds multiple subcommands to the list of valid possibilities. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, }; - /// # Command::new("myprog") - /// .subcommands( [ - /// Command::new("config").about("Controls configuration functionality") - /// .arg(Arg::new("config_file")), - /// Command::new("debug").about("Controls debug functionality")]) - /// # ; - /// ``` - /// [`IntoIterator`]: std::iter::IntoIterator - #[must_use] - pub fn subcommands(mut self, subcmds: impl IntoIterator<Item = impl Into<Self>>) -> Self { - for subcmd in subcmds { - self = self.subcommand(subcmd); - } - self - } - - /// Delay initialization for parts of the `Command` - /// - /// This is useful for large applications to delay definitions of subcommands until they are - /// being invoked. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, arg}; - /// Command::new("myprog") - /// .subcommand(Command::new("config") - /// .about("Controls configuration features") - /// .defer(|cmd| { - /// cmd.arg(arg!(<config> "Required configuration file to use")) - /// }) - /// ) - /// # ; - /// ``` - pub fn defer(mut self, deferred: fn(Command) -> Command) -> Self { - self.deferred = Some(deferred); - self - } - - /// Catch problems earlier in the development cycle. - /// - /// Most error states are handled as asserts under the assumption they are programming mistake - /// and not something to handle at runtime. Rather than relying on tests (manual or automated) - /// that exhaustively test your CLI to ensure the asserts are evaluated, this will run those - /// asserts in a way convenient for running as a test. - /// - /// **Note::** This will not help with asserts in [`ArgMatches`], those will need exhaustive - /// testing of your CLI. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// fn cmd() -> Command { - /// Command::new("foo") - /// .arg( - /// Arg::new("bar").short('b').action(ArgAction::SetTrue) - /// ) - /// } - /// - /// #[test] - /// fn verify_app() { - /// cmd().debug_assert(); - /// } - /// - /// fn main() { - /// let m = cmd().get_matches_from(vec!["foo", "-b"]); - /// println!("{}", m.get_flag("bar")); - /// } - /// ``` - pub fn debug_assert(mut self) { - self.build(); - } - - /// Custom error message for post-parsing validation - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, error::ErrorKind}; - /// let mut cmd = Command::new("myprog"); - /// let err = cmd.error(ErrorKind::InvalidValue, "Some failure case"); - /// ``` - pub fn error(&mut self, kind: ErrorKind, message: impl std::fmt::Display) -> Error { - Error::raw(kind, message).format(self) - } - - /// Parse [`env::args_os`], exiting on failure. - /// - /// # Panics - /// - /// If contradictory arguments or settings exist (debug builds). - /// - /// # Examples - /// - /// ```no_run - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// let matches = Command::new("myprog") - /// // Args and options go here... - /// .get_matches(); - /// ``` - /// [`env::args_os`]: std::env::args_os() - /// [`Command::try_get_matches_from_mut`]: Command::try_get_matches_from_mut() - #[inline] - pub fn get_matches(self) -> ArgMatches { - self.get_matches_from(env::args_os()) - } - - /// Parse [`env::args_os`], exiting on failure. - /// - /// Like [`Command::get_matches`] but doesn't consume the `Command`. - /// - /// # Panics - /// - /// If contradictory arguments or settings exist (debug builds). - /// - /// # Examples - /// - /// ```no_run - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// let mut cmd = Command::new("myprog") - /// // Args and options go here... - /// ; - /// let matches = cmd.get_matches_mut(); - /// ``` - /// [`env::args_os`]: std::env::args_os() - /// [`Command::get_matches`]: Command::get_matches() - pub fn get_matches_mut(&mut self) -> ArgMatches { - self.try_get_matches_from_mut(&mut env::args_os()) - .unwrap_or_else(|e| e.exit()) - } - - /// Parse [`env::args_os`], returning a [`clap::Result`] on failure. - /// - /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are - /// used. It will return a [`clap::Error`], where the [`kind`] is a - /// [`ErrorKind::DisplayHelp`] or [`ErrorKind::DisplayVersion`] respectively. You must call - /// [`Error::exit`] or perform a [`std::process::exit`]. - /// - /// # Panics - /// - /// If contradictory arguments or settings exist (debug builds). - /// - /// # Examples - /// - /// ```no_run - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// let matches = Command::new("myprog") - /// // Args and options go here... - /// .try_get_matches() - /// .unwrap_or_else(|e| e.exit()); - /// ``` - /// [`env::args_os`]: std::env::args_os() - /// [`Error::exit`]: crate::Error::exit() - /// [`std::process::exit`]: std::process::exit() - /// [`clap::Result`]: Result - /// [`clap::Error`]: crate::Error - /// [`kind`]: crate::Error - /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp - /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion - #[inline] - pub fn try_get_matches(self) -> ClapResult<ArgMatches> { - // Start the parsing - self.try_get_matches_from(env::args_os()) - } - - /// Parse the specified arguments, exiting on failure. - /// - /// **NOTE:** The first argument will be parsed as the binary name unless - /// [`Command::no_binary_name`] is used. - /// - /// # Panics - /// - /// If contradictory arguments or settings exist (debug builds). - /// - /// # Examples - /// - /// ```no_run - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; - /// - /// let matches = Command::new("myprog") - /// // Args and options go here... - /// .get_matches_from(arg_vec); - /// ``` - /// [`Command::get_matches`]: Command::get_matches() - /// [`clap::Result`]: Result - /// [`Vec`]: std::vec::Vec - pub fn get_matches_from<I, T>(mut self, itr: I) -> ArgMatches - where - I: IntoIterator<Item = T>, - T: Into<OsString> + Clone, - { - self.try_get_matches_from_mut(itr).unwrap_or_else(|e| { - drop(self); - e.exit() - }) - } - - /// Parse the specified arguments, returning a [`clap::Result`] on failure. - /// - /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are - /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`] - /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or - /// perform a [`std::process::exit`] yourself. - /// - /// **NOTE:** The first argument will be parsed as the binary name unless - /// [`Command::no_binary_name`] is used. - /// - /// # Panics - /// - /// If contradictory arguments or settings exist (debug builds). - /// - /// # Examples - /// - /// ```no_run - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; - /// - /// let matches = Command::new("myprog") - /// // Args and options go here... - /// .try_get_matches_from(arg_vec) - /// .unwrap_or_else(|e| e.exit()); - /// ``` - /// [`Command::get_matches_from`]: Command::get_matches_from() - /// [`Command::try_get_matches`]: Command::try_get_matches() - /// [`Error::exit`]: crate::Error::exit() - /// [`std::process::exit`]: std::process::exit() - /// [`clap::Error`]: crate::Error - /// [`Error::exit`]: crate::Error::exit() - /// [`kind`]: crate::Error - /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp - /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion - /// [`clap::Result`]: Result - pub fn try_get_matches_from<I, T>(mut self, itr: I) -> ClapResult<ArgMatches> - where - I: IntoIterator<Item = T>, - T: Into<OsString> + Clone, - { - self.try_get_matches_from_mut(itr) - } - - /// Parse the specified arguments, returning a [`clap::Result`] on failure. - /// - /// Like [`Command::try_get_matches_from`] but doesn't consume the `Command`. - /// - /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are - /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`] - /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or - /// perform a [`std::process::exit`] yourself. - /// - /// **NOTE:** The first argument will be parsed as the binary name unless - /// [`Command::no_binary_name`] is used. - /// - /// # Panics - /// - /// If contradictory arguments or settings exist (debug builds). - /// - /// # Examples - /// - /// ```no_run - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; - /// - /// let mut cmd = Command::new("myprog"); - /// // Args and options go here... - /// let matches = cmd.try_get_matches_from_mut(arg_vec) - /// .unwrap_or_else(|e| e.exit()); - /// ``` - /// [`Command::try_get_matches_from`]: Command::try_get_matches_from() - /// [`clap::Result`]: Result - /// [`clap::Error`]: crate::Error - /// [`kind`]: crate::Error - pub fn try_get_matches_from_mut<I, T>(&mut self, itr: I) -> ClapResult<ArgMatches> - where - I: IntoIterator<Item = T>, - T: Into<OsString> + Clone, - { - let mut raw_args = clap_lex::RawArgs::new(itr); - let mut cursor = raw_args.cursor(); - - if self.settings.is_set(AppSettings::Multicall) { - if let Some(argv0) = raw_args.next_os(&mut cursor) { - let argv0 = Path::new(&argv0); - if let Some(command) = argv0.file_stem().and_then(|f| f.to_str()) { - // Stop borrowing command so we can get another mut ref to it. - let command = command.to_owned(); - debug!("Command::try_get_matches_from_mut: Parsed command {command} from argv"); - - debug!("Command::try_get_matches_from_mut: Reinserting command into arguments so subcommand parser matches it"); - raw_args.insert(&cursor, [&command]); - debug!("Command::try_get_matches_from_mut: Clearing name and bin_name so that displayed command name starts with applet name"); - self.name = "".into(); - self.bin_name = None; - return self._do_parse(&mut raw_args, cursor); - } - } - }; - - // Get the name of the program (argument 1 of env::args()) and determine the - // actual file - // that was used to execute the program. This is because a program called - // ./target/release/my_prog -a - // will have two arguments, './target/release/my_prog', '-a' but we don't want - // to display - // the full path when displaying help messages and such - if !self.settings.is_set(AppSettings::NoBinaryName) { - if let Some(name) = raw_args.next_os(&mut cursor) { - let p = Path::new(name); - - if let Some(f) = p.file_name() { - if let Some(s) = f.to_str() { - if self.bin_name.is_none() { - self.bin_name = Some(s.to_owned()); - } - } - } - } - } - - self._do_parse(&mut raw_args, cursor) - } - - /// Prints the short help message (`-h`) to [`io::stdout()`]. - /// - /// See also [`Command::print_long_help`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// let mut cmd = Command::new("myprog"); - /// cmd.print_help(); - /// ``` - /// [`io::stdout()`]: std::io::stdout() - pub fn print_help(&mut self) -> io::Result<()> { - self._build_self(false); - let color = self.color_help(); - - let mut styled = StyledStr::new(); - let usage = Usage::new(self); - write_help(&mut styled, self, &usage, false); - - let c = Colorizer::new(Stream::Stdout, color).with_content(styled); - c.print() - } - - /// Prints the long help message (`--help`) to [`io::stdout()`]. - /// - /// See also [`Command::print_help`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// let mut cmd = Command::new("myprog"); - /// cmd.print_long_help(); - /// ``` - /// [`io::stdout()`]: std::io::stdout() - /// [`BufWriter`]: std::io::BufWriter - /// [`-h` (short)]: Arg::help() - /// [`--help` (long)]: Arg::long_help() - pub fn print_long_help(&mut self) -> io::Result<()> { - self._build_self(false); - let color = self.color_help(); - - let mut styled = StyledStr::new(); - let usage = Usage::new(self); - write_help(&mut styled, self, &usage, true); - - let c = Colorizer::new(Stream::Stdout, color).with_content(styled); - c.print() - } - - /// Render the short help message (`-h`) to a [`StyledStr`] - /// - /// See also [`Command::render_long_help`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// use std::io; - /// let mut cmd = Command::new("myprog"); - /// let mut out = io::stdout(); - /// let help = cmd.render_help(); - /// println!("{help}"); - /// ``` - /// [`io::Write`]: std::io::Write - /// [`-h` (short)]: Arg::help() - /// [`--help` (long)]: Arg::long_help() - pub fn render_help(&mut self) -> StyledStr { - self._build_self(false); - - let mut styled = StyledStr::new(); - let usage = Usage::new(self); - write_help(&mut styled, self, &usage, false); - styled - } - - /// Render the long help message (`--help`) to a [`StyledStr`]. - /// - /// See also [`Command::render_help`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// use std::io; - /// let mut cmd = Command::new("myprog"); - /// let mut out = io::stdout(); - /// let help = cmd.render_long_help(); - /// println!("{help}"); - /// ``` - /// [`io::Write`]: std::io::Write - /// [`-h` (short)]: Arg::help() - /// [`--help` (long)]: Arg::long_help() - pub fn render_long_help(&mut self) -> StyledStr { - self._build_self(false); - - let mut styled = StyledStr::new(); - let usage = Usage::new(self); - write_help(&mut styled, self, &usage, true); - styled - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Command::render_help`") - )] - pub fn write_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> { - self._build_self(false); - - let mut styled = StyledStr::new(); - let usage = Usage::new(self); - write_help(&mut styled, self, &usage, false); - ok!(write!(w, "{styled}")); - w.flush() - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Command::render_long_help`") - )] - pub fn write_long_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> { - self._build_self(false); - - let mut styled = StyledStr::new(); - let usage = Usage::new(self); - write_help(&mut styled, self, &usage, true); - ok!(write!(w, "{styled}")); - w.flush() - } - - /// Version message rendered as if the user ran `-V`. - /// - /// See also [`Command::render_long_version`]. - /// - /// ### Coloring - /// - /// This function does not try to color the message nor it inserts any [ANSI escape codes]. - /// - /// ### Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// use std::io; - /// let cmd = Command::new("myprog"); - /// println!("{}", cmd.render_version()); - /// ``` - /// [`io::Write`]: std::io::Write - /// [`-V` (short)]: Command::version() - /// [`--version` (long)]: Command::long_version() - /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code - pub fn render_version(&self) -> String { - self._render_version(false) - } - - /// Version message rendered as if the user ran `--version`. - /// - /// See also [`Command::render_version`]. - /// - /// ### Coloring - /// - /// This function does not try to color the message nor it inserts any [ANSI escape codes]. - /// - /// ### Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// use std::io; - /// let cmd = Command::new("myprog"); - /// println!("{}", cmd.render_long_version()); - /// ``` - /// [`io::Write`]: std::io::Write - /// [`-V` (short)]: Command::version() - /// [`--version` (long)]: Command::long_version() - /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code - pub fn render_long_version(&self) -> String { - self._render_version(true) - } - - /// Usage statement - /// - /// ### Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// use std::io; - /// let mut cmd = Command::new("myprog"); - /// println!("{}", cmd.render_usage()); - /// ``` - pub fn render_usage(&mut self) -> StyledStr { - self.render_usage_().unwrap_or_default() - } - - pub(crate) fn render_usage_(&mut self) -> Option<StyledStr> { - // If there are global arguments, or settings we need to propagate them down to subcommands - // before parsing incase we run into a subcommand - self._build_self(false); - - Usage::new(self).create_usage_with_title(&[]) - } -} - -/// # Application-wide Settings -/// -/// These settings will apply to the top-level command and all subcommands, by default. Some -/// settings can be overridden in subcommands. -impl Command { - /// Specifies that the parser should not assume the first argument passed is the binary name. - /// - /// This is normally the case when using a "daemon" style mode. For shells / REPLs, see - /// [`Command::multicall`][Command::multicall]. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, arg}; - /// let m = Command::new("myprog") - /// .no_binary_name(true) - /// .arg(arg!(<cmd> ... "commands to run")) - /// .get_matches_from(vec!["command", "set"]); - /// - /// let cmds: Vec<_> = m.get_many::<String>("cmd").unwrap().collect(); - /// assert_eq!(cmds, ["command", "set"]); - /// ``` - /// [`try_get_matches_from_mut`]: crate::Command::try_get_matches_from_mut() - #[inline] - pub fn no_binary_name(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::NoBinaryName) - } else { - self.unset_global_setting(AppSettings::NoBinaryName) - } - } - - /// Try not to fail on parse errors, like missing option values. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, arg}; - /// let cmd = Command::new("cmd") - /// .ignore_errors(true) - /// .arg(arg!(-c --config <FILE> "Sets a custom config file")) - /// .arg(arg!(-x --stuff <FILE> "Sets a custom stuff file")) - /// .arg(arg!(f: -f "Flag")); - /// - /// let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]); - /// - /// assert!(r.is_ok(), "unexpected error: {r:?}"); - /// let m = r.unwrap(); - /// assert_eq!(m.get_one::<String>("config").unwrap(), "file"); - /// assert!(m.get_flag("f")); - /// assert_eq!(m.get_one::<String>("stuff"), None); - /// ``` - #[inline] - pub fn ignore_errors(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::IgnoreErrors) - } else { - self.unset_global_setting(AppSettings::IgnoreErrors) - } - } - - /// Replace prior occurrences of arguments rather than error - /// - /// For any argument that would conflict with itself by default (e.g. - /// [`ArgAction::Set`], it will now override itself. - /// - /// This is the equivalent to saying the `foo` arg using [`Arg::overrides_with("foo")`] for all - /// defined arguments. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// [`Arg::overrides_with("foo")`]: crate::Arg::overrides_with() - #[inline] - pub fn args_override_self(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::AllArgsOverrideSelf) - } else { - self.unset_global_setting(AppSettings::AllArgsOverrideSelf) - } - } - - /// Disables the automatic delimiting of values after `--` or when [`Command::trailing_var_arg`] - /// was used. - /// - /// **NOTE:** The same thing can be done manually by setting the final positional argument to - /// [`Arg::value_delimiter(None)`]. Using this setting is safer, because it's easier to locate - /// when making changes. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```no_run - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .dont_delimit_trailing_values(true) - /// .get_matches(); - /// ``` - /// - /// [`Arg::value_delimiter(None)`]: crate::Arg::value_delimiter() - #[inline] - pub fn dont_delimit_trailing_values(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::DontDelimitTrailingValues) - } else { - self.unset_global_setting(AppSettings::DontDelimitTrailingValues) - } - } - - /// Sets when to color output. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// **NOTE:** Default behaviour is [`ColorChoice::Auto`]. - /// - /// # Examples - /// - /// ```no_run - /// # use clap_builder as clap; - /// # use clap::{Command, ColorChoice}; - /// Command::new("myprog") - /// .color(ColorChoice::Never) - /// .get_matches(); - /// ``` - /// [`ColorChoice::Auto`]: crate::ColorChoice::Auto - #[cfg(feature = "color")] - #[inline] - #[must_use] - pub fn color(self, color: ColorChoice) -> Self { - let cmd = self - .unset_global_setting(AppSettings::ColorAuto) - .unset_global_setting(AppSettings::ColorAlways) - .unset_global_setting(AppSettings::ColorNever); - match color { - ColorChoice::Auto => cmd.global_setting(AppSettings::ColorAuto), - ColorChoice::Always => cmd.global_setting(AppSettings::ColorAlways), - ColorChoice::Never => cmd.global_setting(AppSettings::ColorNever), - } - } - - /// Sets the [`Styles`] for terminal output - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// **NOTE:** Default behaviour is [`Styles::default`]. - /// - /// # Examples - /// - /// ```no_run - /// # use clap_builder as clap; - /// # use clap::{Command, ColorChoice, builder::styling}; - /// let styles = styling::Styles::styled() - /// .header(styling::AnsiColor::Green.on_default() | styling::Effects::BOLD) - /// .usage(styling::AnsiColor::Green.on_default() | styling::Effects::BOLD) - /// .literal(styling::AnsiColor::Blue.on_default() | styling::Effects::BOLD) - /// .placeholder(styling::AnsiColor::Cyan.on_default()); - /// Command::new("myprog") - /// .styles(styles) - /// .get_matches(); - /// ``` - #[cfg(feature = "color")] - #[inline] - #[must_use] - pub fn styles(mut self, styles: Styles) -> Self { - self.app_ext.set(styles); - self - } - - /// Sets the terminal width at which to wrap help messages. - /// - /// Using `0` will ignore terminal widths and use source formatting. - /// - /// Defaults to current terminal width when `wrap_help` feature flag is enabled. If current - /// width cannot be determined, the default is 100. - /// - /// **`unstable-v5` feature**: Defaults to unbound, being subject to - /// [`Command::max_term_width`]. - /// - /// **NOTE:** This setting applies globally and *not* on a per-command basis. - /// - /// **NOTE:** This requires the `wrap_help` feature - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// Command::new("myprog") - /// .term_width(80) - /// # ; - /// ``` - #[inline] - #[must_use] - #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))] - pub fn term_width(mut self, width: usize) -> Self { - self.app_ext.set(TermWidth(width)); - self - } - - /// Limit the line length for wrapping help when using the current terminal's width. - /// - /// This only applies when [`term_width`][Command::term_width] is unset so that the current - /// terminal's width will be used. See [`Command::term_width`] for more details. - /// - /// Using `0` will ignore this, always respecting [`Command::term_width`] (default). - /// - /// **`unstable-v5` feature**: Defaults to 100. - /// - /// **NOTE:** This setting applies globally and *not* on a per-command basis. - /// - /// **NOTE:** This requires the `wrap_help` feature - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// Command::new("myprog") - /// .max_term_width(100) - /// # ; - /// ``` - #[inline] - #[must_use] - #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))] - pub fn max_term_width(mut self, width: usize) -> Self { - self.app_ext.set(MaxTermWidth(width)); - self - } - - /// Disables `-V` and `--version` flag. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, error::ErrorKind}; - /// let res = Command::new("myprog") - /// .version("1.0.0") - /// .disable_version_flag(true) - /// .try_get_matches_from(vec![ - /// "myprog", "--version" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// ``` - /// - /// You can create a custom version flag with [`ArgAction::Version`] - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction, error::ErrorKind}; - /// let mut cmd = Command::new("myprog") - /// .version("1.0.0") - /// // Remove the `-V` short flag - /// .disable_version_flag(true) - /// .arg( - /// Arg::new("version") - /// .long("version") - /// .action(ArgAction::Version) - /// .help("Print version") - /// ); - /// - /// let res = cmd.try_get_matches_from_mut(vec![ - /// "myprog", "-V" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// - /// let res = cmd.try_get_matches_from_mut(vec![ - /// "myprog", "--version" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::DisplayVersion); - /// ``` - #[inline] - pub fn disable_version_flag(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::DisableVersionFlag) - } else { - self.unset_global_setting(AppSettings::DisableVersionFlag) - } - } - - /// Specifies to use the version of the current command for all [`subcommands`]. - /// - /// Defaults to `false`; subcommands have independent version strings from their parents. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```no_run - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .version("v1.1") - /// .propagate_version(true) - /// .subcommand(Command::new("test")) - /// .get_matches(); - /// // running `$ myprog test --version` will display - /// // "myprog-test v1.1" - /// ``` - /// - /// [`subcommands`]: crate::Command::subcommand() - #[inline] - pub fn propagate_version(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::PropagateVersion) - } else { - self.unset_global_setting(AppSettings::PropagateVersion) - } - } - - /// Places the help string for all arguments and subcommands on the line after them. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```no_run - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .next_line_help(true) - /// .get_matches(); - /// ``` - #[inline] - pub fn next_line_help(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::NextLineHelp) - } else { - self.unset_global_setting(AppSettings::NextLineHelp) - } - } - - /// Disables `-h` and `--help` flag. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, error::ErrorKind}; - /// let res = Command::new("myprog") - /// .disable_help_flag(true) - /// .try_get_matches_from(vec![ - /// "myprog", "-h" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// ``` - /// - /// You can create a custom help flag with [`ArgAction::Help`], [`ArgAction::HelpShort`], or - /// [`ArgAction::HelpLong`] - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction, error::ErrorKind}; - /// let mut cmd = Command::new("myprog") - /// // Change help short flag to `?` - /// .disable_help_flag(true) - /// .arg( - /// Arg::new("help") - /// .short('?') - /// .long("help") - /// .action(ArgAction::Help) - /// .help("Print help") - /// ); - /// - /// let res = cmd.try_get_matches_from_mut(vec![ - /// "myprog", "-h" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// - /// let res = cmd.try_get_matches_from_mut(vec![ - /// "myprog", "-?" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::DisplayHelp); - /// ``` - #[inline] - pub fn disable_help_flag(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::DisableHelpFlag) - } else { - self.unset_global_setting(AppSettings::DisableHelpFlag) - } - } - - /// Disables the `help` [`subcommand`]. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, error::ErrorKind}; - /// let res = Command::new("myprog") - /// .disable_help_subcommand(true) - /// // Normally, creating a subcommand causes a `help` subcommand to automatically - /// // be generated as well - /// .subcommand(Command::new("test")) - /// .try_get_matches_from(vec![ - /// "myprog", "help" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::InvalidSubcommand); - /// ``` - /// - /// [`subcommand`]: crate::Command::subcommand() - #[inline] - pub fn disable_help_subcommand(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::DisableHelpSubcommand) - } else { - self.unset_global_setting(AppSettings::DisableHelpSubcommand) - } - } - - /// Disables colorized help messages. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```no_run - /// # use clap_builder as clap; - /// # use clap::Command; - /// Command::new("myprog") - /// .disable_colored_help(true) - /// .get_matches(); - /// ``` - #[inline] - pub fn disable_colored_help(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::DisableColoredHelp) - } else { - self.unset_global_setting(AppSettings::DisableColoredHelp) - } - } - - /// Panic if help descriptions are omitted. - /// - /// **NOTE:** When deriving [`Parser`][crate::Parser], you could instead check this at - /// compile-time with `#![deny(missing_docs)]` - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .help_expected(true) - /// .arg( - /// Arg::new("foo").help("It does foo stuff") - /// // As required via `help_expected`, a help message was supplied - /// ) - /// # .get_matches(); - /// ``` - /// - /// # Panics - /// - /// On debug builds: - /// ```rust,no_run - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// Command::new("myapp") - /// .help_expected(true) - /// .arg( - /// Arg::new("foo") - /// // Someone forgot to put .about("...") here - /// // Since the setting `help_expected` is activated, this will lead to - /// // a panic (if you are in debug mode) - /// ) - /// # .get_matches(); - ///``` - #[inline] - pub fn help_expected(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::HelpExpected) - } else { - self.unset_global_setting(AppSettings::HelpExpected) - } - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "This is now the default") - )] - pub fn dont_collapse_args_in_usage(self, _yes: bool) -> Self { - self - } - - /// Tells `clap` *not* to print possible values when displaying help information. - /// - /// This can be useful if there are many values, or they are explained elsewhere. - /// - /// To set this per argument, see - /// [`Arg::hide_possible_values`][crate::Arg::hide_possible_values]. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - #[inline] - pub fn hide_possible_values(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::HidePossibleValues) - } else { - self.unset_global_setting(AppSettings::HidePossibleValues) - } - } - - /// Allow partial matches of long arguments or their [aliases]. - /// - /// For example, to match an argument named `--test`, one could use `--t`, `--te`, `--tes`, and - /// `--test`. - /// - /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match - /// `--te` to `--test` there could not also be another argument or alias `--temp` because both - /// start with `--te` - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// [aliases]: crate::Command::aliases() - #[inline] - pub fn infer_long_args(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::InferLongArgs) - } else { - self.unset_global_setting(AppSettings::InferLongArgs) - } - } - - /// Allow partial matches of [subcommand] names and their [aliases]. - /// - /// For example, to match a subcommand named `test`, one could use `t`, `te`, `tes`, and - /// `test`. - /// - /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match `te` - /// to `test` there could not also be a subcommand or alias `temp` because both start with `te` - /// - /// **CAUTION:** This setting can interfere with [positional/free arguments], take care when - /// designing CLIs which allow inferred subcommands and have potential positional/free - /// arguments whose values could start with the same characters as subcommands. If this is the - /// case, it's recommended to use settings such as [`Command::args_conflicts_with_subcommands`] in - /// conjunction with this setting. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```no_run - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .infer_subcommands(true) - /// .subcommand(Command::new("test")) - /// .get_matches_from(vec![ - /// "prog", "te" - /// ]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// - /// [subcommand]: crate::Command::subcommand() - /// [positional/free arguments]: crate::Arg::index() - /// [aliases]: crate::Command::aliases() - #[inline] - pub fn infer_subcommands(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::InferSubcommands) - } else { - self.unset_global_setting(AppSettings::InferSubcommands) - } - } -} - -/// # Command-specific Settings -/// -/// These apply only to the current command and are not inherited by subcommands. -impl Command { - /// (Re)Sets the program's name. - /// - /// See [`Command::new`] for more details. - /// - /// # Examples - /// - /// ```ignore - /// let cmd = clap::command!() - /// .name("foo"); - /// - /// // continued logic goes here, such as `cmd.get_matches()` etc. - /// ``` - #[must_use] - pub fn name(mut self, name: impl Into<Str>) -> Self { - self.name = name.into(); - self - } - - /// Overrides the runtime-determined name of the binary for help and error messages. - /// - /// This should only be used when absolutely necessary, such as when the binary name for your - /// application is misleading, or perhaps *not* how the user should invoke your program. - /// - /// **Pro-tip:** When building things such as third party `cargo` - /// subcommands, this setting **should** be used! - /// - /// **NOTE:** This *does not* change or set the name of the binary file on - /// disk. It only changes what clap thinks the name is for the purposes of - /// error or help messages. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// Command::new("My Program") - /// .bin_name("my_binary") - /// # ; - /// ``` - #[must_use] - pub fn bin_name(mut self, name: impl IntoResettable<String>) -> Self { - self.bin_name = name.into_resettable().into_option(); - self - } - - /// Overrides the runtime-determined display name of the program for help and error messages. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// Command::new("My Program") - /// .display_name("my_program") - /// # ; - /// ``` - #[must_use] - pub fn display_name(mut self, name: impl IntoResettable<String>) -> Self { - self.display_name = name.into_resettable().into_option(); - self - } - - /// Sets the author(s) for the help message. - /// - /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to - /// automatically set your application's author(s) to the same thing as your - /// crate at compile time. - /// - /// **NOTE:** A custom [`help_template`][Command::help_template] is needed for author to show - /// up. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// Command::new("myprog") - /// .author("Me, me@mymain.com") - /// # ; - /// ``` - #[must_use] - pub fn author(mut self, author: impl IntoResettable<Str>) -> Self { - self.author = author.into_resettable().into_option(); - self - } - - /// Sets the program's description for the short help (`-h`). - /// - /// If [`Command::long_about`] is not specified, this message will be displayed for `--help`. - /// - /// **NOTE:** Only `Command::about` (short format) is used in completion - /// script generation in order to be concise. - /// - /// See also [`crate_description!`](crate::crate_description!). - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// Command::new("myprog") - /// .about("Does really amazing things for great people") - /// # ; - /// ``` - #[must_use] - pub fn about(mut self, about: impl IntoResettable<StyledStr>) -> Self { - self.about = about.into_resettable().into_option(); - self - } - - /// Sets the program's description for the long help (`--help`). - /// - /// If [`Command::about`] is not specified, this message will be displayed for `-h`. - /// - /// **NOTE:** Only [`Command::about`] (short format) is used in completion - /// script generation in order to be concise. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// Command::new("myprog") - /// .long_about( - /// "Does really amazing things to great people. Now let's talk a little - /// more in depth about how this subcommand really works. It may take about - /// a few lines of text, but that's ok!") - /// # ; - /// ``` - /// [`Command::about`]: Command::about() - #[must_use] - pub fn long_about(mut self, long_about: impl IntoResettable<StyledStr>) -> Self { - self.long_about = long_about.into_resettable().into_option(); - self - } - - /// Free-form help text for after auto-generated short help (`-h`). - /// - /// This is often used to describe how to use the arguments, caveats to be noted, or license - /// and contact information. - /// - /// If [`Command::after_long_help`] is not specified, this message will be displayed for `--help`. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// Command::new("myprog") - /// .after_help("Does really amazing things for great people... but be careful with -R!") - /// # ; - /// ``` - /// - #[must_use] - pub fn after_help(mut self, help: impl IntoResettable<StyledStr>) -> Self { - self.after_help = help.into_resettable().into_option(); - self - } - - /// Free-form help text for after auto-generated long help (`--help`). - /// - /// This is often used to describe how to use the arguments, caveats to be noted, or license - /// and contact information. - /// - /// If [`Command::after_help`] is not specified, this message will be displayed for `-h`. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// Command::new("myprog") - /// .after_long_help("Does really amazing things to great people... but be careful with -R, \ - /// like, for real, be careful with this!") - /// # ; - /// ``` - #[must_use] - pub fn after_long_help(mut self, help: impl IntoResettable<StyledStr>) -> Self { - self.after_long_help = help.into_resettable().into_option(); - self - } - - /// Free-form help text for before auto-generated short help (`-h`). - /// - /// This is often used for header, copyright, or license information. - /// - /// If [`Command::before_long_help`] is not specified, this message will be displayed for `--help`. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// Command::new("myprog") - /// .before_help("Some info I'd like to appear before the help info") - /// # ; - /// ``` - #[must_use] - pub fn before_help(mut self, help: impl IntoResettable<StyledStr>) -> Self { - self.before_help = help.into_resettable().into_option(); - self - } - - /// Free-form help text for before auto-generated long help (`--help`). - /// - /// This is often used for header, copyright, or license information. - /// - /// If [`Command::before_help`] is not specified, this message will be displayed for `-h`. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// Command::new("myprog") - /// .before_long_help("Some verbose and long info I'd like to appear before the help info") - /// # ; - /// ``` - #[must_use] - pub fn before_long_help(mut self, help: impl IntoResettable<StyledStr>) -> Self { - self.before_long_help = help.into_resettable().into_option(); - self - } - - /// Sets the version for the short version (`-V`) and help messages. - /// - /// If [`Command::long_version`] is not specified, this message will be displayed for `--version`. - /// - /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to - /// automatically set your application's version to the same thing as your - /// crate at compile time. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// Command::new("myprog") - /// .version("v0.1.24") - /// # ; - /// ``` - #[must_use] - pub fn version(mut self, ver: impl IntoResettable<Str>) -> Self { - self.version = ver.into_resettable().into_option(); - self - } - - /// Sets the version for the long version (`--version`) and help messages. - /// - /// If [`Command::version`] is not specified, this message will be displayed for `-V`. - /// - /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to - /// automatically set your application's version to the same thing as your - /// crate at compile time. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// Command::new("myprog") - /// .long_version( - /// "v0.1.24 - /// commit: abcdef89726d - /// revision: 123 - /// release: 2 - /// binary: myprog") - /// # ; - /// ``` - #[must_use] - pub fn long_version(mut self, ver: impl IntoResettable<Str>) -> Self { - self.long_version = ver.into_resettable().into_option(); - self - } - - /// Overrides the `clap` generated usage string for help and error messages. - /// - /// **NOTE:** Using this setting disables `clap`s "context-aware" usage - /// strings. After this setting is set, this will be *the only* usage string - /// displayed to the user! - /// - /// **NOTE:** Multiple usage lines may be present in the usage argument, but - /// some rules need to be followed to ensure the usage lines are formatted - /// correctly by the default help formatter: - /// - /// - Do not indent the first usage line. - /// - Indent all subsequent usage lines with seven spaces. - /// - The last line must not end with a newline. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .override_usage("myapp [-clDas] <some_file>") - /// # ; - /// ``` - /// - /// Or for multiple usage lines: - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .override_usage( - /// "myapp -X [-a] [-b] <file>\n \ - /// myapp -Y [-c] <file1> <file2>\n \ - /// myapp -Z [-d|-e]" - /// ) - /// # ; - /// ``` - /// - /// [`ArgMatches::usage`]: ArgMatches::usage() - #[must_use] - pub fn override_usage(mut self, usage: impl IntoResettable<StyledStr>) -> Self { - self.usage_str = usage.into_resettable().into_option(); - self - } - - /// Overrides the `clap` generated help message (both `-h` and `--help`). - /// - /// This should only be used when the auto-generated message does not suffice. - /// - /// **NOTE:** This **only** replaces the help message for the current - /// command, meaning if you are using subcommands, those help messages will - /// still be auto-generated unless you specify a [`Command::override_help`] for - /// them as well. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// Command::new("myapp") - /// .override_help("myapp v1.0\n\ - /// Does awesome things\n\ - /// (C) me@mail.com\n\n\ - /// - /// Usage: myapp <opts> <command>\n\n\ - /// - /// Options:\n\ - /// -h, --help Display this message\n\ - /// -V, --version Display version info\n\ - /// -s <stuff> Do something with stuff\n\ - /// -v Be verbose\n\n\ - /// - /// Commands:\n\ - /// help Print this message\n\ - /// work Do some work") - /// # ; - /// ``` - #[must_use] - pub fn override_help(mut self, help: impl IntoResettable<StyledStr>) -> Self { - self.help_str = help.into_resettable().into_option(); - self - } - - /// Sets the help template to be used, overriding the default format. - /// - /// **NOTE:** The template system is by design very simple. Therefore, the - /// tags have to be written in the lowercase and without spacing. - /// - /// Tags are given inside curly brackets. - /// - /// Valid tags are: - /// - /// * `{name}` - Display name for the (sub-)command. - /// * `{bin}` - Binary name.(deprecated) - /// * `{version}` - Version number. - /// * `{author}` - Author information. - /// * `{author-with-newline}` - Author followed by `\n`. - /// * `{author-section}` - Author preceded and followed by `\n`. - /// * `{about}` - General description (from [`Command::about`] or - /// [`Command::long_about`]). - /// * `{about-with-newline}` - About followed by `\n`. - /// * `{about-section}` - About preceded and followed by '\n'. - /// * `{usage-heading}` - Automatically generated usage heading. - /// * `{usage}` - Automatically generated or given usage string. - /// * `{all-args}` - Help for all arguments (options, flags, positional - /// arguments, and subcommands) including titles. - /// * `{options}` - Help for options. - /// * `{positionals}` - Help for positional arguments. - /// * `{subcommands}` - Help for subcommands. - /// * `{tab}` - Standard tab sized used within clap - /// * `{after-help}` - Help from [`Command::after_help`] or [`Command::after_long_help`]. - /// * `{before-help}` - Help from [`Command::before_help`] or [`Command::before_long_help`]. - /// - /// # Examples - /// - /// For a very brief help: - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// Command::new("myprog") - /// .version("1.0") - /// .help_template("{name} ({version}) - {usage}") - /// # ; - /// ``` - /// - /// For showing more application context: - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// Command::new("myprog") - /// .version("1.0") - /// .help_template("\ - /// {before-help}{name} {version} - /// {author-with-newline}{about-with-newline} - /// {usage-heading} {usage} - /// - /// {all-args}{after-help} - /// ") - /// # ; - /// ``` - /// [`Command::about`]: Command::about() - /// [`Command::long_about`]: Command::long_about() - /// [`Command::after_help`]: Command::after_help() - /// [`Command::after_long_help`]: Command::after_long_help() - /// [`Command::before_help`]: Command::before_help() - /// [`Command::before_long_help`]: Command::before_long_help() - #[must_use] - #[cfg(feature = "help")] - pub fn help_template(mut self, s: impl IntoResettable<StyledStr>) -> Self { - self.template = s.into_resettable().into_option(); - self - } - - #[inline] - #[must_use] - pub(crate) fn setting(mut self, setting: AppSettings) -> Self { - self.settings.set(setting); - self - } - - #[inline] - #[must_use] - pub(crate) fn unset_setting(mut self, setting: AppSettings) -> Self { - self.settings.unset(setting); - self - } - - #[inline] - #[must_use] - pub(crate) fn global_setting(mut self, setting: AppSettings) -> Self { - self.settings.set(setting); - self.g_settings.set(setting); - self - } - - #[inline] - #[must_use] - pub(crate) fn unset_global_setting(mut self, setting: AppSettings) -> Self { - self.settings.unset(setting); - self.g_settings.unset(setting); - self - } - - /// Flatten subcommand help into the current command's help - /// - /// This shows a summary of subcommands within the usage and help for the current command, similar to - /// `git stash --help` showing information on `push`, `pop`, etc. - /// To see more information, a user can still pass `--help` to the individual subcommands. - #[inline] - #[must_use] - pub fn flatten_help(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::FlattenHelp) - } else { - self.unset_setting(AppSettings::FlattenHelp) - } - } - - /// Set the default section heading for future args. - /// - /// This will be used for any arg that hasn't had [`Arg::help_heading`] called. - /// - /// This is useful if the default `Options` or `Arguments` headings are - /// not specific enough for one's use case. - /// - /// For subcommands, see [`Command::subcommand_help_heading`] - /// - /// [`Command::arg`]: Command::arg() - /// [`Arg::help_heading`]: crate::Arg::help_heading() - #[inline] - #[must_use] - pub fn next_help_heading(mut self, heading: impl IntoResettable<Str>) -> Self { - self.current_help_heading = heading.into_resettable().into_option(); - self - } - - /// Change the starting value for assigning future display orders for args. - /// - /// This will be used for any arg that hasn't had [`Arg::display_order`] called. - #[inline] - #[must_use] - pub fn next_display_order(mut self, disp_ord: impl IntoResettable<usize>) -> Self { - self.current_disp_ord = disp_ord.into_resettable().into_option(); - self - } - - /// Exit gracefully if no arguments are present (e.g. `$ myprog`). - /// - /// **NOTE:** [`subcommands`] count as arguments - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command}; - /// Command::new("myprog") - /// .arg_required_else_help(true); - /// ``` - /// - /// [`subcommands`]: crate::Command::subcommand() - /// [`Arg::default_value`]: crate::Arg::default_value() - #[inline] - pub fn arg_required_else_help(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::ArgRequiredElseHelp) - } else { - self.unset_setting(AppSettings::ArgRequiredElseHelp) - } - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::allow_hyphen_values`") - )] - pub fn allow_hyphen_values(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::AllowHyphenValues) - } else { - self.unset_setting(AppSettings::AllowHyphenValues) - } - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::allow_negative_numbers`") - )] - pub fn allow_negative_numbers(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::AllowNegativeNumbers) - } else { - self.unset_setting(AppSettings::AllowNegativeNumbers) - } - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::trailing_var_arg`") - )] - pub fn trailing_var_arg(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::TrailingVarArg) - } else { - self.unset_setting(AppSettings::TrailingVarArg) - } - } - - /// Allows one to implement two styles of CLIs where positionals can be used out of order. - /// - /// The first example is a CLI where the second to last positional argument is optional, but - /// the final positional argument is required. Such as `$ prog [optional] <required>` where one - /// of the two following usages is allowed: - /// - /// * `$ prog [optional] <required>` - /// * `$ prog <required>` - /// - /// This would otherwise not be allowed. This is useful when `[optional]` has a default value. - /// - /// **Note:** when using this style of "missing positionals" the final positional *must* be - /// [required] if `--` will not be used to skip to the final positional argument. - /// - /// **Note:** This style also only allows a single positional argument to be "skipped" without - /// the use of `--`. To skip more than one, see the second example. - /// - /// The second example is when one wants to skip multiple optional positional arguments, and use - /// of the `--` operator is OK (but not required if all arguments will be specified anyways). - /// - /// For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where - /// `baz` accepts multiple values (similar to man `ARGS...` style training arguments). - /// - /// With this setting the following invocations are posisble: - /// - /// * `$ prog foo bar baz1 baz2 baz3` - /// * `$ prog foo -- baz1 baz2 baz3` - /// * `$ prog -- baz1 baz2 baz3` - /// - /// # Examples - /// - /// Style number one from above: - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .allow_missing_positional(true) - /// .arg(Arg::new("arg1")) - /// .arg(Arg::new("arg2") - /// .required(true)) - /// .get_matches_from(vec![ - /// "prog", "other" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("arg1"), None); - /// assert_eq!(m.get_one::<String>("arg2").unwrap(), "other"); - /// ``` - /// - /// Now the same example, but using a default value for the first optional positional argument - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .allow_missing_positional(true) - /// .arg(Arg::new("arg1") - /// .default_value("something")) - /// .arg(Arg::new("arg2") - /// .required(true)) - /// .get_matches_from(vec![ - /// "prog", "other" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("arg1").unwrap(), "something"); - /// assert_eq!(m.get_one::<String>("arg2").unwrap(), "other"); - /// ``` - /// - /// Style number two from above: - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .allow_missing_positional(true) - /// .arg(Arg::new("foo")) - /// .arg(Arg::new("bar")) - /// .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..)) - /// .get_matches_from(vec![ - /// "prog", "foo", "bar", "baz1", "baz2", "baz3" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("foo").unwrap(), "foo"); - /// assert_eq!(m.get_one::<String>("bar").unwrap(), "bar"); - /// assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]); - /// ``` - /// - /// Now nofice if we don't specify `foo` or `baz` but use the `--` operator. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .allow_missing_positional(true) - /// .arg(Arg::new("foo")) - /// .arg(Arg::new("bar")) - /// .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..)) - /// .get_matches_from(vec![ - /// "prog", "--", "baz1", "baz2", "baz3" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("foo"), None); - /// assert_eq!(m.get_one::<String>("bar"), None); - /// assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]); - /// ``` - /// - /// [required]: crate::Arg::required() - #[inline] - pub fn allow_missing_positional(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::AllowMissingPositional) - } else { - self.unset_setting(AppSettings::AllowMissingPositional) - } - } -} - -/// # Subcommand-specific Settings -impl Command { - /// Sets the short version of the subcommand flag without the preceding `-`. - /// - /// Allows the subcommand to be used as if it were an [`Arg::short`]. - /// - /// # Examples - /// - /// ``` - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let matches = Command::new("pacman") - /// .subcommand( - /// Command::new("sync").short_flag('S').arg( - /// Arg::new("search") - /// .short('s') - /// .long("search") - /// .action(ArgAction::SetTrue) - /// .help("search remote repositories for matching strings"), - /// ), - /// ) - /// .get_matches_from(vec!["pacman", "-Ss"]); - /// - /// assert_eq!(matches.subcommand_name().unwrap(), "sync"); - /// let sync_matches = matches.subcommand_matches("sync").unwrap(); - /// assert!(sync_matches.get_flag("search")); - /// ``` - /// [`Arg::short`]: Arg::short() - #[must_use] - pub fn short_flag(mut self, short: impl IntoResettable<char>) -> Self { - self.short_flag = short.into_resettable().into_option(); - self - } - - /// Sets the long version of the subcommand flag without the preceding `--`. - /// - /// Allows the subcommand to be used as if it were an [`Arg::long`]. - /// - /// **NOTE:** Any leading `-` characters will be stripped. - /// - /// # Examples - /// - /// To set `long_flag` use a word containing valid UTF-8 codepoints. If you supply a double leading - /// `--` such as `--sync` they will be stripped. Hyphens in the middle of the word; however, - /// will *not* be stripped (i.e. `sync-file` is allowed). - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let matches = Command::new("pacman") - /// .subcommand( - /// Command::new("sync").long_flag("sync").arg( - /// Arg::new("search") - /// .short('s') - /// .long("search") - /// .action(ArgAction::SetTrue) - /// .help("search remote repositories for matching strings"), - /// ), - /// ) - /// .get_matches_from(vec!["pacman", "--sync", "--search"]); - /// - /// assert_eq!(matches.subcommand_name().unwrap(), "sync"); - /// let sync_matches = matches.subcommand_matches("sync").unwrap(); - /// assert!(sync_matches.get_flag("search")); - /// ``` - /// - /// [`Arg::long`]: Arg::long() - #[must_use] - pub fn long_flag(mut self, long: impl Into<Str>) -> Self { - self.long_flag = Some(long.into()); - self - } - - /// Sets a hidden alias to this subcommand. - /// - /// This allows the subcommand to be accessed via *either* the original name, or this given - /// alias. This is more efficient and easier than creating multiple hidden subcommands as one - /// only needs to check for the existence of this command, and not all aliased variants. - /// - /// **NOTE:** Aliases defined with this method are *hidden* from the help - /// message. If you're looking for aliases that will be displayed in the help - /// message, see [`Command::visible_alias`]. - /// - /// **NOTE:** When using aliases and checking for the existence of a - /// particular subcommand within an [`ArgMatches`] struct, one only needs to - /// search for the original name and not all aliases. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test") - /// .alias("do-stuff")) - /// .get_matches_from(vec!["myprog", "do-stuff"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`Command::visible_alias`]: Command::visible_alias() - #[must_use] - pub fn alias(mut self, name: impl IntoResettable<Str>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - self.aliases.push((name, false)); - } else { - self.aliases.clear(); - } - self - } - - /// Add an alias, which functions as "hidden" short flag subcommand - /// - /// This will automatically dispatch as if this subcommand was used. This is more efficient, - /// and easier than creating multiple hidden subcommands as one only needs to check for the - /// existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").short_flag('t') - /// .short_flag_alias('d')) - /// .get_matches_from(vec!["myprog", "-d"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - #[must_use] - pub fn short_flag_alias(mut self, name: impl IntoResettable<char>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - debug_assert!(name != '-', "short alias name cannot be `-`"); - self.short_flag_aliases.push((name, false)); - } else { - self.short_flag_aliases.clear(); - } - self - } - - /// Add an alias, which functions as a "hidden" long flag subcommand. - /// - /// This will automatically dispatch as if this subcommand was used. This is more efficient, - /// and easier than creating multiple hidden subcommands as one only needs to check for the - /// existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").long_flag("test") - /// .long_flag_alias("testing")) - /// .get_matches_from(vec!["myprog", "--testing"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - #[must_use] - pub fn long_flag_alias(mut self, name: impl IntoResettable<Str>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - self.long_flag_aliases.push((name, false)); - } else { - self.long_flag_aliases.clear(); - } - self - } - - /// Sets multiple hidden aliases to this subcommand. - /// - /// This allows the subcommand to be accessed via *either* the original name or any of the - /// given aliases. This is more efficient, and easier than creating multiple hidden subcommands - /// as one only needs to check for the existence of this command and not all aliased variants. - /// - /// **NOTE:** Aliases defined with this method are *hidden* from the help - /// message. If looking for aliases that will be displayed in the help - /// message, see [`Command::visible_aliases`]. - /// - /// **NOTE:** When using aliases and checking for the existence of a - /// particular subcommand within an [`ArgMatches`] struct, one only needs to - /// search for the original name and not all aliases. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test") - /// .aliases(["do-stuff", "do-tests", "tests"])) - /// .arg(Arg::new("input") - /// .help("the file to add") - /// .required(false)) - /// .get_matches_from(vec!["myprog", "do-tests"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`Command::visible_aliases`]: Command::visible_aliases() - #[must_use] - pub fn aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { - self.aliases - .extend(names.into_iter().map(|n| (n.into(), false))); - self - } - - /// Add aliases, which function as "hidden" short flag subcommands. - /// - /// These will automatically dispatch as if this subcommand was used. This is more efficient, - /// and easier than creating multiple hidden subcommands as one only needs to check for the - /// existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").short_flag('t') - /// .short_flag_aliases(['a', 'b', 'c'])) - /// .arg(Arg::new("input") - /// .help("the file to add") - /// .required(false)) - /// .get_matches_from(vec!["myprog", "-a"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - #[must_use] - pub fn short_flag_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self { - for s in names { - debug_assert!(s != '-', "short alias name cannot be `-`"); - self.short_flag_aliases.push((s, false)); - } - self - } - - /// Add aliases, which function as "hidden" long flag subcommands. - /// - /// These will automatically dispatch as if this subcommand was used. This is more efficient, - /// and easier than creating multiple hidden subcommands as one only needs to check for the - /// existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").long_flag("test") - /// .long_flag_aliases(["testing", "testall", "test_all"])) - /// .arg(Arg::new("input") - /// .help("the file to add") - /// .required(false)) - /// .get_matches_from(vec!["myprog", "--testing"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - #[must_use] - pub fn long_flag_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { - for s in names { - self = self.long_flag_alias(s) - } - self - } - - /// Sets a visible alias to this subcommand. - /// - /// This allows the subcommand to be accessed via *either* the - /// original name or the given alias. This is more efficient and easier - /// than creating hidden subcommands as one only needs to check for - /// the existence of this command and not all aliased variants. - /// - /// **NOTE:** The alias defined with this method is *visible* from the help - /// message and displayed as if it were just another regular subcommand. If - /// looking for an alias that will not be displayed in the help message, see - /// [`Command::alias`]. - /// - /// **NOTE:** When using aliases and checking for the existence of a - /// particular subcommand within an [`ArgMatches`] struct, one only needs to - /// search for the original name and not all aliases. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test") - /// .visible_alias("do-stuff")) - /// .get_matches_from(vec!["myprog", "do-stuff"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`Command::alias`]: Command::alias() - #[must_use] - pub fn visible_alias(mut self, name: impl IntoResettable<Str>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - self.aliases.push((name, true)); - } else { - self.aliases.clear(); - } - self - } - - /// Add an alias, which functions as "visible" short flag subcommand - /// - /// This will automatically dispatch as if this subcommand was used. This is more efficient, - /// and easier than creating multiple hidden subcommands as one only needs to check for the - /// existence of this command, and not all variants. - /// - /// See also [`Command::short_flag_alias`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").short_flag('t') - /// .visible_short_flag_alias('d')) - /// .get_matches_from(vec!["myprog", "-d"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`Command::short_flag_alias`]: Command::short_flag_alias() - #[must_use] - pub fn visible_short_flag_alias(mut self, name: impl IntoResettable<char>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - debug_assert!(name != '-', "short alias name cannot be `-`"); - self.short_flag_aliases.push((name, true)); - } else { - self.short_flag_aliases.clear(); - } - self - } - - /// Add an alias, which functions as a "visible" long flag subcommand. - /// - /// This will automatically dispatch as if this subcommand was used. This is more efficient, - /// and easier than creating multiple hidden subcommands as one only needs to check for the - /// existence of this command, and not all variants. - /// - /// See also [`Command::long_flag_alias`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").long_flag("test") - /// .visible_long_flag_alias("testing")) - /// .get_matches_from(vec!["myprog", "--testing"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`Command::long_flag_alias`]: Command::long_flag_alias() - #[must_use] - pub fn visible_long_flag_alias(mut self, name: impl IntoResettable<Str>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - self.long_flag_aliases.push((name, true)); - } else { - self.long_flag_aliases.clear(); - } - self - } - - /// Sets multiple visible aliases to this subcommand. - /// - /// This allows the subcommand to be accessed via *either* the - /// original name or any of the given aliases. This is more efficient and easier - /// than creating multiple hidden subcommands as one only needs to check for - /// the existence of this command and not all aliased variants. - /// - /// **NOTE:** The alias defined with this method is *visible* from the help - /// message and displayed as if it were just another regular subcommand. If - /// looking for an alias that will not be displayed in the help message, see - /// [`Command::alias`]. - /// - /// **NOTE:** When using aliases, and checking for the existence of a - /// particular subcommand within an [`ArgMatches`] struct, one only needs to - /// search for the original name and not all aliases. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test") - /// .visible_aliases(["do-stuff", "tests"])) - /// .get_matches_from(vec!["myprog", "do-stuff"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`Command::alias`]: Command::alias() - #[must_use] - pub fn visible_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { - self.aliases - .extend(names.into_iter().map(|n| (n.into(), true))); - self - } - - /// Add aliases, which function as *visible* short flag subcommands. - /// - /// See [`Command::short_flag_aliases`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").short_flag('b') - /// .visible_short_flag_aliases(['t'])) - /// .get_matches_from(vec!["myprog", "-t"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`Command::short_flag_aliases`]: Command::short_flag_aliases() - #[must_use] - pub fn visible_short_flag_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self { - for s in names { - debug_assert!(s != '-', "short alias name cannot be `-`"); - self.short_flag_aliases.push((s, true)); - } - self - } - - /// Add aliases, which function as *visible* long flag subcommands. - /// - /// See [`Command::long_flag_aliases`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").long_flag("test") - /// .visible_long_flag_aliases(["testing", "testall", "test_all"])) - /// .get_matches_from(vec!["myprog", "--testing"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`Command::long_flag_aliases`]: Command::long_flag_aliases() - #[must_use] - pub fn visible_long_flag_aliases( - mut self, - names: impl IntoIterator<Item = impl Into<Str>>, - ) -> Self { - for s in names { - self = self.visible_long_flag_alias(s); - } - self - } - - /// Set the placement of this subcommand within the help. - /// - /// Subcommands with a lower value will be displayed first in the help message. - /// Those with the same display order will be sorted. - /// - /// `Command`s are automatically assigned a display order based on the order they are added to - /// their parent [`Command`]. - /// Overriding this is helpful when the order commands are added in isn't the same as the - /// display order, whether in one-off cases or to automatically sort commands. - /// - /// # Examples - /// - /// ```rust - /// # #[cfg(feature = "help")] { - /// # use clap_builder as clap; - /// # use clap::{Command, }; - /// let m = Command::new("cust-ord") - /// .subcommand(Command::new("beta") - /// .display_order(0) // Sort - /// .about("Some help and text")) - /// .subcommand(Command::new("alpha") - /// .display_order(0) // Sort - /// .about("I should be first!")) - /// .get_matches_from(vec![ - /// "cust-ord", "--help" - /// ]); - /// # } - /// ``` - /// - /// The above example displays the following help message - /// - /// ```text - /// cust-ord - /// - /// Usage: cust-ord [OPTIONS] - /// - /// Commands: - /// alpha I should be first! - /// beta Some help and text - /// help Print help for the subcommand(s) - /// - /// Options: - /// -h, --help Print help - /// -V, --version Print version - /// ``` - #[inline] - #[must_use] - pub fn display_order(mut self, ord: impl IntoResettable<usize>) -> Self { - self.disp_ord = ord.into_resettable().into_option(); - self - } - - /// Specifies that this [`subcommand`] should be hidden from help messages - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .subcommand( - /// Command::new("test").hide(true) - /// ) - /// # ; - /// ``` - /// - /// [`subcommand`]: crate::Command::subcommand() - #[inline] - pub fn hide(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::Hidden) - } else { - self.unset_setting(AppSettings::Hidden) - } - } - - /// If no [`subcommand`] is present at runtime, error and exit gracefully. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, error::ErrorKind}; - /// let err = Command::new("myprog") - /// .subcommand_required(true) - /// .subcommand(Command::new("test")) - /// .try_get_matches_from(vec![ - /// "myprog", - /// ]); - /// assert!(err.is_err()); - /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand); - /// # ; - /// ``` - /// - /// [`subcommand`]: crate::Command::subcommand() - pub fn subcommand_required(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::SubcommandRequired) - } else { - self.unset_setting(AppSettings::SubcommandRequired) - } - } - - /// Assume unexpected positional arguments are a [`subcommand`]. - /// - /// Arguments will be stored in the `""` argument in the [`ArgMatches`] - /// - /// **NOTE:** Use this setting with caution, - /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand) - /// will **not** cause an error and instead be treated as a potential subcommand. - /// One should check for such cases manually and inform the user appropriately. - /// - /// **NOTE:** A built-in subcommand will be parsed as an external subcommand when escaped with - /// `--`. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use std::ffi::OsString; - /// # use clap::Command; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .allow_external_subcommands(true) - /// .get_matches_from(vec![ - /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" - /// ]); - /// - /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty - /// // string argument name - /// match m.subcommand() { - /// Some((external, ext_m)) => { - /// let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect(); - /// assert_eq!(external, "subcmd"); - /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); - /// }, - /// _ => {}, - /// } - /// ``` - /// - /// [`subcommand`]: crate::Command::subcommand() - /// [`ArgMatches`]: crate::ArgMatches - /// [`ErrorKind::UnknownArgument`]: crate::error::ErrorKind::UnknownArgument - pub fn allow_external_subcommands(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::AllowExternalSubcommands) - } else { - self.unset_setting(AppSettings::AllowExternalSubcommands) - } - } - - /// Specifies how to parse external subcommand arguments. - /// - /// The default parser is for `OsString`. This can be used to switch it to `String` or another - /// type. - /// - /// **NOTE:** Setting this requires [`Command::allow_external_subcommands`] - /// - /// # Examples - /// - /// ```rust - /// # #[cfg(unix)] { - /// # use clap_builder as clap; - /// # use std::ffi::OsString; - /// # use clap::Command; - /// # use clap::value_parser; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .allow_external_subcommands(true) - /// .get_matches_from(vec![ - /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" - /// ]); - /// - /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty - /// // string argument name - /// match m.subcommand() { - /// Some((external, ext_m)) => { - /// let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect(); - /// assert_eq!(external, "subcmd"); - /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); - /// }, - /// _ => {}, - /// } - /// # } - /// ``` - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// # use clap::value_parser; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .external_subcommand_value_parser(value_parser!(String)) - /// .get_matches_from(vec![ - /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" - /// ]); - /// - /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty - /// // string argument name - /// match m.subcommand() { - /// Some((external, ext_m)) => { - /// let ext_args: Vec<_> = ext_m.get_many::<String>("").unwrap().collect(); - /// assert_eq!(external, "subcmd"); - /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); - /// }, - /// _ => {}, - /// } - /// ``` - /// - /// [`subcommands`]: crate::Command::subcommand() - pub fn external_subcommand_value_parser( - mut self, - parser: impl IntoResettable<super::ValueParser>, - ) -> Self { - self.external_value_parser = parser.into_resettable().into_option(); - self - } - - /// Specifies that use of an argument prevents the use of [`subcommands`]. - /// - /// By default `clap` allows arguments between subcommands such - /// as `<cmd> [cmd_args] <subcmd> [subcmd_args] <subsubcmd> [subsubcmd_args]`. - /// - /// This setting disables that functionality and says that arguments can - /// only follow the *final* subcommand. For instance using this setting - /// makes only the following invocations possible: - /// - /// * `<cmd> <subcmd> <subsubcmd> [subsubcmd_args]` - /// * `<cmd> <subcmd> [subcmd_args]` - /// * `<cmd> [cmd_args]` - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// Command::new("myprog") - /// .args_conflicts_with_subcommands(true); - /// ``` - /// - /// [`subcommands`]: crate::Command::subcommand() - pub fn args_conflicts_with_subcommands(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::ArgsNegateSubcommands) - } else { - self.unset_setting(AppSettings::ArgsNegateSubcommands) - } - } - - /// Prevent subcommands from being consumed as an arguments value. - /// - /// By default, if an option taking multiple values is followed by a subcommand, the - /// subcommand will be parsed as another value. - /// - /// ```text - /// cmd --foo val1 val2 subcommand - /// --------- ---------- - /// values another value - /// ``` - /// - /// This setting instructs the parser to stop when encountering a subcommand instead of - /// greedily consuming arguments. - /// - /// ```text - /// cmd --foo val1 val2 subcommand - /// --------- ---------- - /// values subcommand - /// ``` - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, ArgAction}; - /// let cmd = Command::new("cmd").subcommand(Command::new("sub")).arg( - /// Arg::new("arg") - /// .long("arg") - /// .num_args(1..) - /// .action(ArgAction::Set), - /// ); - /// - /// let matches = cmd - /// .clone() - /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"]) - /// .unwrap(); - /// assert_eq!( - /// matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(), - /// &["1", "2", "3", "sub"] - /// ); - /// assert!(matches.subcommand_matches("sub").is_none()); - /// - /// let matches = cmd - /// .subcommand_precedence_over_arg(true) - /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"]) - /// .unwrap(); - /// assert_eq!( - /// matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(), - /// &["1", "2", "3"] - /// ); - /// assert!(matches.subcommand_matches("sub").is_some()); - /// ``` - pub fn subcommand_precedence_over_arg(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::SubcommandPrecedenceOverArg) - } else { - self.unset_setting(AppSettings::SubcommandPrecedenceOverArg) - } - } - - /// Allows [`subcommands`] to override all requirements of the parent command. - /// - /// For example, if you had a subcommand or top level application with a required argument - /// that is only required as long as there is no subcommand present, - /// using this setting would allow you to set those arguments to [`Arg::required(true)`] - /// and yet receive no error so long as the user uses a valid subcommand instead. - /// - /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements) - /// - /// # Examples - /// - /// This first example shows that it is an error to not use a required argument - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind}; - /// let err = Command::new("myprog") - /// .subcommand_negates_reqs(true) - /// .arg(Arg::new("opt").required(true)) - /// .subcommand(Command::new("test")) - /// .try_get_matches_from(vec![ - /// "myprog" - /// ]); - /// assert!(err.is_err()); - /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// # ; - /// ``` - /// - /// This next example shows that it is no longer error to not use a required argument if a - /// valid subcommand is used. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, error::ErrorKind}; - /// let noerr = Command::new("myprog") - /// .subcommand_negates_reqs(true) - /// .arg(Arg::new("opt").required(true)) - /// .subcommand(Command::new("test")) - /// .try_get_matches_from(vec![ - /// "myprog", "test" - /// ]); - /// assert!(noerr.is_ok()); - /// # ; - /// ``` - /// - /// [`Arg::required(true)`]: crate::Arg::required() - /// [`subcommands`]: crate::Command::subcommand() - pub fn subcommand_negates_reqs(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::SubcommandsNegateReqs) - } else { - self.unset_setting(AppSettings::SubcommandsNegateReqs) - } - } - - /// Multiple-personality program dispatched on the binary name (`argv[0]`) - /// - /// A "multicall" executable is a single executable - /// that contains a variety of applets, - /// and decides which applet to run based on the name of the file. - /// The executable can be called from different names by creating hard links - /// or symbolic links to it. - /// - /// This is desirable for: - /// - Easy distribution, a single binary that can install hardlinks to access the different - /// personalities. - /// - Minimal binary size by sharing common code (e.g. standard library, clap) - /// - Custom shells or REPLs where there isn't a single top-level command - /// - /// Setting `multicall` will cause - /// - `argv[0]` to be stripped to the base name and parsed as the first argument, as if - /// [`Command::no_binary_name`][Command::no_binary_name] was set. - /// - Help and errors to report subcommands as if they were the top-level command - /// - /// When the subcommand is not present, there are several strategies you may employ, depending - /// on your needs: - /// - Let the error percolate up normally - /// - Print a specialized error message using the - /// [`Error::context`][crate::Error::context] - /// - Print the [help][Command::write_help] but this might be ambiguous - /// - Disable `multicall` and re-parse it - /// - Disable `multicall` and re-parse it with a specific subcommand - /// - /// When detecting the error condition, the [`ErrorKind`] isn't sufficient as a sub-subcommand - /// might report the same error. Enable - /// [`allow_external_subcommands`][Command::allow_external_subcommands] if you want to specifically - /// get the unrecognized binary name. - /// - /// **NOTE:** Multicall can't be used with [`no_binary_name`] since they interpret - /// the command name in incompatible ways. - /// - /// **NOTE:** The multicall command cannot have arguments. - /// - /// **NOTE:** Applets are slightly semantically different from subcommands, - /// so it's recommended to use [`Command::subcommand_help_heading`] and - /// [`Command::subcommand_value_name`] to change the descriptive text as above. - /// - /// # Examples - /// - /// `hostname` is an example of a multicall executable. - /// Both `hostname` and `dnsdomainname` are provided by the same executable - /// and which behaviour to use is based on the executable file name. - /// - /// This is desirable when the executable has a primary purpose - /// but there is related functionality that would be convenient to provide - /// and implement it to be in the same executable. - /// - /// The name of the cmd is essentially unused - /// and may be the same as the name of a subcommand. - /// - /// The names of the immediate subcommands of the Command - /// are matched against the basename of the first argument, - /// which is conventionally the path of the executable. - /// - /// This does not allow the subcommand to be passed as the first non-path argument. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, error::ErrorKind}; - /// let mut cmd = Command::new("hostname") - /// .multicall(true) - /// .subcommand(Command::new("hostname")) - /// .subcommand(Command::new("dnsdomainname")); - /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/hostname", "dnsdomainname"]); - /// assert!(m.is_err()); - /// assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// let m = cmd.get_matches_from(&["/usr/bin/dnsdomainname"]); - /// assert_eq!(m.subcommand_name(), Some("dnsdomainname")); - /// ``` - /// - /// Busybox is another common example of a multicall executable - /// with a subcommmand for each applet that can be run directly, - /// e.g. with the `cat` applet being run by running `busybox cat`, - /// or with `cat` as a link to the `busybox` binary. - /// - /// This is desirable when the launcher program has additional options - /// or it is useful to run the applet without installing a symlink - /// e.g. to test the applet without installing it - /// or there may already be a command of that name installed. - /// - /// To make an applet usable as both a multicall link and a subcommand - /// the subcommands must be defined both in the top-level Command - /// and as subcommands of the "main" applet. - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// fn applet_commands() -> [Command; 2] { - /// [Command::new("true"), Command::new("false")] - /// } - /// let mut cmd = Command::new("busybox") - /// .multicall(true) - /// .subcommand( - /// Command::new("busybox") - /// .subcommand_value_name("APPLET") - /// .subcommand_help_heading("APPLETS") - /// .subcommands(applet_commands()), - /// ) - /// .subcommands(applet_commands()); - /// // When called from the executable's canonical name - /// // its applets can be matched as subcommands. - /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/busybox", "true"]).unwrap(); - /// assert_eq!(m.subcommand_name(), Some("busybox")); - /// assert_eq!(m.subcommand().unwrap().1.subcommand_name(), Some("true")); - /// // When called from a link named after an applet that applet is matched. - /// let m = cmd.get_matches_from(&["/usr/bin/true"]); - /// assert_eq!(m.subcommand_name(), Some("true")); - /// ``` - /// - /// [`no_binary_name`]: crate::Command::no_binary_name - /// [`Command::subcommand_value_name`]: crate::Command::subcommand_value_name - /// [`Command::subcommand_help_heading`]: crate::Command::subcommand_help_heading - #[inline] - pub fn multicall(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::Multicall) - } else { - self.unset_setting(AppSettings::Multicall) - } - } - - /// Sets the value name used for subcommands when printing usage and help. - /// - /// By default, this is "COMMAND". - /// - /// See also [`Command::subcommand_help_heading`] - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .subcommand(Command::new("sub1")) - /// .print_help() - /// # ; - /// ``` - /// - /// will produce - /// - /// ```text - /// myprog - /// - /// Usage: myprog [COMMAND] - /// - /// Commands: - /// help Print this message or the help of the given subcommand(s) - /// sub1 - /// - /// Options: - /// -h, --help Print help - /// -V, --version Print version - /// ``` - /// - /// but usage of `subcommand_value_name` - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .subcommand(Command::new("sub1")) - /// .subcommand_value_name("THING") - /// .print_help() - /// # ; - /// ``` - /// - /// will produce - /// - /// ```text - /// myprog - /// - /// Usage: myprog [THING] - /// - /// Commands: - /// help Print this message or the help of the given subcommand(s) - /// sub1 - /// - /// Options: - /// -h, --help Print help - /// -V, --version Print version - /// ``` - #[must_use] - pub fn subcommand_value_name(mut self, value_name: impl IntoResettable<Str>) -> Self { - self.subcommand_value_name = value_name.into_resettable().into_option(); - self - } - - /// Sets the help heading used for subcommands when printing usage and help. - /// - /// By default, this is "Commands". - /// - /// See also [`Command::subcommand_value_name`] - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .subcommand(Command::new("sub1")) - /// .print_help() - /// # ; - /// ``` - /// - /// will produce - /// - /// ```text - /// myprog - /// - /// Usage: myprog [COMMAND] - /// - /// Commands: - /// help Print this message or the help of the given subcommand(s) - /// sub1 - /// - /// Options: - /// -h, --help Print help - /// -V, --version Print version - /// ``` - /// - /// but usage of `subcommand_help_heading` - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .subcommand(Command::new("sub1")) - /// .subcommand_help_heading("Things") - /// .print_help() - /// # ; - /// ``` - /// - /// will produce - /// - /// ```text - /// myprog - /// - /// Usage: myprog [COMMAND] - /// - /// Things: - /// help Print this message or the help of the given subcommand(s) - /// sub1 - /// - /// Options: - /// -h, --help Print help - /// -V, --version Print version - /// ``` - #[must_use] - pub fn subcommand_help_heading(mut self, heading: impl IntoResettable<Str>) -> Self { - self.subcommand_heading = heading.into_resettable().into_option(); - self - } -} - -/// # Reflection -impl Command { - #[inline] - #[cfg(feature = "usage")] - pub(crate) fn get_usage_name(&self) -> Option<&str> { - self.usage_name.as_deref() - } - - #[inline] - #[cfg(feature = "usage")] - pub(crate) fn get_usage_name_fallback(&self) -> &str { - self.get_usage_name() - .unwrap_or_else(|| self.get_bin_name_fallback()) - } - - #[inline] - #[cfg(not(feature = "usage"))] - #[allow(dead_code)] - pub(crate) fn get_usage_name_fallback(&self) -> &str { - self.get_bin_name_fallback() - } - - /// Get the name of the binary. - #[inline] - pub fn get_display_name(&self) -> Option<&str> { - self.display_name.as_deref() - } - - /// Get the name of the binary. - #[inline] - pub fn get_bin_name(&self) -> Option<&str> { - self.bin_name.as_deref() - } - - /// Get the name of the binary. - #[inline] - pub(crate) fn get_bin_name_fallback(&self) -> &str { - self.bin_name.as_deref().unwrap_or_else(|| self.get_name()) - } - - /// Set binary name. Uses `&mut self` instead of `self`. - pub fn set_bin_name(&mut self, name: impl Into<String>) { - self.bin_name = Some(name.into()); - } - - /// Get the name of the cmd. - #[inline] - pub fn get_name(&self) -> &str { - self.name.as_str() - } - - #[inline] - #[cfg(debug_assertions)] - pub(crate) fn get_name_str(&self) -> &Str { - &self.name - } - - /// Get the version of the cmd. - #[inline] - pub fn get_version(&self) -> Option<&str> { - self.version.as_deref() - } - - /// Get the long version of the cmd. - #[inline] - pub fn get_long_version(&self) -> Option<&str> { - self.long_version.as_deref() - } - - /// Get the authors of the cmd. - #[inline] - pub fn get_author(&self) -> Option<&str> { - self.author.as_deref() - } - - /// Get the short flag of the subcommand. - #[inline] - pub fn get_short_flag(&self) -> Option<char> { - self.short_flag - } - - /// Get the long flag of the subcommand. - #[inline] - pub fn get_long_flag(&self) -> Option<&str> { - self.long_flag.as_deref() - } - - /// Get the help message specified via [`Command::about`]. - /// - /// [`Command::about`]: Command::about() - #[inline] - pub fn get_about(&self) -> Option<&StyledStr> { - self.about.as_ref() - } - - /// Get the help message specified via [`Command::long_about`]. - /// - /// [`Command::long_about`]: Command::long_about() - #[inline] - pub fn get_long_about(&self) -> Option<&StyledStr> { - self.long_about.as_ref() - } - - /// Get the custom section heading specified via [`Command::flatten_help`]. - #[inline] - pub fn is_flatten_help_set(&self) -> bool { - self.is_set(AppSettings::FlattenHelp) - } - - /// Get the custom section heading specified via [`Command::next_help_heading`]. - /// - /// [`Command::help_heading`]: Command::help_heading() - #[inline] - pub fn get_next_help_heading(&self) -> Option<&str> { - self.current_help_heading.as_deref() - } - - /// Iterate through the *visible* aliases for this subcommand. - #[inline] - pub fn get_visible_aliases(&self) -> impl Iterator<Item = &str> + '_ { - self.aliases - .iter() - .filter(|(_, vis)| *vis) - .map(|a| a.0.as_str()) - } - - /// Iterate through the *visible* short aliases for this subcommand. - #[inline] - pub fn get_visible_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ { - self.short_flag_aliases - .iter() - .filter(|(_, vis)| *vis) - .map(|a| a.0) - } - - /// Iterate through the *visible* long aliases for this subcommand. - #[inline] - pub fn get_visible_long_flag_aliases(&self) -> impl Iterator<Item = &str> + '_ { - self.long_flag_aliases - .iter() - .filter(|(_, vis)| *vis) - .map(|a| a.0.as_str()) - } - - /// Iterate through the set of *all* the aliases for this subcommand, both visible and hidden. - #[inline] - pub fn get_all_aliases(&self) -> impl Iterator<Item = &str> + '_ { - self.aliases.iter().map(|a| a.0.as_str()) - } - - /// Iterate through the set of *all* the short aliases for this subcommand, both visible and hidden. - #[inline] - pub fn get_all_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ { - self.short_flag_aliases.iter().map(|a| a.0) - } - - /// Iterate through the set of *all* the long aliases for this subcommand, both visible and hidden. - #[inline] - pub fn get_all_long_flag_aliases(&self) -> impl Iterator<Item = &str> + '_ { - self.long_flag_aliases.iter().map(|a| a.0.as_str()) - } - - #[inline] - pub(crate) fn is_set(&self, s: AppSettings) -> bool { - self.settings.is_set(s) || self.g_settings.is_set(s) - } - - /// Should we color the output? - pub fn get_color(&self) -> ColorChoice { - debug!("Command::color: Color setting..."); - - if cfg!(feature = "color") { - if self.is_set(AppSettings::ColorNever) { - debug!("Never"); - ColorChoice::Never - } else if self.is_set(AppSettings::ColorAlways) { - debug!("Always"); - ColorChoice::Always - } else { - debug!("Auto"); - ColorChoice::Auto - } - } else { - ColorChoice::Never - } - } - - /// Return the current `Styles` for the `Command` - #[inline] - pub fn get_styles(&self) -> &Styles { - self.app_ext.get().unwrap_or_default() - } - - /// Iterate through the set of subcommands, getting a reference to each. - #[inline] - pub fn get_subcommands(&self) -> impl Iterator<Item = &Command> { - self.subcommands.iter() - } - - /// Iterate through the set of subcommands, getting a mutable reference to each. - #[inline] - pub fn get_subcommands_mut(&mut self) -> impl Iterator<Item = &mut Command> { - self.subcommands.iter_mut() - } - - /// Returns `true` if this `Command` has subcommands. - #[inline] - pub fn has_subcommands(&self) -> bool { - !self.subcommands.is_empty() - } - - /// Returns the help heading for listing subcommands. - #[inline] - pub fn get_subcommand_help_heading(&self) -> Option<&str> { - self.subcommand_heading.as_deref() - } - - /// Returns the subcommand value name. - #[inline] - pub fn get_subcommand_value_name(&self) -> Option<&str> { - self.subcommand_value_name.as_deref() - } - - /// Returns the help heading for listing subcommands. - #[inline] - pub fn get_before_help(&self) -> Option<&StyledStr> { - self.before_help.as_ref() - } - - /// Returns the help heading for listing subcommands. - #[inline] - pub fn get_before_long_help(&self) -> Option<&StyledStr> { - self.before_long_help.as_ref() - } - - /// Returns the help heading for listing subcommands. - #[inline] - pub fn get_after_help(&self) -> Option<&StyledStr> { - self.after_help.as_ref() - } - - /// Returns the help heading for listing subcommands. - #[inline] - pub fn get_after_long_help(&self) -> Option<&StyledStr> { - self.after_long_help.as_ref() - } - - /// Find subcommand such that its name or one of aliases equals `name`. - /// - /// This does not recurse through subcommands of subcommands. - #[inline] - pub fn find_subcommand(&self, name: impl AsRef<std::ffi::OsStr>) -> Option<&Command> { - let name = name.as_ref(); - self.get_subcommands().find(|s| s.aliases_to(name)) - } - - /// Find subcommand such that its name or one of aliases equals `name`, returning - /// a mutable reference to the subcommand. - /// - /// This does not recurse through subcommands of subcommands. - #[inline] - pub fn find_subcommand_mut( - &mut self, - name: impl AsRef<std::ffi::OsStr>, - ) -> Option<&mut Command> { - let name = name.as_ref(); - self.get_subcommands_mut().find(|s| s.aliases_to(name)) - } - - /// Iterate through the set of groups. - #[inline] - pub fn get_groups(&self) -> impl Iterator<Item = &ArgGroup> { - self.groups.iter() - } - - /// Iterate through the set of arguments. - #[inline] - pub fn get_arguments(&self) -> impl Iterator<Item = &Arg> { - self.args.args() - } - - /// Iterate through the *positionals* arguments. - #[inline] - pub fn get_positionals(&self) -> impl Iterator<Item = &Arg> { - self.get_arguments().filter(|a| a.is_positional()) - } - - /// Iterate through the *options*. - pub fn get_opts(&self) -> impl Iterator<Item = &Arg> { - self.get_arguments() - .filter(|a| a.is_takes_value_set() && !a.is_positional()) - } - - /// Get a list of all arguments the given argument conflicts with. - /// - /// If the provided argument is declared as global, the conflicts will be determined - /// based on the propagation rules of global arguments. - /// - /// ### Panics - /// - /// If the given arg contains a conflict with an argument that is unknown to - /// this `Command`. - pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator - { - if arg.is_global_set() { - self.get_global_arg_conflicts_with(arg) - } else { - let mut result = Vec::new(); - for id in arg.blacklist.iter() { - if let Some(arg) = self.find(id) { - result.push(arg); - } else if let Some(group) = self.find_group(id) { - result.extend( - self.unroll_args_in_group(&group.id) - .iter() - .map(|id| self.find(id).expect(INTERNAL_ERROR_MSG)), - ); - } else { - panic!("Command::get_arg_conflicts_with: The passed arg conflicts with an arg unknown to the cmd"); - } - } - result - } - } - - // Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with. - // - // This behavior follows the propagation rules of global arguments. - // It is useful for finding conflicts for arguments declared as global. - // - // ### Panics - // - // If the given arg contains a conflict with an argument that is unknown to - // this `Command`. - fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator - { - arg.blacklist - .iter() - .map(|id| { - self.args - .args() - .chain( - self.get_subcommands_containing(arg) - .iter() - .flat_map(|x| x.args.args()), - ) - .find(|arg| arg.get_id() == id) - .expect( - "Command::get_arg_conflicts_with: \ - The passed arg conflicts with an arg unknown to the cmd", - ) - }) - .collect() - } - - // Get a list of subcommands which contain the provided Argument - // - // This command will only include subcommands in its list for which the subcommands - // parent also contains the Argument. - // - // This search follows the propagation rules of global arguments. - // It is useful to finding subcommands, that have inherited a global argument. - // - // **NOTE:** In this case only Sucommand_1 will be included - // Subcommand_1 (contains Arg) - // Subcommand_1.1 (doesn't contain Arg) - // Subcommand_1.1.1 (contains Arg) - // - fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&Self> { - let mut vec = std::vec::Vec::new(); - for idx in 0..self.subcommands.len() { - if self.subcommands[idx] - .args - .args() - .any(|ar| ar.get_id() == arg.get_id()) - { - vec.push(&self.subcommands[idx]); - vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg)); - } - } - vec - } - - /// Report whether [`Command::no_binary_name`] is set - pub fn is_no_binary_name_set(&self) -> bool { - self.is_set(AppSettings::NoBinaryName) - } - - /// Report whether [`Command::ignore_errors`] is set - pub(crate) fn is_ignore_errors_set(&self) -> bool { - self.is_set(AppSettings::IgnoreErrors) - } - - /// Report whether [`Command::dont_delimit_trailing_values`] is set - pub fn is_dont_delimit_trailing_values_set(&self) -> bool { - self.is_set(AppSettings::DontDelimitTrailingValues) - } - - /// Report whether [`Command::disable_version_flag`] is set - pub fn is_disable_version_flag_set(&self) -> bool { - self.is_set(AppSettings::DisableVersionFlag) - || (self.version.is_none() && self.long_version.is_none()) - } - - /// Report whether [`Command::propagate_version`] is set - pub fn is_propagate_version_set(&self) -> bool { - self.is_set(AppSettings::PropagateVersion) - } - - /// Report whether [`Command::next_line_help`] is set - pub fn is_next_line_help_set(&self) -> bool { - self.is_set(AppSettings::NextLineHelp) - } - - /// Report whether [`Command::disable_help_flag`] is set - pub fn is_disable_help_flag_set(&self) -> bool { - self.is_set(AppSettings::DisableHelpFlag) - } - - /// Report whether [`Command::disable_help_subcommand`] is set - pub fn is_disable_help_subcommand_set(&self) -> bool { - self.is_set(AppSettings::DisableHelpSubcommand) - } - - /// Report whether [`Command::disable_colored_help`] is set - pub fn is_disable_colored_help_set(&self) -> bool { - self.is_set(AppSettings::DisableColoredHelp) - } - - /// Report whether [`Command::help_expected`] is set - #[cfg(debug_assertions)] - pub(crate) fn is_help_expected_set(&self) -> bool { - self.is_set(AppSettings::HelpExpected) - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "This is now the default") - )] - pub fn is_dont_collapse_args_in_usage_set(&self) -> bool { - true - } - - /// Report whether [`Command::infer_long_args`] is set - pub(crate) fn is_infer_long_args_set(&self) -> bool { - self.is_set(AppSettings::InferLongArgs) - } - - /// Report whether [`Command::infer_subcommands`] is set - pub(crate) fn is_infer_subcommands_set(&self) -> bool { - self.is_set(AppSettings::InferSubcommands) - } - - /// Report whether [`Command::arg_required_else_help`] is set - pub fn is_arg_required_else_help_set(&self) -> bool { - self.is_set(AppSettings::ArgRequiredElseHelp) - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "4.0.0", - note = "Replaced with `Arg::is_allow_hyphen_values_set`" - ) - )] - pub(crate) fn is_allow_hyphen_values_set(&self) -> bool { - self.is_set(AppSettings::AllowHyphenValues) - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "4.0.0", - note = "Replaced with `Arg::is_allow_negative_numbers_set`" - ) - )] - pub fn is_allow_negative_numbers_set(&self) -> bool { - self.is_set(AppSettings::AllowNegativeNumbers) - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::is_trailing_var_arg_set`") - )] - pub fn is_trailing_var_arg_set(&self) -> bool { - self.is_set(AppSettings::TrailingVarArg) - } - - /// Report whether [`Command::allow_missing_positional`] is set - pub fn is_allow_missing_positional_set(&self) -> bool { - self.is_set(AppSettings::AllowMissingPositional) - } - - /// Report whether [`Command::hide`] is set - pub fn is_hide_set(&self) -> bool { - self.is_set(AppSettings::Hidden) - } - - /// Report whether [`Command::subcommand_required`] is set - pub fn is_subcommand_required_set(&self) -> bool { - self.is_set(AppSettings::SubcommandRequired) - } - - /// Report whether [`Command::allow_external_subcommands`] is set - pub fn is_allow_external_subcommands_set(&self) -> bool { - self.is_set(AppSettings::AllowExternalSubcommands) - } - - /// Configured parser for values passed to an external subcommand - /// - /// # Example - /// - /// ```rust - /// # use clap_builder as clap; - /// let cmd = clap::Command::new("raw") - /// .external_subcommand_value_parser(clap::value_parser!(String)); - /// let value_parser = cmd.get_external_subcommand_value_parser(); - /// println!("{value_parser:?}"); - /// ``` - pub fn get_external_subcommand_value_parser(&self) -> Option<&super::ValueParser> { - if !self.is_allow_external_subcommands_set() { - None - } else { - static DEFAULT: super::ValueParser = super::ValueParser::os_string(); - Some(self.external_value_parser.as_ref().unwrap_or(&DEFAULT)) - } - } - - /// Report whether [`Command::args_conflicts_with_subcommands`] is set - pub fn is_args_conflicts_with_subcommands_set(&self) -> bool { - self.is_set(AppSettings::ArgsNegateSubcommands) - } - - #[doc(hidden)] - pub fn is_args_override_self(&self) -> bool { - self.is_set(AppSettings::AllArgsOverrideSelf) - } - - /// Report whether [`Command::subcommand_precedence_over_arg`] is set - pub fn is_subcommand_precedence_over_arg_set(&self) -> bool { - self.is_set(AppSettings::SubcommandPrecedenceOverArg) - } - - /// Report whether [`Command::subcommand_negates_reqs`] is set - pub fn is_subcommand_negates_reqs_set(&self) -> bool { - self.is_set(AppSettings::SubcommandsNegateReqs) - } - - /// Report whether [`Command::multicall`] is set - pub fn is_multicall_set(&self) -> bool { - self.is_set(AppSettings::Multicall) - } -} - -// Internally used only -impl Command { - pub(crate) fn get_override_usage(&self) -> Option<&StyledStr> { - self.usage_str.as_ref() - } - - pub(crate) fn get_override_help(&self) -> Option<&StyledStr> { - self.help_str.as_ref() - } - - #[cfg(feature = "help")] - pub(crate) fn get_help_template(&self) -> Option<&StyledStr> { - self.template.as_ref() - } - - #[cfg(feature = "help")] - pub(crate) fn get_term_width(&self) -> Option<usize> { - self.app_ext.get::<TermWidth>().map(|e| e.0) - } - - #[cfg(feature = "help")] - pub(crate) fn get_max_term_width(&self) -> Option<usize> { - self.app_ext.get::<MaxTermWidth>().map(|e| e.0) - } - - pub(crate) fn get_keymap(&self) -> &MKeyMap { - &self.args - } - - fn get_used_global_args(&self, matches: &ArgMatches, global_arg_vec: &mut Vec<Id>) { - global_arg_vec.extend( - self.args - .args() - .filter(|a| a.is_global_set()) - .map(|ga| ga.id.clone()), - ); - if let Some((id, matches)) = matches.subcommand() { - if let Some(used_sub) = self.find_subcommand(id) { - used_sub.get_used_global_args(matches, global_arg_vec); - } - } - } - - fn _do_parse( - &mut self, - raw_args: &mut clap_lex::RawArgs, - args_cursor: clap_lex::ArgCursor, - ) -> ClapResult<ArgMatches> { - debug!("Command::_do_parse"); - - // If there are global arguments, or settings we need to propagate them down to subcommands - // before parsing in case we run into a subcommand - self._build_self(false); - - let mut matcher = ArgMatcher::new(self); - - // do the real parsing - let mut parser = Parser::new(self); - if let Err(error) = parser.get_matches_with(&mut matcher, raw_args, args_cursor) { - if self.is_set(AppSettings::IgnoreErrors) && error.use_stderr() { - debug!("Command::_do_parse: ignoring error: {error}"); - } else { - return Err(error); - } - } - - let mut global_arg_vec = Default::default(); - self.get_used_global_args(&matcher, &mut global_arg_vec); - - matcher.propagate_globals(&global_arg_vec); - - Ok(matcher.into_inner()) - } - - /// Prepare for introspecting on all included [`Command`]s - /// - /// Call this on the top-level [`Command`] when done building and before reading state for - /// cases like completions, custom help output, etc. - pub fn build(&mut self) { - self._build_recursive(true); - self._build_bin_names_internal(); - } - - pub(crate) fn _build_recursive(&mut self, expand_help_tree: bool) { - self._build_self(expand_help_tree); - for subcmd in self.get_subcommands_mut() { - subcmd._build_recursive(expand_help_tree); - } - } - - pub(crate) fn _build_self(&mut self, expand_help_tree: bool) { - debug!("Command::_build: name={:?}", self.get_name()); - if !self.settings.is_set(AppSettings::Built) { - if let Some(deferred) = self.deferred.take() { - *self = (deferred)(std::mem::take(self)); - } - - // Make sure all the globally set flags apply to us as well - self.settings = self.settings | self.g_settings; - - if self.is_multicall_set() { - self.settings.set(AppSettings::SubcommandRequired); - self.settings.set(AppSettings::DisableHelpFlag); - self.settings.set(AppSettings::DisableVersionFlag); - } - if !cfg!(feature = "help") && self.get_override_help().is_none() { - self.settings.set(AppSettings::DisableHelpFlag); - self.settings.set(AppSettings::DisableHelpSubcommand); - } - if self.is_set(AppSettings::ArgsNegateSubcommands) { - self.settings.set(AppSettings::SubcommandsNegateReqs); - } - if self.external_value_parser.is_some() { - self.settings.set(AppSettings::AllowExternalSubcommands); - } - if !self.has_subcommands() { - self.settings.set(AppSettings::DisableHelpSubcommand); - } - - self._propagate(); - self._check_help_and_version(expand_help_tree); - self._propagate_global_args(); - - let mut pos_counter = 1; - let hide_pv = self.is_set(AppSettings::HidePossibleValues); - for a in self.args.args_mut() { - // Fill in the groups - for g in &a.groups { - if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) { - ag.args.push(a.get_id().clone()); - } else { - let mut ag = ArgGroup::new(g); - ag.args.push(a.get_id().clone()); - self.groups.push(ag); - } - } - - // Figure out implied settings - a._build(); - if hide_pv && a.is_takes_value_set() { - a.settings.set(ArgSettings::HidePossibleValues); - } - if a.is_positional() && a.index.is_none() { - a.index = Some(pos_counter); - pos_counter += 1; - } - } - - self.args._build(); - - #[allow(deprecated)] - { - let highest_idx = self - .get_keymap() - .keys() - .filter_map(|x| { - if let crate::mkeymap::KeyType::Position(n) = x { - Some(*n) - } else { - None - } - }) - .max() - .unwrap_or(0); - let is_trailing_var_arg_set = self.is_trailing_var_arg_set(); - let is_allow_hyphen_values_set = self.is_allow_hyphen_values_set(); - let is_allow_negative_numbers_set = self.is_allow_negative_numbers_set(); - for arg in self.args.args_mut() { - if is_allow_hyphen_values_set && arg.is_takes_value_set() { - arg.settings.set(ArgSettings::AllowHyphenValues); - } - if is_allow_negative_numbers_set && arg.is_takes_value_set() { - arg.settings.set(ArgSettings::AllowNegativeNumbers); - } - if is_trailing_var_arg_set && arg.get_index() == Some(highest_idx) { - arg.settings.set(ArgSettings::TrailingVarArg); - } - } - } - - #[cfg(debug_assertions)] - assert_app(self); - self.settings.set(AppSettings::Built); - } else { - debug!("Command::_build: already built"); - } - } - - pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> { - use std::fmt::Write; - - let mut mid_string = String::from(" "); - #[cfg(feature = "usage")] - if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set() - { - let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) - - for s in &reqs { - mid_string.push_str(&s.to_string()); - mid_string.push(' '); - } - } - let is_multicall_set = self.is_multicall_set(); - - let sc = some!(self.subcommands.iter_mut().find(|s| s.name == name)); - - // Display subcommand name, short and long in usage - let mut sc_names = String::new(); - sc_names.push_str(sc.name.as_str()); - let mut flag_subcmd = false; - if let Some(l) = sc.get_long_flag() { - write!(sc_names, "|--{l}").unwrap(); - flag_subcmd = true; - } - if let Some(s) = sc.get_short_flag() { - write!(sc_names, "|-{s}").unwrap(); - flag_subcmd = true; - } - - if flag_subcmd { - sc_names = format!("{{{sc_names}}}"); - } - - let usage_name = self - .bin_name - .as_ref() - .map(|bin_name| format!("{bin_name}{mid_string}{sc_names}")) - .unwrap_or(sc_names); - sc.usage_name = Some(usage_name); - - // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by - // a space - let bin_name = format!( - "{}{}{}", - self.bin_name.as_deref().unwrap_or_default(), - if self.bin_name.is_some() { " " } else { "" }, - &*sc.name - ); - debug!( - "Command::_build_subcommand Setting bin_name of {} to {:?}", - sc.name, bin_name - ); - sc.bin_name = Some(bin_name); - - if sc.display_name.is_none() { - let self_display_name = if is_multicall_set { - self.display_name.as_deref().unwrap_or("") - } else { - self.display_name.as_deref().unwrap_or(&self.name) - }; - let display_name = format!( - "{}{}{}", - self_display_name, - if !self_display_name.is_empty() { - "-" - } else { - "" - }, - &*sc.name - ); - debug!( - "Command::_build_subcommand Setting display_name of {} to {:?}", - sc.name, display_name - ); - sc.display_name = Some(display_name); - } - - // Ensure all args are built and ready to parse - sc._build_self(false); - - Some(sc) - } - - fn _build_bin_names_internal(&mut self) { - debug!("Command::_build_bin_names"); - - if !self.is_set(AppSettings::BinNameBuilt) { - let mut mid_string = String::from(" "); - #[cfg(feature = "usage")] - if !self.is_subcommand_negates_reqs_set() - && !self.is_args_conflicts_with_subcommands_set() - { - let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) - - for s in &reqs { - mid_string.push_str(&s.to_string()); - mid_string.push(' '); - } - } - let is_multicall_set = self.is_multicall_set(); - - let self_bin_name = if is_multicall_set { - self.bin_name.as_deref().unwrap_or("") - } else { - self.bin_name.as_deref().unwrap_or(&self.name) - } - .to_owned(); - - for sc in &mut self.subcommands { - debug!("Command::_build_bin_names:iter: bin_name set..."); - - if sc.usage_name.is_none() { - use std::fmt::Write; - // Display subcommand name, short and long in usage - let mut sc_names = String::new(); - sc_names.push_str(sc.name.as_str()); - let mut flag_subcmd = false; - if let Some(l) = sc.get_long_flag() { - write!(sc_names, "|--{l}").unwrap(); - flag_subcmd = true; - } - if let Some(s) = sc.get_short_flag() { - write!(sc_names, "|-{s}").unwrap(); - flag_subcmd = true; - } - - if flag_subcmd { - sc_names = format!("{{{sc_names}}}"); - } - - let usage_name = format!("{self_bin_name}{mid_string}{sc_names}"); - debug!( - "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}", - sc.name, usage_name - ); - sc.usage_name = Some(usage_name); - } else { - debug!( - "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})", - sc.name, sc.usage_name - ); - } - - if sc.bin_name.is_none() { - let bin_name = format!( - "{}{}{}", - self_bin_name, - if !self_bin_name.is_empty() { " " } else { "" }, - &*sc.name - ); - debug!( - "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}", - sc.name, bin_name - ); - sc.bin_name = Some(bin_name); - } else { - debug!( - "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})", - sc.name, sc.bin_name - ); - } - - if sc.display_name.is_none() { - let self_display_name = if is_multicall_set { - self.display_name.as_deref().unwrap_or("") - } else { - self.display_name.as_deref().unwrap_or(&self.name) - }; - let display_name = format!( - "{}{}{}", - self_display_name, - if !self_display_name.is_empty() { - "-" - } else { - "" - }, - &*sc.name - ); - debug!( - "Command::_build_bin_names:iter: Setting display_name of {} to {:?}", - sc.name, display_name - ); - sc.display_name = Some(display_name); - } else { - debug!( - "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})", - sc.name, sc.display_name - ); - } - - sc._build_bin_names_internal(); - } - self.set(AppSettings::BinNameBuilt); - } else { - debug!("Command::_build_bin_names: already built"); - } - } - - pub(crate) fn _panic_on_missing_help(&self, help_required_globally: bool) { - if self.is_set(AppSettings::HelpExpected) || help_required_globally { - let args_missing_help: Vec<Id> = self - .args - .args() - .filter(|arg| arg.get_help().is_none() && arg.get_long_help().is_none()) - .map(|arg| arg.get_id().clone()) - .collect(); - - debug_assert!(args_missing_help.is_empty(), - "Command::help_expected is enabled for the Command {}, but at least one of its arguments does not have either `help` or `long_help` set. List of such arguments: {}", - self.name, - args_missing_help.join(", ") - ); - } - - for sub_app in &self.subcommands { - sub_app._panic_on_missing_help(help_required_globally); - } - } - - #[cfg(debug_assertions)] - pub(crate) fn two_args_of<F>(&self, condition: F) -> Option<(&Arg, &Arg)> - where - F: Fn(&Arg) -> bool, - { - two_elements_of(self.args.args().filter(|a: &&Arg| condition(a))) - } - - // just in case - #[allow(unused)] - fn two_groups_of<F>(&self, condition: F) -> Option<(&ArgGroup, &ArgGroup)> - where - F: Fn(&ArgGroup) -> bool, - { - two_elements_of(self.groups.iter().filter(|a| condition(a))) - } - - /// Propagate global args - pub(crate) fn _propagate_global_args(&mut self) { - debug!("Command::_propagate_global_args:{}", self.name); - - let autogenerated_help_subcommand = !self.is_disable_help_subcommand_set(); - - for sc in &mut self.subcommands { - if sc.get_name() == "help" && autogenerated_help_subcommand { - // Avoid propagating args to the autogenerated help subtrees used in completion. - // This prevents args from showing up during help completions like - // `myapp help subcmd <TAB>`, which should only suggest subcommands and not args, - // while still allowing args to show up properly on the generated help message. - continue; - } - - for a in self.args.args().filter(|a| a.is_global_set()) { - if sc.find(&a.id).is_some() { - debug!( - "Command::_propagate skipping {:?} to {}, already exists", - a.id, - sc.get_name(), - ); - continue; - } - - debug!( - "Command::_propagate pushing {:?} to {}", - a.id, - sc.get_name(), - ); - sc.args.push(a.clone()); - } - } - } - - /// Propagate settings - pub(crate) fn _propagate(&mut self) { - debug!("Command::_propagate:{}", self.name); - let mut subcommands = std::mem::take(&mut self.subcommands); - for sc in &mut subcommands { - self._propagate_subcommand(sc); - } - self.subcommands = subcommands; - } - - fn _propagate_subcommand(&self, sc: &mut Self) { - // We have to create a new scope in order to tell rustc the borrow of `sc` is - // done and to recursively call this method - { - if self.settings.is_set(AppSettings::PropagateVersion) { - if let Some(version) = self.version.as_ref() { - sc.version.get_or_insert_with(|| version.clone()); - } - if let Some(long_version) = self.long_version.as_ref() { - sc.long_version.get_or_insert_with(|| long_version.clone()); - } - } - - sc.settings = sc.settings | self.g_settings; - sc.g_settings = sc.g_settings | self.g_settings; - sc.app_ext.update(&self.app_ext); - } - } - - pub(crate) fn _check_help_and_version(&mut self, expand_help_tree: bool) { - debug!( - "Command::_check_help_and_version:{} expand_help_tree={}", - self.name, expand_help_tree - ); - - self.long_help_exists = self.long_help_exists_(); - - if !self.is_disable_help_flag_set() { - debug!("Command::_check_help_and_version: Building default --help"); - let mut arg = Arg::new(Id::HELP) - .short('h') - .long("help") - .action(ArgAction::Help); - if self.long_help_exists { - arg = arg - .help("Print help (see more with '--help')") - .long_help("Print help (see a summary with '-h')"); - } else { - arg = arg.help("Print help"); - } - // Avoiding `arg_internal` to not be sensitive to `next_help_heading` / - // `next_display_order` - self.args.push(arg); - } - if !self.is_disable_version_flag_set() { - debug!("Command::_check_help_and_version: Building default --version"); - let arg = Arg::new(Id::VERSION) - .short('V') - .long("version") - .action(ArgAction::Version) - .help("Print version"); - // Avoiding `arg_internal` to not be sensitive to `next_help_heading` / - // `next_display_order` - self.args.push(arg); - } - - if !self.is_set(AppSettings::DisableHelpSubcommand) { - debug!("Command::_check_help_and_version: Building help subcommand"); - let help_about = "Print this message or the help of the given subcommand(s)"; - - let mut help_subcmd = if expand_help_tree { - // Slow code path to recursively clone all other subcommand subtrees under help - let help_subcmd = Command::new("help") - .about(help_about) - .global_setting(AppSettings::DisableHelpSubcommand) - .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help)); - - let mut help_help_subcmd = Command::new("help").about(help_about); - help_help_subcmd.version = None; - help_help_subcmd.long_version = None; - help_help_subcmd = help_help_subcmd - .setting(AppSettings::DisableHelpFlag) - .setting(AppSettings::DisableVersionFlag); - - help_subcmd.subcommand(help_help_subcmd) - } else { - Command::new("help").about(help_about).arg( - Arg::new("subcommand") - .action(ArgAction::Append) - .num_args(..) - .value_name("COMMAND") - .help("Print help for the subcommand(s)"), - ) - }; - self._propagate_subcommand(&mut help_subcmd); - - // The parser acts like this is set, so let's set it so we don't falsely - // advertise it to the user - help_subcmd.version = None; - help_subcmd.long_version = None; - help_subcmd = help_subcmd - .setting(AppSettings::DisableHelpFlag) - .setting(AppSettings::DisableVersionFlag) - .unset_global_setting(AppSettings::PropagateVersion); - - self.subcommands.push(help_subcmd); - } - } - - fn _copy_subtree_for_help(&self) -> Command { - let mut cmd = Command::new(self.name.clone()) - .hide(self.is_hide_set()) - .global_setting(AppSettings::DisableHelpFlag) - .global_setting(AppSettings::DisableVersionFlag) - .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help)); - if self.get_about().is_some() { - cmd = cmd.about(self.get_about().unwrap().clone()); - } - cmd - } - - pub(crate) fn _render_version(&self, use_long: bool) -> String { - debug!("Command::_render_version"); - - let ver = if use_long { - self.long_version - .as_deref() - .or(self.version.as_deref()) - .unwrap_or_default() - } else { - self.version - .as_deref() - .or(self.long_version.as_deref()) - .unwrap_or_default() - }; - let display_name = self.get_display_name().unwrap_or_else(|| self.get_name()); - format!("{display_name} {ver}\n") - } - - pub(crate) fn format_group(&self, g: &Id) -> StyledStr { - let g_string = self - .unroll_args_in_group(g) - .iter() - .filter_map(|x| self.find(x)) - .map(|x| { - if x.is_positional() { - // Print val_name for positional arguments. e.g. <file_name> - x.name_no_brackets() - } else { - // Print usage string for flags arguments, e.g. <--help> - x.to_string() - } - }) - .collect::<Vec<_>>() - .join("|"); - let mut styled = StyledStr::new(); - styled.push_str("<"); - styled.push_string(g_string); - styled.push_str(">"); - styled - } -} - -/// A workaround: -/// <https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999> -pub(crate) trait Captures<'a> {} -impl<'a, T> Captures<'a> for T {} - -// Internal Query Methods -impl Command { - /// Iterate through the *flags* & *options* arguments. - #[cfg(any(feature = "usage", feature = "help"))] - pub(crate) fn get_non_positionals(&self) -> impl Iterator<Item = &Arg> { - self.get_arguments().filter(|a| !a.is_positional()) - } - - pub(crate) fn find(&self, arg_id: &Id) -> Option<&Arg> { - self.args.args().find(|a| a.get_id() == arg_id) - } - - #[inline] - pub(crate) fn contains_short(&self, s: char) -> bool { - debug_assert!( - self.is_set(AppSettings::Built), - "If Command::_build hasn't been called, manually search through Arg shorts" - ); - - self.args.contains(s) - } - - #[inline] - pub(crate) fn set(&mut self, s: AppSettings) { - self.settings.set(s) - } - - #[inline] - pub(crate) fn has_positionals(&self) -> bool { - self.get_positionals().next().is_some() - } - - #[cfg(any(feature = "usage", feature = "help"))] - pub(crate) fn has_visible_subcommands(&self) -> bool { - self.subcommands - .iter() - .any(|sc| sc.name != "help" && !sc.is_set(AppSettings::Hidden)) - } - - /// Check if this subcommand can be referred to as `name`. In other words, - /// check if `name` is the name of this subcommand or is one of its aliases. - #[inline] - pub(crate) fn aliases_to(&self, name: impl AsRef<std::ffi::OsStr>) -> bool { - let name = name.as_ref(); - self.get_name() == name || self.get_all_aliases().any(|alias| alias == name) - } - - /// Check if this subcommand can be referred to as `name`. In other words, - /// check if `name` is the name of this short flag subcommand or is one of its short flag aliases. - #[inline] - pub(crate) fn short_flag_aliases_to(&self, flag: char) -> bool { - Some(flag) == self.short_flag - || self.get_all_short_flag_aliases().any(|alias| flag == alias) - } - - /// Check if this subcommand can be referred to as `name`. In other words, - /// check if `name` is the name of this long flag subcommand or is one of its long flag aliases. - #[inline] - pub(crate) fn long_flag_aliases_to(&self, flag: &str) -> bool { - match self.long_flag.as_ref() { - Some(long_flag) => { - long_flag == flag || self.get_all_long_flag_aliases().any(|alias| alias == flag) - } - None => self.get_all_long_flag_aliases().any(|alias| alias == flag), - } - } - - #[cfg(debug_assertions)] - pub(crate) fn id_exists(&self, id: &Id) -> bool { - self.args.args().any(|x| x.get_id() == id) || self.groups.iter().any(|x| x.id == *id) - } - - /// Iterate through the groups this arg is member of. - pub(crate) fn groups_for_arg<'a>(&'a self, arg: &Id) -> impl Iterator<Item = Id> + 'a { - debug!("Command::groups_for_arg: id={arg:?}"); - let arg = arg.clone(); - self.groups - .iter() - .filter(move |grp| grp.args.iter().any(|a| a == &arg)) - .map(|grp| grp.id.clone()) - } - - pub(crate) fn find_group(&self, group_id: &Id) -> Option<&ArgGroup> { - self.groups.iter().find(|g| g.id == *group_id) - } - - /// Iterate through all the names of all subcommands (not recursively), including aliases. - /// Used for suggestions. - pub(crate) fn all_subcommand_names(&self) -> impl Iterator<Item = &str> + Captures { - self.get_subcommands().flat_map(|sc| { - let name = sc.get_name(); - let aliases = sc.get_all_aliases(); - std::iter::once(name).chain(aliases) - }) - } - - pub(crate) fn required_graph(&self) -> ChildGraph<Id> { - let mut reqs = ChildGraph::with_capacity(5); - for a in self.args.args().filter(|a| a.is_required_set()) { - reqs.insert(a.get_id().clone()); - } - for group in &self.groups { - if group.required { - let idx = reqs.insert(group.id.clone()); - for a in &group.requires { - reqs.insert_child(idx, a.clone()); - } - } - } - - reqs - } - - pub(crate) fn unroll_args_in_group(&self, group: &Id) -> Vec<Id> { - debug!("Command::unroll_args_in_group: group={group:?}"); - let mut g_vec = vec![group]; - let mut args = vec![]; - - while let Some(g) = g_vec.pop() { - for n in self - .groups - .iter() - .find(|grp| grp.id == *g) - .expect(INTERNAL_ERROR_MSG) - .args - .iter() - { - debug!("Command::unroll_args_in_group:iter: entity={n:?}"); - if !args.contains(n) { - if self.find(n).is_some() { - debug!("Command::unroll_args_in_group:iter: this is an arg"); - args.push(n.clone()) - } else { - debug!("Command::unroll_args_in_group:iter: this is a group"); - g_vec.push(n); - } - } - } - } - - args - } - - pub(crate) fn unroll_arg_requires<F>(&self, func: F, arg: &Id) -> Vec<Id> - where - F: Fn(&(ArgPredicate, Id)) -> Option<Id>, - { - let mut processed = vec![]; - let mut r_vec = vec![arg]; - let mut args = vec![]; - - while let Some(a) = r_vec.pop() { - if processed.contains(&a) { - continue; - } - - processed.push(a); - - if let Some(arg) = self.find(a) { - for r in arg.requires.iter().filter_map(&func) { - if let Some(req) = self.find(&r) { - if !req.requires.is_empty() { - r_vec.push(req.get_id()) - } - } - args.push(r); - } - } - } - - args - } - - /// Find a flag subcommand name by short flag or an alias - pub(crate) fn find_short_subcmd(&self, c: char) -> Option<&str> { - self.get_subcommands() - .find(|sc| sc.short_flag_aliases_to(c)) - .map(|sc| sc.get_name()) - } - - /// Find a flag subcommand name by long flag or an alias - pub(crate) fn find_long_subcmd(&self, long: &str) -> Option<&str> { - self.get_subcommands() - .find(|sc| sc.long_flag_aliases_to(long)) - .map(|sc| sc.get_name()) - } - - #[cfg(feature = "help")] - pub(crate) fn get_display_order(&self) -> usize { - self.disp_ord.unwrap_or(999) - } - - pub(crate) fn write_help_err(&self, mut use_long: bool) -> StyledStr { - debug!( - "Command::write_help_err: {}, use_long={:?}", - self.get_display_name().unwrap_or_else(|| self.get_name()), - use_long && self.long_help_exists(), - ); - - use_long = use_long && self.long_help_exists(); - let usage = Usage::new(self); - - let mut styled = StyledStr::new(); - write_help(&mut styled, self, &usage, use_long); - - styled - } - - pub(crate) fn write_version_err(&self, use_long: bool) -> StyledStr { - let msg = self._render_version(use_long); - StyledStr::from(msg) - } - - pub(crate) fn long_help_exists(&self) -> bool { - debug!("Command::long_help_exists: {}", self.long_help_exists); - self.long_help_exists - } - - fn long_help_exists_(&self) -> bool { - debug!("Command::long_help_exists"); - // In this case, both must be checked. This allows the retention of - // original formatting, but also ensures that the actual -h or --help - // specified by the user is sent through. If hide_short_help is not included, - // then items specified with hidden_short_help will also be hidden. - let should_long = |v: &Arg| { - !v.is_hide_set() - && (v.get_long_help().is_some() - || v.is_hide_long_help_set() - || v.is_hide_short_help_set() - || (!v.is_hide_possible_values_set() - && v.get_possible_values() - .iter() - .any(PossibleValue::should_show_help))) - }; - - // Subcommands aren't checked because we prefer short help for them, deferring to - // `cmd subcmd --help` for more. - self.get_long_about().is_some() - || self.get_before_long_help().is_some() - || self.get_after_long_help().is_some() - || self.get_arguments().any(should_long) - } - - // Should we color the help? - pub(crate) fn color_help(&self) -> ColorChoice { - #[cfg(feature = "color")] - if self.is_disable_colored_help_set() { - return ColorChoice::Never; - } - - self.get_color() - } -} - -impl Default for Command { - fn default() -> Self { - Self { - name: Default::default(), - long_flag: Default::default(), - short_flag: Default::default(), - display_name: Default::default(), - bin_name: Default::default(), - author: Default::default(), - version: Default::default(), - long_version: Default::default(), - about: Default::default(), - long_about: Default::default(), - before_help: Default::default(), - before_long_help: Default::default(), - after_help: Default::default(), - after_long_help: Default::default(), - aliases: Default::default(), - short_flag_aliases: Default::default(), - long_flag_aliases: Default::default(), - usage_str: Default::default(), - usage_name: Default::default(), - help_str: Default::default(), - disp_ord: Default::default(), - #[cfg(feature = "help")] - template: Default::default(), - settings: Default::default(), - g_settings: Default::default(), - args: Default::default(), - subcommands: Default::default(), - groups: Default::default(), - current_help_heading: Default::default(), - current_disp_ord: Some(0), - subcommand_value_name: Default::default(), - subcommand_heading: Default::default(), - external_value_parser: Default::default(), - long_help_exists: false, - deferred: None, - app_ext: Default::default(), - } - } -} - -impl Index<&'_ Id> for Command { - type Output = Arg; - - fn index(&self, key: &Id) -> &Self::Output { - self.find(key).expect(INTERNAL_ERROR_MSG) - } -} - -impl From<&'_ Command> for Command { - fn from(cmd: &'_ Command) -> Self { - cmd.clone() - } -} - -impl fmt::Display for Command { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.name) - } -} - -pub(crate) trait AppTag: crate::builder::ext::Extension {} - -#[derive(Default, Copy, Clone, Debug)] -struct TermWidth(usize); - -impl AppTag for TermWidth {} - -#[derive(Default, Copy, Clone, Debug)] -struct MaxTermWidth(usize); - -impl AppTag for MaxTermWidth {} - -fn two_elements_of<I, T>(mut iter: I) -> Option<(T, T)> -where - I: Iterator<Item = T>, -{ - let first = iter.next(); - let second = iter.next(); - - match (first, second) { - (Some(first), Some(second)) => Some((first, second)), - _ => None, - } -} - -#[test] -fn check_auto_traits() { - static_assertions::assert_impl_all!(Command: Send, Sync, Unpin); -} diff --git a/vendor/clap_builder/src/builder/debug_asserts.rs b/vendor/clap_builder/src/builder/debug_asserts.rs deleted file mode 100644 index 2b63384..0000000 --- a/vendor/clap_builder/src/builder/debug_asserts.rs +++ /dev/null @@ -1,840 +0,0 @@ -use std::cmp::Ordering; - -use crate::builder::ValueRange; -use crate::mkeymap::KeyType; -use crate::util::FlatSet; -use crate::util::Id; -use crate::ArgAction; -use crate::INTERNAL_ERROR_MSG; -use crate::{Arg, Command, ValueHint}; - -pub(crate) fn assert_app(cmd: &Command) { - debug!("Command::_debug_asserts"); - - let mut short_flags = vec![]; - let mut long_flags = vec![]; - - // Invalid version flag settings - if cmd.get_version().is_none() && cmd.get_long_version().is_none() { - // PropagateVersion is meaningless if there is no version - assert!( - !cmd.is_propagate_version_set(), - "Command {}: No version information via Command::version or Command::long_version to propagate", - cmd.get_name(), - ); - - // Used `Command::mut_arg("version", ..) but did not provide any version information to display - let version_needed = cmd - .get_arguments() - .filter(|x| matches!(x.get_action(), ArgAction::Version)) - .map(|x| x.get_id()) - .collect::<Vec<_>>(); - - assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version" - ,cmd.get_name() - ); - } - - for sc in cmd.get_subcommands() { - if let Some(s) = sc.get_short_flag().as_ref() { - short_flags.push(Flag::Command(format!("-{s}"), sc.get_name())); - } - - for short_alias in sc.get_all_short_flag_aliases() { - short_flags.push(Flag::Command(format!("-{short_alias}"), sc.get_name())); - } - - if let Some(l) = sc.get_long_flag().as_ref() { - assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l); - long_flags.push(Flag::Command(format!("--{l}"), sc.get_name())); - } - - for long_alias in sc.get_all_long_flag_aliases() { - long_flags.push(Flag::Command(format!("--{long_alias}"), sc.get_name())); - } - } - - for arg in cmd.get_arguments() { - assert_arg(arg); - - assert!( - !cmd.is_multicall_set(), - "Command {}: Arguments like {} cannot be set on a multicall command", - cmd.get_name(), - arg.get_id() - ); - - if let Some(s) = arg.get_short() { - short_flags.push(Flag::Arg(format!("-{s}"), arg.get_id().as_str())); - } - - for (short_alias, _) in &arg.short_aliases { - short_flags.push(Flag::Arg(format!("-{short_alias}"), arg.get_id().as_str())); - } - - if let Some(l) = arg.get_long() { - assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.get_id(), l); - long_flags.push(Flag::Arg(format!("--{l}"), arg.get_id().as_str())); - } - - for (long_alias, _) in &arg.aliases { - long_flags.push(Flag::Arg(format!("--{long_alias}"), arg.get_id().as_str())); - } - - // Name conflicts - if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) { - panic!( - "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}", - cmd.get_name(), - arg.get_id(), - duplicate_tip(cmd, first, second), - ); - } - - // Long conflicts - if let Some(l) = arg.get_long() { - if let Some((first, second)) = cmd.two_args_of(|x| x.get_long() == Some(l)) { - panic!( - "Command {}: Long option names must be unique for each argument, \ - but '--{}' is in use by both '{}' and '{}'{}", - cmd.get_name(), - l, - first.get_id(), - second.get_id(), - duplicate_tip(cmd, first, second) - ) - } - } - - // Short conflicts - if let Some(s) = arg.get_short() { - if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) { - panic!( - "Command {}: Short option names must be unique for each argument, \ - but '-{}' is in use by both '{}' and '{}'{}", - cmd.get_name(), - s, - first.get_id(), - second.get_id(), - duplicate_tip(cmd, first, second), - ) - } - } - - // Index conflicts - if let Some(idx) = arg.index { - if let Some((first, second)) = - cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx)) - { - panic!( - "Command {}: Argument '{}' has the same index as '{}' \ - and they are both positional arguments\n\n\t \ - Use `Arg::num_args(1..)` to allow one \ - positional argument to take multiple values", - cmd.get_name(), - first.get_id(), - second.get_id() - ) - } - } - - // requires, r_if, r_unless - for req in &arg.requires { - assert!( - cmd.id_exists(&req.1), - "Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist", - cmd.get_name(), - req.1, - arg.get_id(), - ); - } - - for req in &arg.r_ifs { - assert!( - !arg.is_required_set(), - "Argument {}: `required` conflicts with `required_if_eq*`", - arg.get_id() - ); - assert!( - cmd.id_exists(&req.0), - "Command {}: Argument or group '{}' specified in 'required_if_eq*' for '{}' does not exist", - cmd.get_name(), - req.0, - arg.get_id() - ); - } - - for req in &arg.r_ifs_all { - assert!( - !arg.is_required_set(), - "Argument {}: `required` conflicts with `required_if_eq_all`", - arg.get_id() - ); - assert!( - cmd.id_exists(&req.0), - "Command {}: Argument or group '{}' specified in 'required_if_eq_all' for '{}' does not exist", - cmd.get_name(), - req.0, - arg.get_id() - ); - } - - for req in &arg.r_unless { - assert!( - !arg.is_required_set(), - "Argument {}: `required` conflicts with `required_unless*`", - arg.get_id() - ); - assert!( - cmd.id_exists(req), - "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist", - cmd.get_name(), - req, - arg.get_id(), - ); - } - - for req in &arg.r_unless_all { - assert!( - !arg.is_required_set(), - "Argument {}: `required` conflicts with `required_unless*`", - arg.get_id() - ); - assert!( - cmd.id_exists(req), - "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist", - cmd.get_name(), - req, - arg.get_id(), - ); - } - - // blacklist - for req in &arg.blacklist { - assert!( - cmd.id_exists(req), - "Command {}: Argument or group '{}' specified in 'conflicts_with*' for '{}' does not exist", - cmd.get_name(), - req, - arg.get_id(), - ); - } - - // overrides - for req in &arg.overrides { - assert!( - cmd.id_exists(req), - "Command {}: Argument or group '{}' specified in 'overrides_with*' for '{}' does not exist", - cmd.get_name(), - req, - arg.get_id(), - ); - } - - if arg.is_last_set() { - assert!( - arg.get_long().is_none(), - "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.", - cmd.get_name(), - arg.get_id() - ); - assert!( - arg.get_short().is_none(), - "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.", - cmd.get_name(), - arg.get_id() - ); - } - - assert!( - !(arg.is_required_set() && arg.is_global_set()), - "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required", - cmd.get_name(), - arg.get_id() - ); - - if arg.get_value_hint() == ValueHint::CommandWithArguments { - assert!( - arg.is_positional(), - "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.", - cmd.get_name(), - arg.get_id() - ); - - assert!( - arg.is_trailing_var_arg_set() || arg.is_last_set(), - "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have `trailing_var_arg(true)` or `last(true)` set.", - cmd.get_name(), - arg.get_id() - ); - } - } - - for group in cmd.get_groups() { - // Name conflicts - assert!( - cmd.get_groups().filter(|x| x.id == group.id).count() < 2, - "Command {}: Argument group name must be unique\n\n\t'{}' is already in use", - cmd.get_name(), - group.get_id(), - ); - - // Groups should not have naming conflicts with Args - assert!( - !cmd.get_arguments().any(|x| x.get_id() == group.get_id()), - "Command {}: Argument group name '{}' must not conflict with argument name", - cmd.get_name(), - group.get_id(), - ); - - for arg in &group.args { - // Args listed inside groups should exist - assert!( - cmd.get_arguments().any(|x| x.get_id() == arg), - "Command {}: Argument group '{}' contains non-existent argument '{}'", - cmd.get_name(), - group.get_id(), - arg - ); - } - - for arg in &group.requires { - // Args listed inside groups should exist - assert!( - cmd.id_exists(arg), - "Command {}: Argument group '{}' requires non-existent '{}' id", - cmd.get_name(), - group.get_id(), - arg - ); - } - - for arg in &group.conflicts { - // Args listed inside groups should exist - assert!( - cmd.id_exists(arg), - "Command {}: Argument group '{}' conflicts with non-existent '{}' id", - cmd.get_name(), - group.get_id(), - arg - ); - } - } - - // Conflicts between flags and subcommands - - long_flags.sort_unstable(); - short_flags.sort_unstable(); - - detect_duplicate_flags(&long_flags, "long"); - detect_duplicate_flags(&short_flags, "short"); - - let mut subs = FlatSet::new(); - for sc in cmd.get_subcommands() { - assert!( - subs.insert(sc.get_name()), - "Command {}: command name `{}` is duplicated", - cmd.get_name(), - sc.get_name() - ); - for alias in sc.get_all_aliases() { - assert!( - subs.insert(alias), - "Command {}: command `{}` alias `{}` is duplicated", - cmd.get_name(), - sc.get_name(), - alias - ); - } - } - - _verify_positionals(cmd); - - #[cfg(feature = "help")] - if let Some(help_template) = cmd.get_help_template() { - assert!( - !help_template.to_string().contains("{flags}"), - "Command {}: {}", - cmd.get_name(), - "`{flags}` template variable was removed in clap3, they are now included in `{options}`", - ); - assert!( - !help_template.to_string().contains("{unified}"), - "Command {}: {}", - cmd.get_name(), - "`{unified}` template variable was removed in clap3, use `{options}` instead" - ); - #[cfg(feature = "unstable-v5")] - assert!( - !help_template.to_string().contains("{bin}"), - "Command {}: {}", - cmd.get_name(), - "`{bin}` template variable was removed in clap5, use `{name}` instead" - ) - } - - cmd._panic_on_missing_help(cmd.is_help_expected_set()); - assert_app_flags(cmd); -} - -fn duplicate_tip(cmd: &Command, first: &Arg, second: &Arg) -> &'static str { - if !cmd.is_disable_help_flag_set() - && (first.get_id() == Id::HELP || second.get_id() == Id::HELP) - { - " (call `cmd.disable_help_flag(true)` to remove the auto-generated `--help`)" - } else if !cmd.is_disable_version_flag_set() - && (first.get_id() == Id::VERSION || second.get_id() == Id::VERSION) - { - " (call `cmd.disable_version_flag(true)` to remove the auto-generated `--version`)" - } else { - "" - } -} - -#[derive(Eq)] -enum Flag<'a> { - Command(String, &'a str), - Arg(String, &'a str), -} - -impl PartialEq for Flag<'_> { - fn eq(&self, other: &Flag) -> bool { - self.cmp(other) == Ordering::Equal - } -} - -impl PartialOrd for Flag<'_> { - fn partial_cmp(&self, other: &Flag) -> Option<Ordering> { - Some(self.cmp(other)) - } -} - -impl Ord for Flag<'_> { - fn cmp(&self, other: &Self) -> Ordering { - use Flag::*; - - match (self, other) { - (Command(s1, _), Command(s2, _)) - | (Arg(s1, _), Arg(s2, _)) - | (Command(s1, _), Arg(s2, _)) - | (Arg(s1, _), Command(s2, _)) => { - if s1 == s2 { - Ordering::Equal - } else { - s1.cmp(s2) - } - } - } - } -} - -fn detect_duplicate_flags(flags: &[Flag], short_or_long: &str) { - use Flag::*; - - for (one, two) in find_duplicates(flags) { - match (one, two) { - (Command(flag, one), Command(_, another)) if one != another => panic!( - "the '{flag}' {short_or_long} flag is specified for both '{one}' and '{another}' subcommands" - ), - - (Arg(flag, one), Arg(_, another)) if one != another => panic!( - "{short_or_long} option names must be unique, but '{flag}' is in use by both '{one}' and '{another}'" - ), - - (Arg(flag, arg), Command(_, sub)) | (Command(flag, sub), Arg(_, arg)) => panic!( - "the '{flag}' {short_or_long} flag for the '{arg}' argument conflicts with the short flag \ - for '{sub}' subcommand" - ), - - _ => {} - } - } -} - -/// Find duplicates in a sorted array. -/// -/// The algorithm is simple: the array is sorted, duplicates -/// must be placed next to each other, we can check only adjacent elements. -fn find_duplicates<T: PartialEq>(slice: &[T]) -> impl Iterator<Item = (&T, &T)> { - slice.windows(2).filter_map(|w| { - if w[0] == w[1] { - Some((&w[0], &w[1])) - } else { - None - } - }) -} - -fn assert_app_flags(cmd: &Command) { - macro_rules! checker { - ($a:ident requires $($b:ident)|+) => { - if cmd.$a() { - let mut s = String::new(); - - $( - if !cmd.$b() { - use std::fmt::Write; - write!(&mut s, " AppSettings::{} is required when AppSettings::{} is set.\n", std::stringify!($b), std::stringify!($a)).unwrap(); - } - )+ - - if !s.is_empty() { - panic!("{s}") - } - } - }; - ($a:ident conflicts $($b:ident)|+) => { - if cmd.$a() { - let mut s = String::new(); - - $( - if cmd.$b() { - use std::fmt::Write; - write!(&mut s, " AppSettings::{} conflicts with AppSettings::{}.\n", std::stringify!($b), std::stringify!($a)).unwrap(); - } - )+ - - if !s.is_empty() { - panic!("{}\n{}", cmd.get_name(), s) - } - } - }; - } - - checker!(is_multicall_set conflicts is_no_binary_name_set); -} - -#[cfg(debug_assertions)] -fn _verify_positionals(cmd: &Command) -> bool { - debug!("Command::_verify_positionals"); - // Because you must wait until all arguments have been supplied, this is the first chance - // to make assertions on positional argument indexes - // - // First we verify that the index highest supplied index, is equal to the number of - // positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3 - // but no 2) - - let highest_idx = cmd - .get_keymap() - .keys() - .filter_map(|x| { - if let KeyType::Position(n) = x { - Some(*n) - } else { - None - } - }) - .max() - .unwrap_or(0); - - let num_p = cmd.get_keymap().keys().filter(|x| x.is_position()).count(); - - assert!( - highest_idx == num_p, - "Found positional argument whose index is {highest_idx} but there \ - are only {num_p} positional arguments defined", - ); - - for arg in cmd.get_arguments() { - if arg.index.unwrap_or(0) == highest_idx { - assert!( - !arg.is_trailing_var_arg_set() || !arg.is_last_set(), - "{}:{}: `Arg::trailing_var_arg` and `Arg::last` cannot be used together", - cmd.get_name(), - arg.get_id() - ); - - if arg.is_trailing_var_arg_set() { - assert!( - arg.is_multiple(), - "{}:{}: `Arg::trailing_var_arg` must accept multiple values", - cmd.get_name(), - arg.get_id() - ); - } - } else { - assert!( - !arg.is_trailing_var_arg_set(), - "{}:{}: `Arg::trailing_var_arg` can only apply to last positional", - cmd.get_name(), - arg.get_id() - ); - } - } - - // Next we verify that only the highest index has takes multiple arguments (if any) - let only_highest = |a: &Arg| a.is_multiple() && (a.get_index().unwrap_or(0) != highest_idx); - if cmd.get_positionals().any(only_highest) { - // First we make sure if there is a positional that allows multiple values - // the one before it (second to last) has one of these: - // * a value terminator - // * ArgSettings::Last - // * The last arg is Required - - // We can't pass the closure (it.next()) to the macro directly because each call to - // find() (iterator, not macro) gets called repeatedly. - let last = &cmd.get_keymap()[&KeyType::Position(highest_idx)]; - let second_to_last = &cmd.get_keymap()[&KeyType::Position(highest_idx - 1)]; - - // Either the final positional is required - // Or the second to last has a terminator or .last(true) set - let ok = last.is_required_set() - || (second_to_last.terminator.is_some() || second_to_last.is_last_set()) - || last.is_last_set(); - assert!( - ok, - "Positional argument `{last}` *must* have `required(true)` or `last(true)` set \ - because a prior positional argument (`{second_to_last}`) has `num_args(1..)`" - ); - - // We make sure if the second to last is Multiple the last is ArgSettings::Last - let ok = second_to_last.is_multiple() || last.is_last_set(); - assert!( - ok, - "Only the last positional argument, or second to last positional \ - argument may be set to `.num_args(1..)`" - ); - - // Next we check how many have both Multiple and not a specific number of values set - let count = cmd - .get_positionals() - .filter(|p| { - p.is_multiple_values_set() - && p.get_value_terminator().is_none() - && !p.get_num_args().expect(INTERNAL_ERROR_MSG).is_fixed() - }) - .count(); - let ok = count <= 1 - || (last.is_last_set() - && last.is_multiple() - && second_to_last.is_multiple() - && count == 2); - assert!( - ok, - "Only one positional argument with `.num_args(1..)` set is allowed per \ - command, unless the second one also has .last(true) set" - ); - } - - let mut found = false; - - if cmd.is_allow_missing_positional_set() { - // Check that if a required positional argument is found, all positions with a lower - // index are also required. - let mut foundx2 = false; - - for p in cmd.get_positionals() { - if foundx2 && !p.is_required_set() { - assert!( - p.is_required_set(), - "Found non-required positional argument with a lower \ - index than a required positional argument by two or more: {:?} \ - index {:?}", - p.get_id(), - p.get_index() - ); - } else if p.is_required_set() && !p.is_last_set() { - // Args that .last(true) don't count since they can be required and have - // positionals with a lower index that aren't required - // Imagine: prog <req1> [opt1] -- <req2> - // Both of these are valid invocations: - // $ prog r1 -- r2 - // $ prog r1 o1 -- r2 - if found { - foundx2 = true; - continue; - } - found = true; - continue; - } else { - found = false; - } - } - } else { - // Check that if a required positional argument is found, all positions with a lower - // index are also required - for p in (1..=num_p).rev().filter_map(|n| cmd.get_keymap().get(&n)) { - if found { - assert!( - p.is_required_set(), - "Found non-required positional argument with a lower \ - index than a required positional argument: {:?} index {:?}", - p.get_id(), - p.get_index() - ); - } else if p.is_required_set() && !p.is_last_set() { - // Args that .last(true) don't count since they can be required and have - // positionals with a lower index that aren't required - // Imagine: prog <req1> [opt1] -- <req2> - // Both of these are valid invocations: - // $ prog r1 -- r2 - // $ prog r1 o1 -- r2 - found = true; - continue; - } - } - } - assert!( - cmd.get_positionals().filter(|p| p.is_last_set()).count() < 2, - "Only one positional argument may have last(true) set. Found two." - ); - if cmd - .get_positionals() - .any(|p| p.is_last_set() && p.is_required_set()) - && cmd.has_subcommands() - && !cmd.is_subcommand_negates_reqs_set() - { - panic!( - "Having a required positional argument with .last(true) set *and* child \ - subcommands without setting SubcommandsNegateReqs isn't compatible." - ); - } - - true -} - -fn assert_arg(arg: &Arg) { - debug!("Arg::_debug_asserts:{}", arg.get_id()); - - // Self conflict - // TODO: this check should be recursive - assert!( - !arg.blacklist.iter().any(|x| x == arg.get_id()), - "Argument '{}' cannot conflict with itself", - arg.get_id(), - ); - - assert_eq!( - arg.get_action().takes_values(), - arg.is_takes_value_set(), - "Argument `{}`'s selected action {:?} contradicts `takes_value`", - arg.get_id(), - arg.get_action() - ); - if let Some(action_type_id) = arg.get_action().value_type_id() { - assert_eq!( - action_type_id, - arg.get_value_parser().type_id(), - "Argument `{}`'s selected action {:?} contradicts `value_parser` ({:?})", - arg.get_id(), - arg.get_action(), - arg.get_value_parser() - ); - } - - if arg.get_value_hint() != ValueHint::Unknown { - assert!( - arg.is_takes_value_set(), - "Argument '{}' has value hint but takes no value", - arg.get_id() - ); - - if arg.get_value_hint() == ValueHint::CommandWithArguments { - assert!( - arg.is_multiple_values_set(), - "Argument '{}' uses hint CommandWithArguments and must accept multiple values", - arg.get_id() - ) - } - } - - if arg.index.is_some() { - assert!( - arg.is_positional(), - "Argument '{}' is a positional argument and can't have short or long name versions", - arg.get_id() - ); - assert!( - arg.is_takes_value_set(), - "Argument '{}` is positional and it must take a value but action is {:?}{}", - arg.get_id(), - arg.get_action(), - if arg.get_id() == Id::HELP { - " (`mut_arg` no longer works with implicit `--help`)" - } else if arg.get_id() == Id::VERSION { - " (`mut_arg` no longer works with implicit `--version`)" - } else { - "" - } - ); - } - - let num_vals = arg.get_num_args().expect(INTERNAL_ERROR_MSG); - // This can be the cause of later asserts, so put this first - if num_vals != ValueRange::EMPTY { - // HACK: Don't check for flags to make the derive easier - let num_val_names = arg.get_value_names().unwrap_or(&[]).len(); - if num_vals.max_values() < num_val_names { - panic!( - "Argument {}: Too many value names ({}) compared to `num_args` ({})", - arg.get_id(), - num_val_names, - num_vals - ); - } - } - - assert_eq!( - num_vals.takes_values(), - arg.is_takes_value_set(), - "Argument {}: mismatch between `num_args` ({}) and `takes_value`", - arg.get_id(), - num_vals, - ); - assert_eq!( - num_vals.is_multiple(), - arg.is_multiple_values_set(), - "Argument {}: mismatch between `num_args` ({}) and `multiple_values`", - arg.get_id(), - num_vals, - ); - - if 1 < num_vals.min_values() { - assert!( - !arg.is_require_equals_set(), - "Argument {}: cannot accept more than 1 arg (num_args={}) with require_equals", - arg.get_id(), - num_vals - ); - } - - if num_vals == ValueRange::SINGLE { - assert!( - !arg.is_multiple_values_set(), - "Argument {}: mismatch between `num_args` and `multiple_values`", - arg.get_id() - ); - } - - assert_arg_flags(arg); -} - -fn assert_arg_flags(arg: &Arg) { - macro_rules! checker { - ($a:ident requires $($b:ident)|+) => { - if arg.$a() { - let mut s = String::new(); - - $( - if !arg.$b() { - use std::fmt::Write; - write!(&mut s, " Arg::{} is required when Arg::{} is set.\n", std::stringify!($b), std::stringify!($a)).unwrap(); - } - )+ - - if !s.is_empty() { - panic!("Argument {:?}\n{}", arg.get_id(), s) - } - } - } - } - - checker!(is_hide_possible_values_set requires is_takes_value_set); - checker!(is_allow_hyphen_values_set requires is_takes_value_set); - checker!(is_allow_negative_numbers_set requires is_takes_value_set); - checker!(is_require_equals_set requires is_takes_value_set); - checker!(is_last_set requires is_takes_value_set); - checker!(is_hide_default_value_set requires is_takes_value_set); - checker!(is_multiple_values_set requires is_takes_value_set); - checker!(is_ignore_case_set requires is_takes_value_set); -} diff --git a/vendor/clap_builder/src/builder/ext.rs b/vendor/clap_builder/src/builder/ext.rs deleted file mode 100644 index 2fb0d96..0000000 --- a/vendor/clap_builder/src/builder/ext.rs +++ /dev/null @@ -1,216 +0,0 @@ -use crate::util::AnyValueId; -use crate::util::FlatMap; - -#[derive(Default, Clone, Debug)] -pub(crate) struct Extensions { - extensions: FlatMap<AnyValueId, BoxedExtension>, -} - -impl Extensions { - #[allow(dead_code)] - pub(crate) fn get<T: Extension>(&self) -> Option<&T> { - let id = AnyValueId::of::<T>(); - self.extensions.get(&id).map(|e| e.as_ref::<T>()) - } - - #[allow(dead_code)] - pub(crate) fn get_mut<T: Extension>(&mut self) -> Option<&mut T> { - let id = AnyValueId::of::<T>(); - self.extensions.get_mut(&id).map(|e| e.as_mut::<T>()) - } - - #[allow(dead_code)] - pub(crate) fn get_or_insert_default<T: Extension + Default>(&mut self) -> &mut T { - let id = AnyValueId::of::<T>(); - self.extensions - .entry(id) - .or_insert_with(|| BoxedExtension::new(T::default())) - .as_mut::<T>() - } - - #[allow(dead_code)] - pub(crate) fn set<T: Extension + Into<BoxedEntry>>(&mut self, tagged: T) -> bool { - let BoxedEntry { id, value } = tagged.into(); - self.extensions.insert(id, value).is_some() - } - - #[allow(dead_code)] - pub(crate) fn remove<T: Extension>(&mut self) -> Option<Box<dyn Extension>> { - let id = AnyValueId::of::<T>(); - self.extensions.remove(&id).map(BoxedExtension::into_inner) - } - - pub(crate) fn update(&mut self, other: &Self) { - for (key, value) in other.extensions.iter() { - self.extensions.insert(*key, value.clone()); - } - } -} - -/// Supports conversion to `Any`. Traits to be extended by `impl_downcast!` must extend `Extension`. -pub(crate) trait Extension: std::fmt::Debug + Send + Sync + 'static { - /// Convert `Box<dyn Trait>` (where `Trait: Extension`) to `Box<dyn Any>`. - /// - /// `Box<dyn Any>` can /// then be further `downcast` into - /// `Box<ConcreteType>` where `ConcreteType` implements `Trait`. - fn into_any(self: Box<Self>) -> Box<dyn std::any::Any>; - /// Clone `&Box<dyn Trait>` (where `Trait: Extension`) to `Box<dyn Extension>`. - /// - /// `Box<dyn Any>` can /// then be further `downcast` into - // `Box<ConcreteType>` where `ConcreteType` implements `Trait`. - fn clone_extension(&self) -> Box<dyn Extension>; - /// Convert `&Trait` (where `Trait: Extension`) to `&Any`. - /// - /// This is needed since Rust cannot /// generate `&Any`'s vtable from - /// `&Trait`'s. - fn as_any(&self) -> &dyn std::any::Any; - /// Convert `&mut Trait` (where `Trait: Extension`) to `&Any`. - /// - /// This is needed since Rust cannot /// generate `&mut Any`'s vtable from - /// `&mut Trait`'s. - fn as_any_mut(&mut self) -> &mut dyn std::any::Any; -} - -impl<T> Extension for T -where - T: Clone + std::fmt::Debug + Send + Sync + 'static, -{ - fn into_any(self: Box<Self>) -> Box<dyn std::any::Any> { - self - } - fn clone_extension(&self) -> Box<dyn Extension> { - Box::new(self.clone()) - } - fn as_any(&self) -> &dyn std::any::Any { - self - } - fn as_any_mut(&mut self) -> &mut dyn std::any::Any { - self - } -} - -impl Clone for Box<dyn Extension> { - fn clone(&self) -> Self { - self.as_ref().clone_extension() - } -} - -#[derive(Clone)] -#[repr(transparent)] -struct BoxedExtension(Box<dyn Extension>); - -impl BoxedExtension { - fn new<T: Extension>(inner: T) -> Self { - Self(Box::new(inner)) - } - - fn into_inner(self) -> Box<dyn Extension> { - self.0 - } - - fn as_ref<T: Extension>(&self) -> &T { - self.0.as_ref().as_any().downcast_ref::<T>().unwrap() - } - - fn as_mut<T: Extension>(&mut self) -> &mut T { - self.0.as_mut().as_any_mut().downcast_mut::<T>().unwrap() - } -} - -impl std::fmt::Debug for BoxedExtension { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { - self.0.fmt(f) - } -} - -#[derive(Clone)] -pub(crate) struct BoxedEntry { - id: AnyValueId, - value: BoxedExtension, -} - -impl BoxedEntry { - pub(crate) fn new(r: impl Extension) -> Self { - let id = AnyValueId::from(&r); - let value = BoxedExtension::new(r); - BoxedEntry { id, value } - } -} - -impl<R: Extension> From<R> for BoxedEntry { - fn from(inner: R) -> Self { - BoxedEntry::new(inner) - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[derive(Default, Copy, Clone, Debug, PartialEq, Eq)] - struct Number(usize); - - #[test] - fn get() { - let mut ext = Extensions::default(); - ext.set(Number(10)); - assert_eq!(ext.get::<Number>(), Some(&Number(10))); - } - - #[test] - fn get_mut() { - let mut ext = Extensions::default(); - ext.set(Number(10)); - *ext.get_mut::<Number>().unwrap() = Number(20); - assert_eq!(ext.get::<Number>(), Some(&Number(20))); - } - - #[test] - fn get_or_insert_default_empty() { - let mut ext = Extensions::default(); - assert_eq!(ext.get_or_insert_default::<Number>(), &Number(0)); - } - - #[test] - fn get_or_insert_default_full() { - let mut ext = Extensions::default(); - ext.set(Number(10)); - assert_eq!(ext.get_or_insert_default::<Number>(), &Number(10)); - } - - #[test] - fn set() { - let mut ext = Extensions::default(); - assert!(!ext.set(Number(10))); - assert_eq!(ext.get::<Number>(), Some(&Number(10))); - assert!(ext.set(Number(20))); - assert_eq!(ext.get::<Number>(), Some(&Number(20))); - } - - #[test] - fn reset() { - let mut ext = Extensions::default(); - assert_eq!(ext.get::<Number>(), None); - - assert!(ext.remove::<Number>().is_none()); - assert_eq!(ext.get::<Number>(), None); - - assert!(!ext.set(Number(10))); - assert_eq!(ext.get::<Number>(), Some(&Number(10))); - - assert!(ext.remove::<Number>().is_some()); - assert_eq!(ext.get::<Number>(), None); - } - - #[test] - fn update() { - let mut ext = Extensions::default(); - assert_eq!(ext.get::<Number>(), None); - - let mut new = Extensions::default(); - assert!(!new.set(Number(10))); - - ext.update(&new); - assert_eq!(ext.get::<Number>(), Some(&Number(10))); - } -} diff --git a/vendor/clap_builder/src/builder/mod.rs b/vendor/clap_builder/src/builder/mod.rs deleted file mode 100644 index 320a453..0000000 --- a/vendor/clap_builder/src/builder/mod.rs +++ /dev/null @@ -1,67 +0,0 @@ -//! Define [`Command`] line [arguments][`Arg`] - -mod action; -mod app_settings; -mod arg; -mod arg_group; -mod arg_predicate; -mod arg_settings; -mod command; -mod ext; -mod os_str; -mod possible_value; -mod range; -mod resettable; -mod str; -mod styled_str; -mod value_hint; -mod value_parser; - -#[cfg(debug_assertions)] -mod debug_asserts; - -#[cfg(test)] -mod tests; - -pub mod styling; - -pub use self::str::Str; -pub use action::ArgAction; -pub use arg::Arg; -pub use arg_group::ArgGroup; -pub use arg_predicate::ArgPredicate; -pub use command::Command; -pub use os_str::OsStr; -pub use possible_value::PossibleValue; -pub use range::ValueRange; -pub use resettable::IntoResettable; -pub use resettable::Resettable; -pub use styled_str::StyledStr; -pub use styling::Styles; -pub use value_hint::ValueHint; -pub use value_parser::_AutoValueParser; -pub use value_parser::via_prelude; -pub use value_parser::BoolValueParser; -pub use value_parser::BoolishValueParser; -pub use value_parser::EnumValueParser; -pub use value_parser::FalseyValueParser; -pub use value_parser::MapValueParser; -pub use value_parser::NonEmptyStringValueParser; -pub use value_parser::OsStringValueParser; -pub use value_parser::PathBufValueParser; -pub use value_parser::PossibleValuesParser; -pub use value_parser::RangedI64ValueParser; -pub use value_parser::RangedU64ValueParser; -pub use value_parser::StringValueParser; -pub use value_parser::TryMapValueParser; -pub use value_parser::TypedValueParser; -pub use value_parser::UnknownArgumentValueParser; -pub use value_parser::ValueParser; -pub use value_parser::ValueParserFactory; -pub use value_parser::_AnonymousValueParser; - -#[allow(unused_imports)] -pub(crate) use self::str::Inner as StrInner; -pub(crate) use action::CountType; -pub(crate) use arg_settings::{ArgFlags, ArgSettings}; -pub(crate) use command::AppTag; diff --git a/vendor/clap_builder/src/builder/os_str.rs b/vendor/clap_builder/src/builder/os_str.rs deleted file mode 100644 index fe8928e..0000000 --- a/vendor/clap_builder/src/builder/os_str.rs +++ /dev/null @@ -1,336 +0,0 @@ -use crate::builder::Str; - -/// A UTF-8-encoded fixed string -/// -/// **NOTE:** To support dynamic values (i.e. `OsString`), enable the `string` -/// feature -#[derive(Default, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)] -pub struct OsStr { - name: Inner, -} - -impl OsStr { - #[cfg(feature = "string")] - pub(crate) fn from_string(name: std::ffi::OsString) -> Self { - Self { - name: Inner::from_string(name), - } - } - - #[cfg(feature = "string")] - pub(crate) fn from_ref(name: &std::ffi::OsStr) -> Self { - Self { - name: Inner::from_ref(name), - } - } - - pub(crate) fn from_static_ref(name: &'static std::ffi::OsStr) -> Self { - Self { - name: Inner::from_static_ref(name), - } - } - - /// Get the raw string as an `std::ffi::OsStr` - pub fn as_os_str(&self) -> &std::ffi::OsStr { - self.name.as_os_str() - } - - /// Get the raw string as an `OsString` - pub fn to_os_string(&self) -> std::ffi::OsString { - self.as_os_str().to_owned() - } -} - -impl From<&'_ OsStr> for OsStr { - fn from(id: &'_ OsStr) -> Self { - id.clone() - } -} - -#[cfg(feature = "string")] -impl From<Str> for OsStr { - fn from(id: Str) -> Self { - match id.into_inner() { - crate::builder::StrInner::Static(s) => Self::from_static_ref(std::ffi::OsStr::new(s)), - crate::builder::StrInner::Owned(s) => Self::from_ref(std::ffi::OsStr::new(s.as_ref())), - } - } -} - -#[cfg(not(feature = "string"))] -impl From<Str> for OsStr { - fn from(id: Str) -> Self { - Self::from_static_ref(std::ffi::OsStr::new(id.into_inner().0)) - } -} - -#[cfg(feature = "perf")] -impl From<&'_ Str> for OsStr { - fn from(id: &'_ Str) -> Self { - match id.clone().into_inner() { - crate::builder::StrInner::Static(s) => Self::from_static_ref(std::ffi::OsStr::new(s)), - crate::builder::StrInner::Owned(s) => Self::from_ref(std::ffi::OsStr::new(s.as_ref())), - } - } -} - -impl From<&'_ Str> for OsStr { - fn from(id: &'_ Str) -> Self { - id.clone().into() - } -} - -#[cfg(feature = "string")] -impl From<std::ffi::OsString> for OsStr { - fn from(name: std::ffi::OsString) -> Self { - Self::from_string(name) - } -} - -#[cfg(feature = "string")] -impl From<&'_ std::ffi::OsString> for OsStr { - fn from(name: &'_ std::ffi::OsString) -> Self { - Self::from_ref(name.as_os_str()) - } -} - -#[cfg(feature = "string")] -impl From<std::string::String> for OsStr { - fn from(name: std::string::String) -> Self { - Self::from_string(name.into()) - } -} - -#[cfg(feature = "string")] -impl From<&'_ std::string::String> for OsStr { - fn from(name: &'_ std::string::String) -> Self { - Self::from_ref(name.as_str().as_ref()) - } -} - -impl From<&'static std::ffi::OsStr> for OsStr { - fn from(name: &'static std::ffi::OsStr) -> Self { - Self::from_static_ref(name) - } -} - -impl From<&'_ &'static std::ffi::OsStr> for OsStr { - fn from(name: &'_ &'static std::ffi::OsStr) -> Self { - Self::from_static_ref(name) - } -} - -impl From<&'static str> for OsStr { - fn from(name: &'static str) -> Self { - Self::from_static_ref(name.as_ref()) - } -} - -impl From<&'_ &'static str> for OsStr { - fn from(name: &'_ &'static str) -> Self { - Self::from_static_ref((*name).as_ref()) - } -} - -impl From<OsStr> for std::ffi::OsString { - fn from(name: OsStr) -> Self { - name.name.into_os_string() - } -} - -impl From<OsStr> for std::path::PathBuf { - fn from(name: OsStr) -> Self { - std::ffi::OsString::from(name).into() - } -} - -impl std::fmt::Debug for OsStr { - #[inline] - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - std::fmt::Debug::fmt(self.as_os_str(), f) - } -} - -impl std::ops::Deref for OsStr { - type Target = std::ffi::OsStr; - - #[inline] - fn deref(&self) -> &std::ffi::OsStr { - self.as_os_str() - } -} - -impl AsRef<std::ffi::OsStr> for OsStr { - #[inline] - fn as_ref(&self) -> &std::ffi::OsStr { - self.as_os_str() - } -} - -impl AsRef<std::path::Path> for OsStr { - #[inline] - fn as_ref(&self) -> &std::path::Path { - std::path::Path::new(self) - } -} - -impl std::borrow::Borrow<std::ffi::OsStr> for OsStr { - #[inline] - fn borrow(&self) -> &std::ffi::OsStr { - self.as_os_str() - } -} - -impl PartialEq<str> for OsStr { - #[inline] - fn eq(&self, other: &str) -> bool { - PartialEq::eq(self.as_os_str(), other) - } -} -impl PartialEq<OsStr> for str { - #[inline] - fn eq(&self, other: &OsStr) -> bool { - PartialEq::eq(self, other.as_os_str()) - } -} - -impl PartialEq<&'_ str> for OsStr { - #[inline] - fn eq(&self, other: &&str) -> bool { - PartialEq::eq(self.as_os_str(), *other) - } -} -impl PartialEq<OsStr> for &'_ str { - #[inline] - fn eq(&self, other: &OsStr) -> bool { - PartialEq::eq(*self, other.as_os_str()) - } -} - -impl PartialEq<&'_ std::ffi::OsStr> for OsStr { - #[inline] - fn eq(&self, other: &&std::ffi::OsStr) -> bool { - PartialEq::eq(self.as_os_str(), *other) - } -} -impl PartialEq<OsStr> for &'_ std::ffi::OsStr { - #[inline] - fn eq(&self, other: &OsStr) -> bool { - PartialEq::eq(*self, other.as_os_str()) - } -} - -impl PartialEq<std::string::String> for OsStr { - #[inline] - fn eq(&self, other: &std::string::String) -> bool { - PartialEq::eq(self.as_os_str(), other.as_str()) - } -} -impl PartialEq<OsStr> for std::string::String { - #[inline] - fn eq(&self, other: &OsStr) -> bool { - PartialEq::eq(self.as_str(), other.as_os_str()) - } -} - -impl PartialEq<std::ffi::OsString> for OsStr { - #[inline] - fn eq(&self, other: &std::ffi::OsString) -> bool { - PartialEq::eq(self.as_os_str(), other.as_os_str()) - } -} -impl PartialEq<OsStr> for std::ffi::OsString { - #[inline] - fn eq(&self, other: &OsStr) -> bool { - PartialEq::eq(self.as_os_str(), other.as_os_str()) - } -} - -#[cfg(feature = "string")] -pub(crate) mod inner { - #[derive(Clone)] - pub(crate) enum Inner { - Static(&'static std::ffi::OsStr), - Owned(Box<std::ffi::OsStr>), - } - - impl Inner { - pub(crate) fn from_string(name: std::ffi::OsString) -> Self { - Self::Owned(name.into_boxed_os_str()) - } - - pub(crate) fn from_ref(name: &std::ffi::OsStr) -> Self { - Self::Owned(Box::from(name)) - } - - pub(crate) fn from_static_ref(name: &'static std::ffi::OsStr) -> Self { - Self::Static(name) - } - - pub(crate) fn as_os_str(&self) -> &std::ffi::OsStr { - match self { - Self::Static(s) => s, - Self::Owned(s) => s.as_ref(), - } - } - - pub(crate) fn into_os_string(self) -> std::ffi::OsString { - self.as_os_str().to_owned() - } - } -} - -#[cfg(not(feature = "string"))] -pub(crate) mod inner { - #[derive(Clone)] - pub(crate) struct Inner(&'static std::ffi::OsStr); - - impl Inner { - pub(crate) fn from_static_ref(name: &'static std::ffi::OsStr) -> Self { - Self(name) - } - - pub(crate) fn as_os_str(&self) -> &std::ffi::OsStr { - self.0 - } - - pub(crate) fn into_os_string(self) -> std::ffi::OsString { - self.as_os_str().to_owned() - } - } -} - -pub(crate) use inner::Inner; - -impl Default for Inner { - fn default() -> Self { - Self::from_static_ref(std::ffi::OsStr::new("")) - } -} - -impl PartialEq for Inner { - fn eq(&self, other: &Inner) -> bool { - self.as_os_str() == other.as_os_str() - } -} - -impl PartialOrd for Inner { - fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { - Some(self.cmp(other)) - } -} - -impl Ord for Inner { - fn cmp(&self, other: &Inner) -> std::cmp::Ordering { - self.as_os_str().cmp(other.as_os_str()) - } -} - -impl Eq for Inner {} - -impl std::hash::Hash for Inner { - #[inline] - fn hash<H: std::hash::Hasher>(&self, state: &mut H) { - self.as_os_str().hash(state); - } -} diff --git a/vendor/clap_builder/src/builder/possible_value.rs b/vendor/clap_builder/src/builder/possible_value.rs deleted file mode 100644 index de7e543..0000000 --- a/vendor/clap_builder/src/builder/possible_value.rs +++ /dev/null @@ -1,229 +0,0 @@ -use crate::builder::IntoResettable; -use crate::builder::Str; -use crate::builder::StyledStr; -use crate::util::eq_ignore_case; - -/// A possible value of an argument. -/// -/// This is used for specifying [possible values] of [Args]. -/// -/// See also [`PossibleValuesParser`][crate::builder::PossibleValuesParser] -/// -/// **NOTE:** Most likely you can use strings, rather than `PossibleValue` as it is only required -/// to [hide] single values from help messages and shell completions or to attach [help] to -/// possible values. -/// -/// # Examples -/// -/// ```rust -/// # use clap_builder as clap; -/// # use clap::{Arg, builder::PossibleValue, ArgAction}; -/// let cfg = Arg::new("config") -/// .action(ArgAction::Set) -/// .value_name("FILE") -/// .value_parser([ -/// PossibleValue::new("fast"), -/// PossibleValue::new("slow").help("slower than fast"), -/// PossibleValue::new("secret speed").hide(true) -/// ]); -/// ``` -/// -/// [Args]: crate::Arg -/// [possible values]: crate::builder::ValueParser::possible_values -/// [hide]: PossibleValue::hide() -/// [help]: PossibleValue::help() -#[derive(Debug, Default, Clone, PartialEq, Eq)] -pub struct PossibleValue { - name: Str, - help: Option<StyledStr>, - aliases: Vec<Str>, // (name, visible) - hide: bool, -} - -impl PossibleValue { - /// Create a [`PossibleValue`] with its name. - /// - /// The name will be used to decide whether this value was provided by the user to an argument. - /// - /// **NOTE:** In case it is not [hidden] it will also be shown in help messages for arguments - /// that use it as a [possible value] and have not hidden them through [`Arg::hide_possible_values(true)`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::builder::PossibleValue; - /// PossibleValue::new("fast") - /// # ; - /// ``` - /// [hidden]: PossibleValue::hide - /// [possible value]: crate::builder::PossibleValuesParser - /// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values() - pub fn new(name: impl Into<Str>) -> Self { - PossibleValue { - name: name.into(), - ..Default::default() - } - } - - /// Sets the help description of the value. - /// - /// This is typically displayed in completions (where supported) and should be a short, one-line - /// description. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::builder::PossibleValue; - /// PossibleValue::new("slow") - /// .help("not fast") - /// # ; - /// ``` - #[inline] - #[must_use] - pub fn help(mut self, help: impl IntoResettable<StyledStr>) -> Self { - self.help = help.into_resettable().into_option(); - self - } - - /// Hides this value from help and shell completions. - /// - /// This is an alternative to hiding through [`Arg::hide_possible_values(true)`], if you only - /// want to hide some values. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::builder::PossibleValue; - /// PossibleValue::new("secret") - /// .hide(true) - /// # ; - /// ``` - /// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values() - #[inline] - #[must_use] - pub fn hide(mut self, yes: bool) -> Self { - self.hide = yes; - self - } - - /// Sets a *hidden* alias for this argument value. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::builder::PossibleValue; - /// PossibleValue::new("slow") - /// .alias("not-fast") - /// # ; - /// ``` - #[must_use] - pub fn alias(mut self, name: impl IntoResettable<Str>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - self.aliases.push(name); - } else { - self.aliases.clear(); - } - self - } - - /// Sets multiple *hidden* aliases for this argument value. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::builder::PossibleValue; - /// PossibleValue::new("slow") - /// .aliases(["not-fast", "snake-like"]) - /// # ; - /// ``` - #[must_use] - pub fn aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { - self.aliases.extend(names.into_iter().map(|a| a.into())); - self - } -} - -/// Reflection -impl PossibleValue { - /// Get the name of the argument value - #[inline] - pub fn get_name(&self) -> &str { - self.name.as_str() - } - - /// Get the help specified for this argument, if any - #[inline] - pub fn get_help(&self) -> Option<&StyledStr> { - self.help.as_ref() - } - - /// Report if [`PossibleValue::hide`] is set - #[inline] - pub fn is_hide_set(&self) -> bool { - self.hide - } - - /// Report if PossibleValue is not hidden and has a help message - pub(crate) fn should_show_help(&self) -> bool { - !self.hide && self.help.is_some() - } - - /// Get the name if argument value is not hidden, `None` otherwise, - /// but wrapped in quotes if it contains whitespace - #[cfg(feature = "help")] - pub(crate) fn get_visible_quoted_name(&self) -> Option<std::borrow::Cow<'_, str>> { - if !self.hide { - Some(if self.name.contains(char::is_whitespace) { - format!("{:?}", self.name).into() - } else { - self.name.as_str().into() - }) - } else { - None - } - } - - /// Returns all valid values of the argument value. - /// - /// Namely the name and all aliases. - pub fn get_name_and_aliases(&self) -> impl Iterator<Item = &str> + '_ { - std::iter::once(self.get_name()).chain(self.aliases.iter().map(|s| s.as_str())) - } - - /// Tests if the value is valid for this argument value - /// - /// The value is valid if it is either the name or one of the aliases. - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::builder::PossibleValue; - /// let arg_value = PossibleValue::new("fast").alias("not-slow"); - /// - /// assert!(arg_value.matches("fast", false)); - /// assert!(arg_value.matches("not-slow", false)); - /// - /// assert!(arg_value.matches("FAST", true)); - /// assert!(!arg_value.matches("FAST", false)); - /// ``` - pub fn matches(&self, value: &str, ignore_case: bool) -> bool { - if ignore_case { - self.get_name_and_aliases() - .any(|name| eq_ignore_case(name, value)) - } else { - self.get_name_and_aliases().any(|name| name == value) - } - } -} - -impl<S: Into<Str>> From<S> for PossibleValue { - fn from(s: S) -> Self { - Self::new(s) - } -} diff --git a/vendor/clap_builder/src/builder/range.rs b/vendor/clap_builder/src/builder/range.rs deleted file mode 100644 index 158d02c..0000000 --- a/vendor/clap_builder/src/builder/range.rs +++ /dev/null @@ -1,286 +0,0 @@ -/// Values per occurrence for an argument -#[derive(Copy, Clone, PartialEq, Eq, Hash)] -pub struct ValueRange { - start_inclusive: usize, - end_inclusive: usize, -} - -impl ValueRange { - /// Nor argument values, or a flag - pub const EMPTY: Self = Self { - start_inclusive: 0, - end_inclusive: 0, - }; - - /// A single argument value, the most common case for options - pub const SINGLE: Self = Self { - start_inclusive: 1, - end_inclusive: 1, - }; - - /// Create a range - /// - /// # Panics - /// - /// If the end is less than the start (debug builds) - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::builder::ValueRange; - /// let range = ValueRange::new(5); - /// let range = ValueRange::new(5..10); - /// let range = ValueRange::new(5..=10); - /// let range = ValueRange::new(5..); - /// let range = ValueRange::new(..10); - /// let range = ValueRange::new(..=10); - /// ``` - /// - /// While this will panic: - /// ```should_panic - /// # use clap_builder as clap; - /// # use clap::builder::ValueRange; - /// let range = ValueRange::new(10..5); // Panics! - /// ``` - pub fn new(range: impl Into<Self>) -> Self { - range.into() - } - - pub(crate) fn raw(start_inclusive: usize, end_inclusive: usize) -> Self { - debug_assert!(start_inclusive <= end_inclusive); - Self { - start_inclusive, - end_inclusive, - } - } - - /// Fewest number of values the argument accepts - pub fn min_values(&self) -> usize { - self.start_inclusive - } - - /// Most number of values the argument accepts - pub fn max_values(&self) -> usize { - self.end_inclusive - } - - /// Report whether the argument takes any values (ie is a flag) - /// - /// # Examples - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::builder::ValueRange; - /// let range = ValueRange::new(5); - /// assert!(range.takes_values()); - /// - /// let range = ValueRange::new(0); - /// assert!(!range.takes_values()); - /// ``` - pub fn takes_values(&self) -> bool { - self.end_inclusive != 0 - } - - pub(crate) fn is_unbounded(&self) -> bool { - self.end_inclusive == usize::MAX - } - - pub(crate) fn is_fixed(&self) -> bool { - self.start_inclusive == self.end_inclusive - } - - pub(crate) fn is_multiple(&self) -> bool { - self.start_inclusive != self.end_inclusive || 1 < self.start_inclusive - } - - pub(crate) fn num_values(&self) -> Option<usize> { - self.is_fixed().then_some(self.start_inclusive) - } - - pub(crate) fn accepts_more(&self, current: usize) -> bool { - current < self.end_inclusive - } -} - -impl std::ops::RangeBounds<usize> for ValueRange { - fn start_bound(&self) -> std::ops::Bound<&usize> { - std::ops::Bound::Included(&self.start_inclusive) - } - - fn end_bound(&self) -> std::ops::Bound<&usize> { - std::ops::Bound::Included(&self.end_inclusive) - } -} - -impl Default for ValueRange { - fn default() -> Self { - Self::SINGLE - } -} - -impl From<usize> for ValueRange { - fn from(fixed: usize) -> Self { - (fixed..=fixed).into() - } -} - -impl From<std::ops::Range<usize>> for ValueRange { - fn from(range: std::ops::Range<usize>) -> Self { - let start_inclusive = range.start; - let end_inclusive = range.end.saturating_sub(1); - Self::raw(start_inclusive, end_inclusive) - } -} - -impl From<std::ops::RangeFull> for ValueRange { - fn from(_: std::ops::RangeFull) -> Self { - let start_inclusive = 0; - let end_inclusive = usize::MAX; - Self::raw(start_inclusive, end_inclusive) - } -} - -impl From<std::ops::RangeFrom<usize>> for ValueRange { - fn from(range: std::ops::RangeFrom<usize>) -> Self { - let start_inclusive = range.start; - let end_inclusive = usize::MAX; - Self::raw(start_inclusive, end_inclusive) - } -} - -impl From<std::ops::RangeTo<usize>> for ValueRange { - fn from(range: std::ops::RangeTo<usize>) -> Self { - let start_inclusive = 0; - let end_inclusive = range.end.saturating_sub(1); - Self::raw(start_inclusive, end_inclusive) - } -} - -impl From<std::ops::RangeInclusive<usize>> for ValueRange { - fn from(range: std::ops::RangeInclusive<usize>) -> Self { - let start_inclusive = *range.start(); - let end_inclusive = *range.end(); - Self::raw(start_inclusive, end_inclusive) - } -} - -impl From<std::ops::RangeToInclusive<usize>> for ValueRange { - fn from(range: std::ops::RangeToInclusive<usize>) -> Self { - let start_inclusive = 0; - let end_inclusive = range.end; - Self::raw(start_inclusive, end_inclusive) - } -} - -impl std::fmt::Display for ValueRange { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - ok!(self.start_inclusive.fmt(f)); - if !self.is_fixed() { - ok!("..=".fmt(f)); - ok!(self.end_inclusive.fmt(f)); - } - Ok(()) - } -} - -impl std::fmt::Debug for ValueRange { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{self}") - } -} - -#[cfg(test)] -mod test { - use super::*; - - use std::ops::RangeBounds; - - #[test] - fn from_fixed() { - let range: ValueRange = 5.into(); - assert_eq!(range.start_bound(), std::ops::Bound::Included(&5)); - assert_eq!(range.end_bound(), std::ops::Bound::Included(&5)); - assert!(range.is_fixed()); - assert!(range.is_multiple()); - assert_eq!(range.num_values(), Some(5)); - assert!(range.takes_values()); - } - - #[test] - fn from_fixed_empty() { - let range: ValueRange = 0.into(); - assert_eq!(range.start_bound(), std::ops::Bound::Included(&0)); - assert_eq!(range.end_bound(), std::ops::Bound::Included(&0)); - assert!(range.is_fixed()); - assert!(!range.is_multiple()); - assert_eq!(range.num_values(), Some(0)); - assert!(!range.takes_values()); - } - - #[test] - fn from_range() { - let range: ValueRange = (5..10).into(); - assert_eq!(range.start_bound(), std::ops::Bound::Included(&5)); - assert_eq!(range.end_bound(), std::ops::Bound::Included(&9)); - assert!(!range.is_fixed()); - assert!(range.is_multiple()); - assert_eq!(range.num_values(), None); - assert!(range.takes_values()); - } - - #[test] - fn from_range_inclusive() { - let range: ValueRange = (5..=10).into(); - assert_eq!(range.start_bound(), std::ops::Bound::Included(&5)); - assert_eq!(range.end_bound(), std::ops::Bound::Included(&10)); - assert!(!range.is_fixed()); - assert!(range.is_multiple()); - assert_eq!(range.num_values(), None); - assert!(range.takes_values()); - } - - #[test] - fn from_range_full() { - let range: ValueRange = (..).into(); - assert_eq!(range.start_bound(), std::ops::Bound::Included(&0)); - assert_eq!(range.end_bound(), std::ops::Bound::Included(&usize::MAX)); - assert!(!range.is_fixed()); - assert!(range.is_multiple()); - assert_eq!(range.num_values(), None); - assert!(range.takes_values()); - } - - #[test] - fn from_range_from() { - let range: ValueRange = (5..).into(); - assert_eq!(range.start_bound(), std::ops::Bound::Included(&5)); - assert_eq!(range.end_bound(), std::ops::Bound::Included(&usize::MAX)); - assert!(!range.is_fixed()); - assert!(range.is_multiple()); - assert_eq!(range.num_values(), None); - assert!(range.takes_values()); - } - - #[test] - fn from_range_to() { - let range: ValueRange = (..10).into(); - assert_eq!(range.start_bound(), std::ops::Bound::Included(&0)); - assert_eq!(range.end_bound(), std::ops::Bound::Included(&9)); - assert!(!range.is_fixed()); - assert!(range.is_multiple()); - assert_eq!(range.num_values(), None); - assert!(range.takes_values()); - } - - #[test] - fn from_range_to_inclusive() { - let range: ValueRange = (..=10).into(); - assert_eq!(range.start_bound(), std::ops::Bound::Included(&0)); - assert_eq!(range.end_bound(), std::ops::Bound::Included(&10)); - assert!(!range.is_fixed()); - assert!(range.is_multiple()); - assert_eq!(range.num_values(), None); - assert!(range.takes_values()); - } -} diff --git a/vendor/clap_builder/src/builder/resettable.rs b/vendor/clap_builder/src/builder/resettable.rs deleted file mode 100644 index 0572740..0000000 --- a/vendor/clap_builder/src/builder/resettable.rs +++ /dev/null @@ -1,212 +0,0 @@ -// Unlike `impl Into<Option<T>>` or `Option<impl Into<T>>`, this isn't ambiguous for the `None` -// case. - -use crate::builder::ArgAction; -use crate::builder::OsStr; -use crate::builder::Str; -use crate::builder::StyledStr; -use crate::builder::ValueHint; -use crate::builder::ValueParser; -use crate::builder::ValueRange; - -/// Clearable builder value -/// -/// This allows a builder function to both accept any value that can [`Into::into`] `T` (like -/// `&str` into `OsStr`) as well as `None` to reset it to the default. This is needed to -/// workaround a limitation where you can't have a function argument that is `impl Into<Option<T>>` -/// where `T` is `impl Into<S>` accept `None` as its type is ambiguous. -/// -/// # Example -/// -/// ```rust -/// # use clap_builder as clap; -/// # use clap::Command; -/// # use clap::Arg; -/// fn common() -> Command { -/// Command::new("cli") -/// .arg(Arg::new("input").short('i').long("input")) -/// } -/// let mut command = common(); -/// command.mut_arg("input", |arg| arg.short(None)); -/// ``` -#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum Resettable<T> { - /// Overwrite builder value - Value(T), - /// Reset builder value - Reset, -} - -impl<T> Resettable<T> { - pub(crate) fn into_option(self) -> Option<T> { - match self { - Self::Value(t) => Some(t), - Self::Reset => None, - } - } -} - -impl<T> From<T> for Resettable<T> { - fn from(other: T) -> Self { - Self::Value(other) - } -} - -impl<T> From<Option<T>> for Resettable<T> { - fn from(other: Option<T>) -> Self { - match other { - Some(inner) => Self::Value(inner), - None => Self::Reset, - } - } -} - -/// Convert to the intended resettable type -pub trait IntoResettable<T> { - /// Convert to the intended resettable type - fn into_resettable(self) -> Resettable<T>; -} - -impl IntoResettable<char> for Option<char> { - fn into_resettable(self) -> Resettable<char> { - match self { - Some(s) => Resettable::Value(s), - None => Resettable::Reset, - } - } -} - -impl IntoResettable<usize> for Option<usize> { - fn into_resettable(self) -> Resettable<usize> { - match self { - Some(s) => Resettable::Value(s), - None => Resettable::Reset, - } - } -} - -impl IntoResettable<ArgAction> for Option<ArgAction> { - fn into_resettable(self) -> Resettable<ArgAction> { - match self { - Some(s) => Resettable::Value(s), - None => Resettable::Reset, - } - } -} - -impl IntoResettable<ValueHint> for Option<ValueHint> { - fn into_resettable(self) -> Resettable<ValueHint> { - match self { - Some(s) => Resettable::Value(s), - None => Resettable::Reset, - } - } -} - -impl IntoResettable<ValueParser> for Option<ValueParser> { - fn into_resettable(self) -> Resettable<ValueParser> { - match self { - Some(s) => Resettable::Value(s), - None => Resettable::Reset, - } - } -} - -impl IntoResettable<StyledStr> for Option<&'static str> { - fn into_resettable(self) -> Resettable<StyledStr> { - match self { - Some(s) => Resettable::Value(s.into()), - None => Resettable::Reset, - } - } -} - -impl IntoResettable<OsStr> for Option<&'static str> { - fn into_resettable(self) -> Resettable<OsStr> { - match self { - Some(s) => Resettable::Value(s.into()), - None => Resettable::Reset, - } - } -} - -impl IntoResettable<Str> for Option<&'static str> { - fn into_resettable(self) -> Resettable<Str> { - match self { - Some(s) => Resettable::Value(s.into()), - None => Resettable::Reset, - } - } -} - -impl<T> IntoResettable<T> for Resettable<T> { - fn into_resettable(self) -> Resettable<T> { - self - } -} - -impl IntoResettable<char> for char { - fn into_resettable(self) -> Resettable<char> { - Resettable::Value(self) - } -} - -impl IntoResettable<usize> for usize { - fn into_resettable(self) -> Resettable<usize> { - Resettable::Value(self) - } -} - -impl IntoResettable<ArgAction> for ArgAction { - fn into_resettable(self) -> Resettable<ArgAction> { - Resettable::Value(self) - } -} - -impl IntoResettable<ValueHint> for ValueHint { - fn into_resettable(self) -> Resettable<ValueHint> { - Resettable::Value(self) - } -} - -impl<I: Into<ValueRange>> IntoResettable<ValueRange> for I { - fn into_resettable(self) -> Resettable<ValueRange> { - Resettable::Value(self.into()) - } -} - -impl<I: Into<ValueParser>> IntoResettable<ValueParser> for I { - fn into_resettable(self) -> Resettable<ValueParser> { - Resettable::Value(self.into()) - } -} - -impl<I: Into<String>> IntoResettable<String> for I { - fn into_resettable(self) -> Resettable<String> { - Resettable::Value(self.into()) - } -} - -impl<I: Into<StyledStr>> IntoResettable<StyledStr> for I { - fn into_resettable(self) -> Resettable<StyledStr> { - Resettable::Value(self.into()) - } -} - -impl<I: Into<OsStr>> IntoResettable<OsStr> for I { - fn into_resettable(self) -> Resettable<OsStr> { - Resettable::Value(self.into()) - } -} - -impl<I: Into<Str>> IntoResettable<Str> for I { - fn into_resettable(self) -> Resettable<Str> { - Resettable::Value(self.into()) - } -} - -impl<I: Into<crate::Id>> IntoResettable<crate::Id> for I { - fn into_resettable(self) -> Resettable<crate::Id> { - Resettable::Value(self.into()) - } -} diff --git a/vendor/clap_builder/src/builder/str.rs b/vendor/clap_builder/src/builder/str.rs deleted file mode 100644 index cf87691..0000000 --- a/vendor/clap_builder/src/builder/str.rs +++ /dev/null @@ -1,310 +0,0 @@ -/// A UTF-8-encoded fixed string -/// -/// **NOTE:** To support dynamic values (i.e. `String`), enable the `string` -/// feature -#[derive(Default, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)] -pub struct Str { - name: Inner, -} - -impl Str { - #[cfg(feature = "string")] - pub(crate) fn from_string(name: std::string::String) -> Self { - Self { - name: Inner::from_string(name), - } - } - - #[cfg(feature = "string")] - pub(crate) fn from_ref(name: &str) -> Self { - Self { - name: Inner::from_ref(name), - } - } - - pub(crate) fn from_static_ref(name: &'static str) -> Self { - Self { - name: Inner::from_static_ref(name), - } - } - - pub(crate) fn into_inner(self) -> Inner { - self.name - } - - /// Get the raw string of the `Str` - pub fn as_str(&self) -> &str { - self.name.as_str() - } -} - -impl From<&'_ Str> for Str { - fn from(id: &'_ Str) -> Self { - id.clone() - } -} - -#[cfg(feature = "string")] -impl From<std::string::String> for Str { - fn from(name: std::string::String) -> Self { - Self::from_string(name) - } -} - -#[cfg(feature = "string")] -impl From<&'_ std::string::String> for Str { - fn from(name: &'_ std::string::String) -> Self { - Self::from_ref(name.as_str()) - } -} - -impl From<&'static str> for Str { - fn from(name: &'static str) -> Self { - Self::from_static_ref(name) - } -} - -impl From<&'_ &'static str> for Str { - fn from(name: &'_ &'static str) -> Self { - Self::from_static_ref(name) - } -} - -impl From<Str> for String { - fn from(name: Str) -> Self { - name.name.into_string() - } -} - -impl From<Str> for Vec<u8> { - fn from(name: Str) -> Self { - String::from(name).into() - } -} - -impl From<Str> for std::ffi::OsString { - fn from(name: Str) -> Self { - String::from(name).into() - } -} - -impl From<Str> for std::path::PathBuf { - fn from(name: Str) -> Self { - String::from(name).into() - } -} - -impl std::fmt::Display for Str { - #[inline] - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - std::fmt::Display::fmt(self.as_str(), f) - } -} - -impl std::fmt::Debug for Str { - #[inline] - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - std::fmt::Debug::fmt(self.as_str(), f) - } -} - -impl std::ops::Deref for Str { - type Target = str; - - #[inline] - fn deref(&self) -> &str { - self.as_str() - } -} - -impl AsRef<str> for Str { - #[inline] - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl AsRef<[u8]> for Str { - #[inline] - fn as_ref(&self) -> &[u8] { - self.as_bytes() - } -} - -impl AsRef<std::ffi::OsStr> for Str { - #[inline] - fn as_ref(&self) -> &std::ffi::OsStr { - (**self).as_ref() - } -} - -impl AsRef<std::path::Path> for Str { - #[inline] - fn as_ref(&self) -> &std::path::Path { - std::path::Path::new(self) - } -} - -impl std::borrow::Borrow<str> for Str { - #[inline] - fn borrow(&self) -> &str { - self.as_str() - } -} - -impl PartialEq<str> for Str { - #[inline] - fn eq(&self, other: &str) -> bool { - PartialEq::eq(self.as_str(), other) - } -} -impl PartialEq<Str> for str { - #[inline] - fn eq(&self, other: &Str) -> bool { - PartialEq::eq(self, other.as_str()) - } -} - -impl PartialEq<&'_ str> for Str { - #[inline] - fn eq(&self, other: &&str) -> bool { - PartialEq::eq(self.as_str(), *other) - } -} -impl PartialEq<Str> for &'_ str { - #[inline] - fn eq(&self, other: &Str) -> bool { - PartialEq::eq(*self, other.as_str()) - } -} - -impl PartialEq<std::ffi::OsStr> for Str { - #[inline] - fn eq(&self, other: &std::ffi::OsStr) -> bool { - PartialEq::eq(self.as_str(), other) - } -} -impl PartialEq<Str> for std::ffi::OsStr { - #[inline] - fn eq(&self, other: &Str) -> bool { - PartialEq::eq(self, other.as_str()) - } -} - -impl PartialEq<&'_ std::ffi::OsStr> for Str { - #[inline] - fn eq(&self, other: &&std::ffi::OsStr) -> bool { - PartialEq::eq(self.as_str(), *other) - } -} -impl PartialEq<Str> for &'_ std::ffi::OsStr { - #[inline] - fn eq(&self, other: &Str) -> bool { - PartialEq::eq(*self, other.as_str()) - } -} - -impl PartialEq<std::string::String> for Str { - #[inline] - fn eq(&self, other: &std::string::String) -> bool { - PartialEq::eq(self.as_str(), other.as_str()) - } -} -impl PartialEq<Str> for std::string::String { - #[inline] - fn eq(&self, other: &Str) -> bool { - PartialEq::eq(self.as_str(), other.as_str()) - } -} - -#[cfg(feature = "string")] -pub(crate) mod inner { - #[derive(Clone)] - pub(crate) enum Inner { - Static(&'static str), - Owned(Box<str>), - } - - impl Inner { - pub(crate) fn from_string(name: std::string::String) -> Self { - Self::Owned(name.into_boxed_str()) - } - - pub(crate) fn from_ref(name: &str) -> Self { - Self::Owned(Box::from(name)) - } - - pub(crate) fn from_static_ref(name: &'static str) -> Self { - Self::Static(name) - } - - pub(crate) fn as_str(&self) -> &str { - match self { - Self::Static(s) => s, - Self::Owned(s) => s.as_ref(), - } - } - - pub(crate) fn into_string(self) -> String { - match self { - Self::Static(s) => s.to_owned(), - Self::Owned(s) => s.into(), - } - } - } -} - -#[cfg(not(feature = "string"))] -pub(crate) mod inner { - #[derive(Clone)] - pub(crate) struct Inner(pub(crate) &'static str); - - impl Inner { - pub(crate) fn from_static_ref(name: &'static str) -> Self { - Self(name) - } - - pub(crate) fn as_str(&self) -> &str { - self.0 - } - - pub(crate) fn into_string(self) -> String { - self.as_str().to_owned() - } - } -} - -pub(crate) use inner::Inner; - -impl Default for Inner { - fn default() -> Self { - Self::from_static_ref("") - } -} - -impl PartialEq for Inner { - fn eq(&self, other: &Inner) -> bool { - self.as_str() == other.as_str() - } -} - -impl PartialOrd for Inner { - fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { - Some(self.cmp(other)) - } -} - -impl Ord for Inner { - fn cmp(&self, other: &Inner) -> std::cmp::Ordering { - self.as_str().cmp(other.as_str()) - } -} - -impl Eq for Inner {} - -impl std::hash::Hash for Inner { - #[inline] - fn hash<H: std::hash::Hasher>(&self, state: &mut H) { - self.as_str().hash(state); - } -} diff --git a/vendor/clap_builder/src/builder/styled_str.rs b/vendor/clap_builder/src/builder/styled_str.rs deleted file mode 100644 index e06ddbc..0000000 --- a/vendor/clap_builder/src/builder/styled_str.rs +++ /dev/null @@ -1,210 +0,0 @@ -#![cfg_attr(not(feature = "usage"), allow(dead_code))] - -/// Terminal-styling container -/// -/// Styling may be encoded as [ANSI Escape Code](https://en.wikipedia.org/wiki/ANSI_escape_code) -/// -/// # Examples -/// -/// ```rust -/// # use clap_builder as clap; -/// // `cstr!` converts tags to ANSI codes -/// let after_help: &'static str = color_print::cstr!( -/// r#"<bold><underline>Examples</underline></bold> -/// -/// <dim>$</dim> <bold>mybin --input file.toml</bold> -/// "#); -/// -/// let cmd = clap::Command::new("mybin") -/// .after_help(after_help) // The `&str` gets converted into a `StyledStr` -/// // ... -/// # ; -/// ``` -#[derive(Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub struct StyledStr(String); - -impl StyledStr { - /// Create an empty buffer - pub const fn new() -> Self { - Self(String::new()) - } - - /// Display using [ANSI Escape Code](https://en.wikipedia.org/wiki/ANSI_escape_code) styling - #[cfg(feature = "color")] - pub fn ansi(&self) -> impl std::fmt::Display + '_ { - self.0.as_str() - } - - /// May allow the compiler to consolidate the `Drop`s for `msg`, reducing code size compared to - /// `styled.push_str(&msg)` - pub(crate) fn push_string(&mut self, msg: String) { - self.0.push_str(&msg); - } - - pub(crate) fn push_str(&mut self, msg: &str) { - self.0.push_str(msg); - } - - pub(crate) fn trim_start_lines(&mut self) { - if let Some(pos) = self.0.find('\n') { - let (leading, help) = self.0.split_at(pos + 1); - if leading.trim().is_empty() { - self.0 = help.to_owned() - } - } - } - - pub(crate) fn trim_end(&mut self) { - self.0 = self.0.trim_end().to_owned() - } - - #[cfg(feature = "help")] - pub(crate) fn replace_newline_var(&mut self) { - self.0 = self.0.replace("{n}", "\n"); - } - - #[cfg(feature = "help")] - pub(crate) fn indent(&mut self, initial: &str, trailing: &str) { - self.0.insert_str(0, initial); - - let mut line_sep = "\n".to_owned(); - line_sep.push_str(trailing); - self.0 = self.0.replace('\n', &line_sep); - } - - #[cfg(all(not(feature = "wrap_help"), feature = "help"))] - pub(crate) fn wrap(&mut self, _hard_width: usize) {} - - #[cfg(feature = "wrap_help")] - pub(crate) fn wrap(&mut self, hard_width: usize) { - let mut new = String::with_capacity(self.0.len()); - - let mut last = 0; - let mut wrapper = crate::output::textwrap::wrap_algorithms::LineWrapper::new(hard_width); - for content in self.iter_text() { - // Preserve styling - let current = content.as_ptr() as usize - self.0.as_str().as_ptr() as usize; - if last != current { - new.push_str(&self.0.as_str()[last..current]); - } - last = current + content.len(); - - for (i, line) in content.split_inclusive('\n').enumerate() { - if 0 < i { - // reset char count on newline, skipping the start as we might have carried - // over from a prior block of styled text - wrapper.reset(); - } - let line = crate::output::textwrap::word_separators::find_words_ascii_space(line) - .collect::<Vec<_>>(); - new.extend(wrapper.wrap(line)); - } - } - if last != self.0.len() { - new.push_str(&self.0.as_str()[last..]); - } - new = new.trim_end().to_owned(); - - self.0 = new; - } - - #[inline(never)] - #[cfg(feature = "help")] - pub(crate) fn display_width(&self) -> usize { - let mut width = 0; - for c in self.iter_text() { - width += crate::output::display_width(c); - } - width - } - - #[cfg(feature = "help")] - pub(crate) fn is_empty(&self) -> bool { - self.0.is_empty() - } - - #[cfg(feature = "help")] - pub(crate) fn as_styled_str(&self) -> &str { - &self.0 - } - - #[cfg(feature = "color")] - pub(crate) fn iter_text(&self) -> impl Iterator<Item = &str> { - anstream::adapter::strip_str(&self.0) - } - - #[cfg(not(feature = "color"))] - pub(crate) fn iter_text(&self) -> impl Iterator<Item = &str> { - [self.0.as_str()].into_iter() - } - - pub(crate) fn push_styled(&mut self, other: &Self) { - self.0.push_str(&other.0); - } - - pub(crate) fn write_to(&self, buffer: &mut dyn std::io::Write) -> std::io::Result<()> { - ok!(buffer.write_all(self.0.as_bytes())); - - Ok(()) - } -} - -impl Default for &'_ StyledStr { - fn default() -> Self { - static DEFAULT: StyledStr = StyledStr::new(); - &DEFAULT - } -} - -impl From<std::string::String> for StyledStr { - fn from(name: std::string::String) -> Self { - StyledStr(name) - } -} - -impl From<&'_ std::string::String> for StyledStr { - fn from(name: &'_ std::string::String) -> Self { - let mut styled = StyledStr::new(); - styled.push_str(name); - styled - } -} - -impl From<&'static str> for StyledStr { - fn from(name: &'static str) -> Self { - let mut styled = StyledStr::new(); - styled.push_str(name); - styled - } -} - -impl From<&'_ &'static str> for StyledStr { - fn from(name: &'_ &'static str) -> Self { - StyledStr::from(*name) - } -} - -impl std::fmt::Write for StyledStr { - #[inline] - fn write_str(&mut self, s: &str) -> Result<(), std::fmt::Error> { - self.0.push_str(s); - Ok(()) - } - - #[inline] - fn write_char(&mut self, c: char) -> Result<(), std::fmt::Error> { - self.0.push(c); - Ok(()) - } -} - -/// Color-unaware printing. Never uses coloring. -impl std::fmt::Display for StyledStr { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - for part in self.iter_text() { - part.fmt(f)?; - } - - Ok(()) - } -} diff --git a/vendor/clap_builder/src/builder/styling.rs b/vendor/clap_builder/src/builder/styling.rs deleted file mode 100644 index 3a03448..0000000 --- a/vendor/clap_builder/src/builder/styling.rs +++ /dev/null @@ -1,179 +0,0 @@ -//! Terminal [`Styles`] for help and error output - -pub use anstyle::*; - -/// Terminal styling definitions -/// -/// See also [`Command::styles`][crate::Command::styles]. -/// -/// # Example -/// -/// clap v3 styling -/// ```rust -/// # use clap_builder as clap; -/// # use clap::builder::styling::*; -/// let styles = Styles::styled() -/// .header(AnsiColor::Yellow.on_default()) -/// .usage(AnsiColor::Green.on_default()) -/// .literal(AnsiColor::Green.on_default()) -/// .placeholder(AnsiColor::Green.on_default()); -/// ``` -#[derive(Clone, Debug)] -#[allow(missing_copy_implementations)] // Large enough type that I want an explicit `clone()` for now -pub struct Styles { - header: anstyle::Style, - error: anstyle::Style, - usage: anstyle::Style, - literal: anstyle::Style, - placeholder: anstyle::Style, - valid: anstyle::Style, - invalid: anstyle::Style, -} - -impl Styles { - /// No terminal styling - pub const fn plain() -> Self { - Self { - header: anstyle::Style::new(), - error: anstyle::Style::new(), - usage: anstyle::Style::new(), - literal: anstyle::Style::new(), - placeholder: anstyle::Style::new(), - valid: anstyle::Style::new(), - invalid: anstyle::Style::new(), - } - } - - /// Default terminal styling - pub const fn styled() -> Self { - #[cfg(feature = "color")] - { - Self { - header: anstyle::Style::new().bold().underline(), - error: anstyle::Style::new() - .fg_color(Some(anstyle::Color::Ansi(anstyle::AnsiColor::Red))) - .bold(), - usage: anstyle::Style::new().bold().underline(), - literal: anstyle::Style::new().bold(), - placeholder: anstyle::Style::new(), - valid: anstyle::Style::new() - .fg_color(Some(anstyle::Color::Ansi(anstyle::AnsiColor::Green))), - invalid: anstyle::Style::new() - .fg_color(Some(anstyle::Color::Ansi(anstyle::AnsiColor::Yellow))), - } - } - #[cfg(not(feature = "color"))] - { - Self::plain() - } - } - - /// General Heading style, e.g. [`help_heading`][crate::Arg::help_heading] - #[inline] - pub const fn header(mut self, style: anstyle::Style) -> Self { - self.header = style; - self - } - - /// Error heading - #[inline] - pub const fn error(mut self, style: anstyle::Style) -> Self { - self.error = style; - self - } - - /// Usage heading - #[inline] - pub const fn usage(mut self, style: anstyle::Style) -> Self { - self.usage = style; - self - } - - /// Literal command-line syntax, e.g. `--help` - #[inline] - pub const fn literal(mut self, style: anstyle::Style) -> Self { - self.literal = style; - self - } - - /// Descriptions within command-line syntax, e.g. [`value_name`][crate::Arg::value_name] - #[inline] - pub const fn placeholder(mut self, style: anstyle::Style) -> Self { - self.placeholder = style; - self - } - - /// Highlight suggested usage - #[inline] - pub const fn valid(mut self, style: anstyle::Style) -> Self { - self.valid = style; - self - } - - /// Highlight invalid usage - #[inline] - pub const fn invalid(mut self, style: anstyle::Style) -> Self { - self.invalid = style; - self - } -} - -/// Reflection -impl Styles { - /// General Heading style, e.g. [`help_heading`][crate::Arg::help_heading] - #[inline(always)] - pub const fn get_header(&self) -> &anstyle::Style { - &self.header - } - - /// Error heading - #[inline(always)] - pub const fn get_error(&self) -> &anstyle::Style { - &self.error - } - - /// Usage heading - #[inline(always)] - pub const fn get_usage(&self) -> &anstyle::Style { - &self.usage - } - - /// Literal command-line syntax, e.g. `--help` - #[inline(always)] - pub const fn get_literal(&self) -> &anstyle::Style { - &self.literal - } - - /// Descriptions within command-line syntax, e.g. [`value_name`][crate::Arg::value_name] - #[inline(always)] - pub const fn get_placeholder(&self) -> &anstyle::Style { - &self.placeholder - } - - /// Highlight suggested usage - #[inline(always)] - pub const fn get_valid(&self) -> &anstyle::Style { - &self.valid - } - - /// Highlight invalid usage - #[inline(always)] - pub const fn get_invalid(&self) -> &anstyle::Style { - &self.invalid - } -} - -impl super::AppTag for Styles {} - -impl Default for Styles { - fn default() -> Self { - Self::styled() - } -} - -impl Default for &'_ Styles { - fn default() -> Self { - const STYLES: Styles = Styles::styled(); - &STYLES - } -} diff --git a/vendor/clap_builder/src/builder/tests.rs b/vendor/clap_builder/src/builder/tests.rs deleted file mode 100644 index 15cb8c4..0000000 --- a/vendor/clap_builder/src/builder/tests.rs +++ /dev/null @@ -1,56 +0,0 @@ -use crate::Arg; -use crate::Command; - -#[test] -fn propagate_version() { - let mut cmd = Command::new("test") - .propagate_version(true) - .version("1.1") - .subcommand(Command::new("sub1")); - cmd._propagate(); - assert_eq!( - cmd.get_subcommands().next().unwrap().get_version(), - Some("1.1") - ); -} - -#[test] -fn global_setting() { - let mut cmd = Command::new("test") - .disable_version_flag(true) - .subcommand(Command::new("subcmd")); - cmd._propagate(); - assert!(cmd - .get_subcommands() - .find(|s| s.get_name() == "subcmd") - .unwrap() - .is_disable_version_flag_set()); -} - -// This test will *fail to compile* if Command is not Send + Sync -#[test] -fn app_send_sync() { - fn foo<T: Send + Sync>(_: T) {} - foo(Command::new("test")) -} - -#[test] -fn issue_2090() { - let mut cmd = Command::new("cmd") - .disable_version_flag(true) - .subcommand(Command::new("sub")); - cmd._build_self(false); - - assert!(cmd - .get_subcommands() - .next() - .unwrap() - .is_disable_version_flag_set()); -} - -// This test will *fail to compile* if Arg is not Send + Sync -#[test] -fn arg_send_sync() { - fn foo<T: Send + Sync>(_: T) {} - foo(Arg::new("test")) -} diff --git a/vendor/clap_builder/src/builder/value_hint.rs b/vendor/clap_builder/src/builder/value_hint.rs deleted file mode 100644 index 38fa862..0000000 --- a/vendor/clap_builder/src/builder/value_hint.rs +++ /dev/null @@ -1,90 +0,0 @@ -use std::str::FromStr; - -/// Provide shell with hint on how to complete an argument. -/// -/// See [Arg::value_hint][crate::Arg::value_hint] to set this on an argument. -/// -/// See the `clap_complete` crate for completion script generation. -/// -/// Overview of which hints are supported by which shell: -/// -/// | Hint | zsh | fish[^1]| -/// | ---------------------- | --- | ------- | -/// | `AnyPath` | Yes | Yes | -/// | `FilePath` | Yes | Yes | -/// | `DirPath` | Yes | Yes | -/// | `ExecutablePath` | Yes | Partial | -/// | `CommandName` | Yes | Yes | -/// | `CommandString` | Yes | Partial | -/// | `CommandWithArguments` | Yes | | -/// | `Username` | Yes | Yes | -/// | `Hostname` | Yes | Yes | -/// | `Url` | Yes | | -/// | `EmailAddress` | Yes | | -/// -/// [^1]: fish completions currently only support named arguments (e.g. -o or --opt), not -/// positional arguments. -#[derive(Debug, Default, PartialEq, Eq, Hash, Copy, Clone)] -#[non_exhaustive] -pub enum ValueHint { - /// Default value if hint is not specified. Follows shell default behavior, which is usually - /// auto-completing filenames. - #[default] - Unknown, - /// None of the hints below apply. Disables shell completion for this argument. - Other, - /// Any existing path. - AnyPath, - /// Path to a file. - FilePath, - /// Path to a directory. - DirPath, - /// Path to an executable file. - ExecutablePath, - /// Name of a command, without arguments. May be relative to PATH, or full path to executable. - CommandName, - /// A single string containing a command and its arguments. - CommandString, - /// Capture the remaining arguments as a command name and arguments for that command. This is - /// common when writing shell wrappers that execute anther command, for example `sudo` or `env`. - /// - /// This hint is special, the argument must be a positional argument and have - /// [`.num_args(1..)`] and Command must use [`Command::trailing_var_arg(true)`]. The result is that the - /// command line `my_app ls -la /` will be parsed as `["ls", "-la", "/"]` and clap won't try to - /// parse the `-la` argument itself. - /// - /// [`Command::trailing_var_arg(true)`]: crate::Command::trailing_var_arg - /// [`.num_args(1..)`]: crate::Arg::num_args() - CommandWithArguments, - /// Name of a local operating system user. - Username, - /// Host name of a computer. - /// Shells usually parse `/etc/hosts` and `.ssh/known_hosts` to complete hostnames. - Hostname, - /// Complete web address. - Url, - /// Email address. - EmailAddress, -} - -impl FromStr for ValueHint { - type Err = String; - fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> { - Ok(match &*s.to_ascii_lowercase() { - "unknown" => ValueHint::Unknown, - "other" => ValueHint::Other, - "anypath" => ValueHint::AnyPath, - "filepath" => ValueHint::FilePath, - "dirpath" => ValueHint::DirPath, - "executablepath" => ValueHint::ExecutablePath, - "commandname" => ValueHint::CommandName, - "commandstring" => ValueHint::CommandString, - "commandwitharguments" => ValueHint::CommandWithArguments, - "username" => ValueHint::Username, - "hostname" => ValueHint::Hostname, - "url" => ValueHint::Url, - "emailaddress" => ValueHint::EmailAddress, - _ => return Err(format!("unknown ValueHint: `{s}`")), - }) - } -} diff --git a/vendor/clap_builder/src/builder/value_parser.rs b/vendor/clap_builder/src/builder/value_parser.rs deleted file mode 100644 index 1f0ef92..0000000 --- a/vendor/clap_builder/src/builder/value_parser.rs +++ /dev/null @@ -1,2712 +0,0 @@ -use std::convert::TryInto; -use std::ops::RangeBounds; - -use crate::builder::Str; -use crate::builder::StyledStr; -use crate::parser::ValueSource; -use crate::util::AnyValue; -use crate::util::AnyValueId; - -/// Parse/validate argument values -/// -/// Specified with [`Arg::value_parser`][crate::Arg::value_parser]. -/// -/// `ValueParser` defines how to convert a raw argument value into a validated and typed value for -/// use within an application. -/// -/// See -/// - [`value_parser!`][crate::value_parser] for automatically selecting an implementation for a given type -/// - [`ValueParser::new`] for additional [`TypedValueParser`] that can be used -/// -/// # Example -/// -/// ```rust -/// # use clap_builder as clap; -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("color") -/// .long("color") -/// .value_parser(["always", "auto", "never"]) -/// .default_value("auto") -/// ) -/// .arg( -/// clap::Arg::new("hostname") -/// .long("hostname") -/// .value_parser(clap::builder::NonEmptyStringValueParser::new()) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ) -/// .arg( -/// clap::Arg::new("port") -/// .long("port") -/// .value_parser(clap::value_parser!(u16).range(3000..)) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut( -/// ["cmd", "--hostname", "rust-lang.org", "--port", "3001"] -/// ).unwrap(); -/// -/// let color: &String = m.get_one("color") -/// .expect("default"); -/// assert_eq!(color, "auto"); -/// -/// let hostname: &String = m.get_one("hostname") -/// .expect("required"); -/// assert_eq!(hostname, "rust-lang.org"); -/// -/// let port: u16 = *m.get_one("port") -/// .expect("required"); -/// assert_eq!(port, 3001); -/// ``` -pub struct ValueParser(ValueParserInner); - -enum ValueParserInner { - // Common enough to optimize and for possible values - Bool, - // Common enough to optimize - String, - // Common enough to optimize - OsString, - // Common enough to optimize - PathBuf, - Other(Box<dyn AnyValueParser>), -} - -impl ValueParser { - /// Custom parser for argument values - /// - /// Pre-existing [`TypedValueParser`] implementations include: - /// - `Fn(&str) -> Result<T, E>` - /// - [`EnumValueParser`] and [`PossibleValuesParser`] for static enumerated values - /// - [`BoolishValueParser`] and [`FalseyValueParser`] for alternative `bool` implementations - /// - [`RangedI64ValueParser`] and [`RangedU64ValueParser`] - /// - [`NonEmptyStringValueParser`] - /// - /// # Example - /// - /// ```rust - /// # use clap_builder as clap; - /// type EnvVar = (String, Option<String>); - /// fn parse_env_var(env: &str) -> Result<EnvVar, std::io::Error> { - /// if let Some((var, value)) = env.split_once('=') { - /// Ok((var.to_owned(), Some(value.to_owned()))) - /// } else { - /// Ok((env.to_owned(), None)) - /// } - /// } - /// - /// let mut cmd = clap::Command::new("raw") - /// .arg( - /// clap::Arg::new("env") - /// .value_parser(clap::builder::ValueParser::new(parse_env_var)) - /// .required(true) - /// ); - /// - /// let m = cmd.try_get_matches_from_mut(["cmd", "key=value"]).unwrap(); - /// let port: &EnvVar = m.get_one("env") - /// .expect("required"); - /// assert_eq!(*port, ("key".into(), Some("value".into()))); - /// ``` - pub fn new<P>(other: P) -> Self - where - P: TypedValueParser, - { - Self(ValueParserInner::Other(Box::new(other))) - } - - /// [`bool`] parser for argument values - /// - /// See also: - /// - [`BoolishValueParser`] for different human readable bool representations - /// - [`FalseyValueParser`] for assuming non-false is true - /// - /// # Example - /// - /// ```rust - /// # use clap_builder as clap; - /// let mut cmd = clap::Command::new("raw") - /// .arg( - /// clap::Arg::new("download") - /// .value_parser(clap::value_parser!(bool)) - /// .required(true) - /// ); - /// - /// let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap(); - /// let port: bool = *m.get_one("download") - /// .expect("required"); - /// assert_eq!(port, true); - /// - /// assert!(cmd.try_get_matches_from_mut(["cmd", "forever"]).is_err()); - /// ``` - pub const fn bool() -> Self { - Self(ValueParserInner::Bool) - } - - /// [`String`] parser for argument values - /// - /// See also: - /// - [`NonEmptyStringValueParser`] - /// - /// # Example - /// - /// ```rust - /// # use clap_builder as clap; - /// let mut cmd = clap::Command::new("raw") - /// .arg( - /// clap::Arg::new("port") - /// .value_parser(clap::value_parser!(String)) - /// .required(true) - /// ); - /// - /// let m = cmd.try_get_matches_from_mut(["cmd", "80"]).unwrap(); - /// let port: &String = m.get_one("port") - /// .expect("required"); - /// assert_eq!(port, "80"); - /// ``` - pub const fn string() -> Self { - Self(ValueParserInner::String) - } - - /// [`OsString`][std::ffi::OsString] parser for argument values - /// - /// # Example - /// - /// ```rust - /// # #[cfg(unix)] { - /// # use clap_builder as clap; - /// # use clap::{Command, Arg, builder::ValueParser}; - /// use std::ffi::OsString; - /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; - /// let r = Command::new("myprog") - /// .arg( - /// Arg::new("arg") - /// .required(true) - /// .value_parser(ValueParser::os_string()) - /// ) - /// .try_get_matches_from(vec![ - /// OsString::from("myprog"), - /// OsString::from_vec(vec![0xe9]) - /// ]); - /// - /// assert!(r.is_ok()); - /// let m = r.unwrap(); - /// let arg: &OsString = m.get_one("arg") - /// .expect("required"); - /// assert_eq!(arg.as_bytes(), &[0xe9]); - /// # } - /// ``` - pub const fn os_string() -> Self { - Self(ValueParserInner::OsString) - } - - /// [`PathBuf`][std::path::PathBuf] parser for argument values - /// - /// # Example - /// - /// ```rust - /// # use clap_builder as clap; - /// # use std::path::PathBuf; - /// # use std::path::Path; - /// let mut cmd = clap::Command::new("raw") - /// .arg( - /// clap::Arg::new("output") - /// .value_parser(clap::value_parser!(PathBuf)) - /// .required(true) - /// ); - /// - /// let m = cmd.try_get_matches_from_mut(["cmd", "hello.txt"]).unwrap(); - /// let port: &PathBuf = m.get_one("output") - /// .expect("required"); - /// assert_eq!(port, Path::new("hello.txt")); - /// - /// assert!(cmd.try_get_matches_from_mut(["cmd", ""]).is_err()); - /// ``` - pub const fn path_buf() -> Self { - Self(ValueParserInner::PathBuf) - } -} - -impl ValueParser { - /// Parse into a `AnyValue` - /// - /// When `arg` is `None`, an external subcommand value is being parsed. - pub(crate) fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - source: ValueSource, - ) -> Result<AnyValue, crate::Error> { - self.any_value_parser().parse_ref_(cmd, arg, value, source) - } - - /// Describes the content of `AnyValue` - pub fn type_id(&self) -> AnyValueId { - self.any_value_parser().type_id() - } - - /// Reflect on enumerated value properties - /// - /// Error checking should not be done with this; it is mostly targeted at user-facing - /// applications like errors and completion. - pub fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - self.any_value_parser().possible_values() - } - - fn any_value_parser(&self) -> &dyn AnyValueParser { - match &self.0 { - ValueParserInner::Bool => &BoolValueParser {}, - ValueParserInner::String => &StringValueParser {}, - ValueParserInner::OsString => &OsStringValueParser {}, - ValueParserInner::PathBuf => &PathBufValueParser {}, - ValueParserInner::Other(o) => o.as_ref(), - } - } -} - -/// Convert a [`TypedValueParser`] to [`ValueParser`] -/// -/// # Example -/// -/// ```rust -/// # use clap_builder as clap; -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("hostname") -/// .long("hostname") -/// .value_parser(clap::builder::NonEmptyStringValueParser::new()) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut( -/// ["cmd", "--hostname", "rust-lang.org"] -/// ).unwrap(); -/// -/// let hostname: &String = m.get_one("hostname") -/// .expect("required"); -/// assert_eq!(hostname, "rust-lang.org"); -/// ``` -impl<P> From<P> for ValueParser -where - P: TypedValueParser + Send + Sync + 'static, -{ - fn from(p: P) -> Self { - Self::new(p) - } -} - -impl From<_AnonymousValueParser> for ValueParser { - fn from(p: _AnonymousValueParser) -> Self { - p.0 - } -} - -/// Create an `i64` [`ValueParser`] from a `N..M` range -/// -/// See [`RangedI64ValueParser`] for more control over the output type. -/// -/// See also [`RangedU64ValueParser`] -/// -/// # Examples -/// -/// ```rust -/// # use clap_builder as clap; -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("port") -/// .long("port") -/// .value_parser(3000..4000) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap(); -/// let port: i64 = *m.get_one("port") -/// .expect("required"); -/// assert_eq!(port, 3001); -/// ``` -impl From<std::ops::Range<i64>> for ValueParser { - fn from(value: std::ops::Range<i64>) -> Self { - let inner = RangedI64ValueParser::<i64>::new().range(value.start..value.end); - Self::from(inner) - } -} - -/// Create an `i64` [`ValueParser`] from a `N..=M` range -/// -/// See [`RangedI64ValueParser`] for more control over the output type. -/// -/// See also [`RangedU64ValueParser`] -/// -/// # Examples -/// -/// ```rust -/// # use clap_builder as clap; -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("port") -/// .long("port") -/// .value_parser(3000..=4000) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap(); -/// let port: i64 = *m.get_one("port") -/// .expect("required"); -/// assert_eq!(port, 3001); -/// ``` -impl From<std::ops::RangeInclusive<i64>> for ValueParser { - fn from(value: std::ops::RangeInclusive<i64>) -> Self { - let inner = RangedI64ValueParser::<i64>::new().range(value.start()..=value.end()); - Self::from(inner) - } -} - -/// Create an `i64` [`ValueParser`] from a `N..` range -/// -/// See [`RangedI64ValueParser`] for more control over the output type. -/// -/// See also [`RangedU64ValueParser`] -/// -/// # Examples -/// -/// ```rust -/// # use clap_builder as clap; -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("port") -/// .long("port") -/// .value_parser(3000..) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap(); -/// let port: i64 = *m.get_one("port") -/// .expect("required"); -/// assert_eq!(port, 3001); -/// ``` -impl From<std::ops::RangeFrom<i64>> for ValueParser { - fn from(value: std::ops::RangeFrom<i64>) -> Self { - let inner = RangedI64ValueParser::<i64>::new().range(value.start..); - Self::from(inner) - } -} - -/// Create an `i64` [`ValueParser`] from a `..M` range -/// -/// See [`RangedI64ValueParser`] for more control over the output type. -/// -/// See also [`RangedU64ValueParser`] -/// -/// # Examples -/// -/// ```rust -/// # use clap_builder as clap; -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("port") -/// .long("port") -/// .value_parser(..3000) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "80"]).unwrap(); -/// let port: i64 = *m.get_one("port") -/// .expect("required"); -/// assert_eq!(port, 80); -/// ``` -impl From<std::ops::RangeTo<i64>> for ValueParser { - fn from(value: std::ops::RangeTo<i64>) -> Self { - let inner = RangedI64ValueParser::<i64>::new().range(..value.end); - Self::from(inner) - } -} - -/// Create an `i64` [`ValueParser`] from a `..=M` range -/// -/// See [`RangedI64ValueParser`] for more control over the output type. -/// -/// See also [`RangedU64ValueParser`] -/// -/// # Examples -/// -/// ```rust -/// # use clap_builder as clap; -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("port") -/// .long("port") -/// .value_parser(..=3000) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "80"]).unwrap(); -/// let port: i64 = *m.get_one("port") -/// .expect("required"); -/// assert_eq!(port, 80); -/// ``` -impl From<std::ops::RangeToInclusive<i64>> for ValueParser { - fn from(value: std::ops::RangeToInclusive<i64>) -> Self { - let inner = RangedI64ValueParser::<i64>::new().range(..=value.end); - Self::from(inner) - } -} - -/// Create an `i64` [`ValueParser`] from a `..` range -/// -/// See [`RangedI64ValueParser`] for more control over the output type. -/// -/// See also [`RangedU64ValueParser`] -/// -/// # Examples -/// -/// ```rust -/// # use clap_builder as clap; -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("port") -/// .long("port") -/// .value_parser(..) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap(); -/// let port: i64 = *m.get_one("port") -/// .expect("required"); -/// assert_eq!(port, 3001); -/// ``` -impl From<std::ops::RangeFull> for ValueParser { - fn from(value: std::ops::RangeFull) -> Self { - let inner = RangedI64ValueParser::<i64>::new().range(value); - Self::from(inner) - } -} - -/// Create a [`ValueParser`] with [`PossibleValuesParser`] -/// -/// See [`PossibleValuesParser`] for more flexibility in creating the -/// [`PossibleValue`][crate::builder::PossibleValue]s. -/// -/// # Examples -/// -/// ```rust -/// # use clap_builder as clap; -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("color") -/// .long("color") -/// .value_parser(["always", "auto", "never"]) -/// .default_value("auto") -/// ); -/// -/// let m = cmd.try_get_matches_from_mut( -/// ["cmd", "--color", "never"] -/// ).unwrap(); -/// -/// let color: &String = m.get_one("color") -/// .expect("default"); -/// assert_eq!(color, "never"); -/// ``` -impl<P, const C: usize> From<[P; C]> for ValueParser -where - P: Into<super::PossibleValue>, -{ - fn from(values: [P; C]) -> Self { - let inner = PossibleValuesParser::from(values); - Self::from(inner) - } -} - -/// Create a [`ValueParser`] with [`PossibleValuesParser`] -/// -/// See [`PossibleValuesParser`] for more flexibility in creating the -/// [`PossibleValue`][crate::builder::PossibleValue]s. -/// -/// # Examples -/// -/// ```rust -/// # use clap_builder as clap; -/// let possible = vec!["always", "auto", "never"]; -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("color") -/// .long("color") -/// .value_parser(possible) -/// .default_value("auto") -/// ); -/// -/// let m = cmd.try_get_matches_from_mut( -/// ["cmd", "--color", "never"] -/// ).unwrap(); -/// -/// let color: &String = m.get_one("color") -/// .expect("default"); -/// assert_eq!(color, "never"); -/// ``` -impl<P> From<Vec<P>> for ValueParser -where - P: Into<super::PossibleValue>, -{ - fn from(values: Vec<P>) -> Self { - let inner = PossibleValuesParser::from(values); - Self::from(inner) - } -} - -impl std::fmt::Debug for ValueParser { - fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { - match &self.0 { - ValueParserInner::Bool => f.debug_struct("ValueParser::bool").finish(), - ValueParserInner::String => f.debug_struct("ValueParser::string").finish(), - ValueParserInner::OsString => f.debug_struct("ValueParser::os_string").finish(), - ValueParserInner::PathBuf => f.debug_struct("ValueParser::path_buf").finish(), - ValueParserInner::Other(o) => write!(f, "ValueParser::other({:?})", o.type_id()), - } - } -} - -impl Clone for ValueParser { - fn clone(&self) -> Self { - Self(match &self.0 { - ValueParserInner::Bool => ValueParserInner::Bool, - ValueParserInner::String => ValueParserInner::String, - ValueParserInner::OsString => ValueParserInner::OsString, - ValueParserInner::PathBuf => ValueParserInner::PathBuf, - ValueParserInner::Other(o) => ValueParserInner::Other(o.clone_any()), - }) - } -} - -/// A type-erased wrapper for [`TypedValueParser`]. -trait AnyValueParser: Send + Sync + 'static { - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<AnyValue, crate::Error>; - - fn parse_ref_( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - _source: ValueSource, - ) -> Result<AnyValue, crate::Error> { - self.parse_ref(cmd, arg, value) - } - - fn parse( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: std::ffi::OsString, - ) -> Result<AnyValue, crate::Error>; - - fn parse_( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: std::ffi::OsString, - _source: ValueSource, - ) -> Result<AnyValue, crate::Error> { - self.parse(cmd, arg, value) - } - - /// Describes the content of `AnyValue` - fn type_id(&self) -> AnyValueId; - - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>>; - - fn clone_any(&self) -> Box<dyn AnyValueParser>; -} - -impl<T, P> AnyValueParser for P -where - T: std::any::Any + Clone + Send + Sync + 'static, - P: TypedValueParser<Value = T>, -{ - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<AnyValue, crate::Error> { - let value = ok!(TypedValueParser::parse_ref(self, cmd, arg, value)); - Ok(AnyValue::new(value)) - } - - fn parse_ref_( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - source: ValueSource, - ) -> Result<AnyValue, crate::Error> { - let value = ok!(TypedValueParser::parse_ref_(self, cmd, arg, value, source)); - Ok(AnyValue::new(value)) - } - - fn parse( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: std::ffi::OsString, - ) -> Result<AnyValue, crate::Error> { - let value = ok!(TypedValueParser::parse(self, cmd, arg, value)); - Ok(AnyValue::new(value)) - } - - fn parse_( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: std::ffi::OsString, - source: ValueSource, - ) -> Result<AnyValue, crate::Error> { - let value = ok!(TypedValueParser::parse_(self, cmd, arg, value, source)); - Ok(AnyValue::new(value)) - } - - fn type_id(&self) -> AnyValueId { - AnyValueId::of::<T>() - } - - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - P::possible_values(self) - } - - fn clone_any(&self) -> Box<dyn AnyValueParser> { - Box::new(self.clone()) - } -} - -/// Parse/validate argument values -/// -/// As alternatives to implementing `TypedValueParser`, -/// - Use `Fn(&str) -> Result<T, E>` which implements `TypedValueParser` -/// - [`TypedValueParser::map`] or [`TypedValueParser::try_map`] to adapt an existing `TypedValueParser` -/// -/// See `ValueParserFactory` to register `TypedValueParser::Value` with -/// [`value_parser!`][crate::value_parser]. -/// -/// # Example -/// -/// ```rust -/// # #[cfg(feature = "error-context")] { -/// # use clap_builder as clap; -/// # use clap::error::ErrorKind; -/// # use clap::error::ContextKind; -/// # use clap::error::ContextValue; -/// #[derive(Clone)] -/// struct Custom(u32); -/// -/// #[derive(Clone)] -/// struct CustomValueParser; -/// -/// impl clap::builder::TypedValueParser for CustomValueParser { -/// type Value = Custom; -/// -/// fn parse_ref( -/// &self, -/// cmd: &clap::Command, -/// arg: Option<&clap::Arg>, -/// value: &std::ffi::OsStr, -/// ) -> Result<Self::Value, clap::Error> { -/// let inner = clap::value_parser!(u32); -/// let val = inner.parse_ref(cmd, arg, value)?; -/// -/// const INVALID_VALUE: u32 = 10; -/// if val == INVALID_VALUE { -/// let mut err = clap::Error::new(ErrorKind::ValueValidation) -/// .with_cmd(cmd); -/// if let Some(arg) = arg { -/// err.insert(ContextKind::InvalidArg, ContextValue::String(arg.to_string())); -/// } -/// err.insert(ContextKind::InvalidValue, ContextValue::String(INVALID_VALUE.to_string())); -/// return Err(err); -/// } -/// -/// Ok(Custom(val)) -/// } -/// } -/// # } -/// ``` -pub trait TypedValueParser: Clone + Send + Sync + 'static { - /// Argument's value type - type Value: Send + Sync + Clone; - - /// Parse the argument value - /// - /// When `arg` is `None`, an external subcommand value is being parsed. - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error>; - - /// Parse the argument value - /// - /// When `arg` is `None`, an external subcommand value is being parsed. - fn parse_ref_( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - _source: ValueSource, - ) -> Result<Self::Value, crate::Error> { - self.parse_ref(cmd, arg, value) - } - - /// Parse the argument value - /// - /// When `arg` is `None`, an external subcommand value is being parsed. - fn parse( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: std::ffi::OsString, - ) -> Result<Self::Value, crate::Error> { - self.parse_ref(cmd, arg, &value) - } - - /// Parse the argument value - /// - /// When `arg` is `None`, an external subcommand value is being parsed. - fn parse_( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: std::ffi::OsString, - _source: ValueSource, - ) -> Result<Self::Value, crate::Error> { - self.parse(cmd, arg, value) - } - - /// Reflect on enumerated value properties - /// - /// Error checking should not be done with this; it is mostly targeted at user-facing - /// applications like errors and completion. - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - None - } - - /// Adapt a `TypedValueParser` from one value to another - /// - /// # Example - /// - /// ```rust - /// # use clap_builder as clap; - /// # use clap::Command; - /// # use clap::Arg; - /// # use clap::builder::TypedValueParser as _; - /// # use clap::builder::BoolishValueParser; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::SetTrue) - /// .value_parser( - /// BoolishValueParser::new() - /// .map(|b| -> usize { - /// if b { 10 } else { 5 } - /// }) - /// ) - /// ); - /// - /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_one::<usize>("flag").copied(), - /// Some(10) - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_one::<usize>("flag").copied(), - /// Some(5) - /// ); - /// ``` - fn map<T, F>(self, func: F) -> MapValueParser<Self, F> - where - T: Send + Sync + Clone, - F: Fn(Self::Value) -> T + Clone, - { - MapValueParser::new(self, func) - } - - /// Adapt a `TypedValueParser` from one value to another - /// - /// # Example - /// - /// ```rust - /// # use clap_builder as clap; - /// # use std::ffi::OsString; - /// # use std::ffi::OsStr; - /// # use std::path::PathBuf; - /// # use std::path::Path; - /// # use clap::Command; - /// # use clap::Arg; - /// # use clap::builder::TypedValueParser as _; - /// # use clap::builder::OsStringValueParser; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .value_parser( - /// OsStringValueParser::new() - /// .try_map(verify_ext) - /// ) - /// ); - /// - /// fn verify_ext(os: OsString) -> Result<PathBuf, &'static str> { - /// let path = PathBuf::from(os); - /// if path.extension() != Some(OsStr::new("rs")) { - /// return Err("only Rust files are supported"); - /// } - /// Ok(path) - /// } - /// - /// let error = cmd.clone().try_get_matches_from(["mycmd", "--flag", "foo.txt"]).unwrap_err(); - /// error.print(); - /// - /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "foo.rs"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_one::<PathBuf>("flag").map(|s| s.as_path()), - /// Some(Path::new("foo.rs")) - /// ); - /// ``` - fn try_map<T, E, F>(self, func: F) -> TryMapValueParser<Self, F> - where - F: Fn(Self::Value) -> Result<T, E> + Clone + Send + Sync + 'static, - T: Send + Sync + Clone, - E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>, - { - TryMapValueParser::new(self, func) - } -} - -impl<F, T, E> TypedValueParser for F -where - F: Fn(&str) -> Result<T, E> + Clone + Send + Sync + 'static, - E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>, - T: Send + Sync + Clone, -{ - type Value = T; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - let value = ok!(value.to_str().ok_or_else(|| { - crate::Error::invalid_utf8( - cmd, - crate::output::Usage::new(cmd).create_usage_with_title(&[]), - ) - })); - let value = ok!((self)(value).map_err(|e| { - let arg = arg - .map(|a| a.to_string()) - .unwrap_or_else(|| "...".to_owned()); - crate::Error::value_validation(arg, value.to_owned(), e.into()).with_cmd(cmd) - })); - Ok(value) - } -} - -/// Implementation for [`ValueParser::string`] -/// -/// Useful for composing new [`TypedValueParser`]s -#[derive(Copy, Clone, Debug)] -#[non_exhaustive] -pub struct StringValueParser {} - -impl StringValueParser { - /// Implementation for [`ValueParser::string`] - pub fn new() -> Self { - Self {} - } -} - -impl TypedValueParser for StringValueParser { - type Value = String; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - TypedValueParser::parse(self, cmd, arg, value.to_owned()) - } - - fn parse( - &self, - cmd: &crate::Command, - _arg: Option<&crate::Arg>, - value: std::ffi::OsString, - ) -> Result<Self::Value, crate::Error> { - let value = ok!(value.into_string().map_err(|_| { - crate::Error::invalid_utf8( - cmd, - crate::output::Usage::new(cmd).create_usage_with_title(&[]), - ) - })); - Ok(value) - } -} - -impl Default for StringValueParser { - fn default() -> Self { - Self::new() - } -} - -/// Implementation for [`ValueParser::os_string`] -/// -/// Useful for composing new [`TypedValueParser`]s -#[derive(Copy, Clone, Debug)] -#[non_exhaustive] -pub struct OsStringValueParser {} - -impl OsStringValueParser { - /// Implementation for [`ValueParser::os_string`] - pub fn new() -> Self { - Self {} - } -} - -impl TypedValueParser for OsStringValueParser { - type Value = std::ffi::OsString; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - TypedValueParser::parse(self, cmd, arg, value.to_owned()) - } - - fn parse( - &self, - _cmd: &crate::Command, - _arg: Option<&crate::Arg>, - value: std::ffi::OsString, - ) -> Result<Self::Value, crate::Error> { - Ok(value) - } -} - -impl Default for OsStringValueParser { - fn default() -> Self { - Self::new() - } -} - -/// Implementation for [`ValueParser::path_buf`] -/// -/// Useful for composing new [`TypedValueParser`]s -#[derive(Copy, Clone, Debug)] -#[non_exhaustive] -pub struct PathBufValueParser {} - -impl PathBufValueParser { - /// Implementation for [`ValueParser::path_buf`] - pub fn new() -> Self { - Self {} - } -} - -impl TypedValueParser for PathBufValueParser { - type Value = std::path::PathBuf; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - TypedValueParser::parse(self, cmd, arg, value.to_owned()) - } - - fn parse( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: std::ffi::OsString, - ) -> Result<Self::Value, crate::Error> { - if value.is_empty() { - return Err(crate::Error::empty_value( - cmd, - &[], - arg.map(ToString::to_string) - .unwrap_or_else(|| "...".to_owned()), - )); - } - Ok(Self::Value::from(value)) - } -} - -impl Default for PathBufValueParser { - fn default() -> Self { - Self::new() - } -} - -/// Parse an [`ValueEnum`][crate::ValueEnum] value. -/// -/// See also: -/// - [`PossibleValuesParser`] -/// -/// # Example -/// -/// ```rust -/// # use clap_builder as clap; -/// # use std::ffi::OsStr; -/// # use clap::ColorChoice; -/// # use clap::builder::TypedValueParser; -/// # let cmd = clap::Command::new("test"); -/// # let arg = None; -/// -/// // Usage -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("color") -/// .value_parser(clap::builder::EnumValueParser::<ColorChoice>::new()) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "always"]).unwrap(); -/// let port: ColorChoice = *m.get_one("color") -/// .expect("required"); -/// assert_eq!(port, ColorChoice::Always); -/// -/// // Semantics -/// let value_parser = clap::builder::EnumValueParser::<ColorChoice>::new(); -/// // or -/// let value_parser = clap::value_parser!(ColorChoice); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err()); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("always")).unwrap(), ColorChoice::Always); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("auto")).unwrap(), ColorChoice::Auto); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("never")).unwrap(), ColorChoice::Never); -/// ``` -#[derive(Clone, Debug)] -pub struct EnumValueParser<E: crate::ValueEnum + Clone + Send + Sync + 'static>( - std::marker::PhantomData<E>, -); - -impl<E: crate::ValueEnum + Clone + Send + Sync + 'static> EnumValueParser<E> { - /// Parse an [`ValueEnum`][crate::ValueEnum] - pub fn new() -> Self { - let phantom: std::marker::PhantomData<E> = Default::default(); - Self(phantom) - } -} - -impl<E: crate::ValueEnum + Clone + Send + Sync + 'static> TypedValueParser for EnumValueParser<E> { - type Value = E; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - let ignore_case = arg.map(|a| a.is_ignore_case_set()).unwrap_or(false); - let possible_vals = || { - E::value_variants() - .iter() - .filter_map(|v| v.to_possible_value()) - .filter(|v| !v.is_hide_set()) - .map(|v| v.get_name().to_owned()) - .collect::<Vec<_>>() - }; - - let value = ok!(value.to_str().ok_or_else(|| { - crate::Error::invalid_value( - cmd, - value.to_string_lossy().into_owned(), - &possible_vals(), - arg.map(ToString::to_string) - .unwrap_or_else(|| "...".to_owned()), - ) - })); - let value = ok!(E::value_variants() - .iter() - .find(|v| { - v.to_possible_value() - .expect("ValueEnum::value_variants contains only values with a corresponding ValueEnum::to_possible_value") - .matches(value, ignore_case) - }) - .ok_or_else(|| { - crate::Error::invalid_value( - cmd, - value.to_owned(), - &possible_vals(), - arg.map(ToString::to_string) - .unwrap_or_else(|| "...".to_owned()), - ) - })) - .clone(); - Ok(value) - } - - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - Some(Box::new( - E::value_variants() - .iter() - .filter_map(|v| v.to_possible_value()), - )) - } -} - -impl<E: crate::ValueEnum + Clone + Send + Sync + 'static> Default for EnumValueParser<E> { - fn default() -> Self { - Self::new() - } -} - -/// Verify the value is from an enumerated set of [`PossibleValue`][crate::builder::PossibleValue]. -/// -/// See also: -/// - [`EnumValueParser`] for directly supporting [`ValueEnum`][crate::ValueEnum] types -/// - [`TypedValueParser::map`] for adapting values to a more specialized type, like an external -/// enums that can't implement [`ValueEnum`][crate::ValueEnum] -/// -/// # Example -/// -/// Usage: -/// ```rust -/// # use clap_builder as clap; -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("color") -/// .value_parser(clap::builder::PossibleValuesParser::new(["always", "auto", "never"])) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "always"]).unwrap(); -/// let port: &String = m.get_one("color") -/// .expect("required"); -/// assert_eq!(port, "always"); -/// ``` -/// -/// Semantics: -/// ```rust -/// # use clap_builder as clap; -/// # use std::ffi::OsStr; -/// # use clap::builder::TypedValueParser; -/// # let cmd = clap::Command::new("test"); -/// # let arg = None; -/// let value_parser = clap::builder::PossibleValuesParser::new(["always", "auto", "never"]); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err()); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("always")).unwrap(), "always"); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("auto")).unwrap(), "auto"); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("never")).unwrap(), "never"); -/// ``` -#[derive(Clone, Debug)] -pub struct PossibleValuesParser(Vec<super::PossibleValue>); - -impl PossibleValuesParser { - /// Verify the value is from an enumerated set of [`PossibleValue`][crate::builder::PossibleValue]. - pub fn new(values: impl Into<PossibleValuesParser>) -> Self { - values.into() - } -} - -impl TypedValueParser for PossibleValuesParser { - type Value = String; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - TypedValueParser::parse(self, cmd, arg, value.to_owned()) - } - - fn parse( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: std::ffi::OsString, - ) -> Result<String, crate::Error> { - let value = ok!(value.into_string().map_err(|_| { - crate::Error::invalid_utf8( - cmd, - crate::output::Usage::new(cmd).create_usage_with_title(&[]), - ) - })); - - let ignore_case = arg.map(|a| a.is_ignore_case_set()).unwrap_or(false); - if self.0.iter().any(|v| v.matches(&value, ignore_case)) { - Ok(value) - } else { - let possible_vals = self - .0 - .iter() - .filter(|v| !v.is_hide_set()) - .map(|v| v.get_name().to_owned()) - .collect::<Vec<_>>(); - - Err(crate::Error::invalid_value( - cmd, - value, - &possible_vals, - arg.map(ToString::to_string) - .unwrap_or_else(|| "...".to_owned()), - )) - } - } - - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - Some(Box::new(self.0.iter().cloned())) - } -} - -impl<I, T> From<I> for PossibleValuesParser -where - I: IntoIterator<Item = T>, - T: Into<super::PossibleValue>, -{ - fn from(values: I) -> Self { - Self(values.into_iter().map(|t| t.into()).collect()) - } -} - -/// Parse number that fall within a range of values -/// -/// **NOTE:** To capture negative values, you will also need to set -/// [`Arg::allow_negative_numbers`][crate::Arg::allow_negative_numbers] or -/// [`Arg::allow_hyphen_values`][crate::Arg::allow_hyphen_values]. -/// -/// # Example -/// -/// Usage: -/// ```rust -/// # use clap_builder as clap; -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("port") -/// .long("port") -/// .value_parser(clap::value_parser!(u16).range(3000..)) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap(); -/// let port: u16 = *m.get_one("port") -/// .expect("required"); -/// assert_eq!(port, 3001); -/// ``` -/// -/// Semantics: -/// ```rust -/// # use clap_builder as clap; -/// # use std::ffi::OsStr; -/// # use clap::builder::TypedValueParser; -/// # let cmd = clap::Command::new("test"); -/// # let arg = None; -/// let value_parser = clap::builder::RangedI64ValueParser::<i32>::new().range(-1..200); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("-200")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("300")).is_err()); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("-1")).unwrap(), -1); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), 0); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("50")).unwrap(), 50); -/// ``` -#[derive(Copy, Clone, Debug)] -pub struct RangedI64ValueParser<T: std::convert::TryFrom<i64> + Clone + Send + Sync = i64> { - bounds: (std::ops::Bound<i64>, std::ops::Bound<i64>), - target: std::marker::PhantomData<T>, -} - -impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync> RangedI64ValueParser<T> { - /// Select full range of `i64` - pub fn new() -> Self { - Self::from(..) - } - - /// Narrow the supported range - pub fn range<B: RangeBounds<i64>>(mut self, range: B) -> Self { - // Consideration: when the user does `value_parser!(u8).range()` - // - Avoid programming mistakes by accidentally expanding the range - // - Make it convenient to limit the range like with `..10` - let start = match range.start_bound() { - l @ std::ops::Bound::Included(i) => { - debug_assert!( - self.bounds.contains(i), - "{} must be in {:?}", - i, - self.bounds - ); - l.cloned() - } - l @ std::ops::Bound::Excluded(i) => { - debug_assert!( - self.bounds.contains(&i.saturating_add(1)), - "{} must be in {:?}", - i, - self.bounds - ); - l.cloned() - } - std::ops::Bound::Unbounded => self.bounds.start_bound().cloned(), - }; - let end = match range.end_bound() { - l @ std::ops::Bound::Included(i) => { - debug_assert!( - self.bounds.contains(i), - "{} must be in {:?}", - i, - self.bounds - ); - l.cloned() - } - l @ std::ops::Bound::Excluded(i) => { - debug_assert!( - self.bounds.contains(&i.saturating_sub(1)), - "{} must be in {:?}", - i, - self.bounds - ); - l.cloned() - } - std::ops::Bound::Unbounded => self.bounds.end_bound().cloned(), - }; - self.bounds = (start, end); - self - } - - fn format_bounds(&self) -> String { - let mut result = match self.bounds.0 { - std::ops::Bound::Included(i) => i.to_string(), - std::ops::Bound::Excluded(i) => i.saturating_add(1).to_string(), - std::ops::Bound::Unbounded => i64::MIN.to_string(), - }; - result.push_str(".."); - match self.bounds.1 { - std::ops::Bound::Included(i) => { - result.push('='); - result.push_str(&i.to_string()); - } - std::ops::Bound::Excluded(i) => { - result.push_str(&i.to_string()); - } - std::ops::Bound::Unbounded => { - result.push_str(&i64::MAX.to_string()); - } - } - result - } -} - -impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync + 'static> TypedValueParser - for RangedI64ValueParser<T> -where - <T as std::convert::TryFrom<i64>>::Error: Send + Sync + 'static + std::error::Error + ToString, -{ - type Value = T; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - raw_value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - let value = ok!(raw_value.to_str().ok_or_else(|| { - crate::Error::invalid_utf8( - cmd, - crate::output::Usage::new(cmd).create_usage_with_title(&[]), - ) - })); - let value = ok!(value.parse::<i64>().map_err(|err| { - let arg = arg - .map(|a| a.to_string()) - .unwrap_or_else(|| "...".to_owned()); - crate::Error::value_validation( - arg, - raw_value.to_string_lossy().into_owned(), - err.into(), - ) - .with_cmd(cmd) - })); - if !self.bounds.contains(&value) { - let arg = arg - .map(|a| a.to_string()) - .unwrap_or_else(|| "...".to_owned()); - return Err(crate::Error::value_validation( - arg, - raw_value.to_string_lossy().into_owned(), - format!("{} is not in {}", value, self.format_bounds()).into(), - ) - .with_cmd(cmd)); - } - - let value: Result<Self::Value, _> = value.try_into(); - let value = ok!(value.map_err(|err| { - let arg = arg - .map(|a| a.to_string()) - .unwrap_or_else(|| "...".to_owned()); - crate::Error::value_validation( - arg, - raw_value.to_string_lossy().into_owned(), - err.into(), - ) - .with_cmd(cmd) - })); - - Ok(value) - } -} - -impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync, B: RangeBounds<i64>> From<B> - for RangedI64ValueParser<T> -{ - fn from(range: B) -> Self { - Self { - bounds: (range.start_bound().cloned(), range.end_bound().cloned()), - target: Default::default(), - } - } -} - -impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync> Default for RangedI64ValueParser<T> { - fn default() -> Self { - Self::new() - } -} - -/// Parse number that fall within a range of values -/// -/// # Example -/// -/// Usage: -/// ```rust -/// # use clap_builder as clap; -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("port") -/// .long("port") -/// .value_parser(clap::value_parser!(u64).range(3000..)) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap(); -/// let port: u64 = *m.get_one("port") -/// .expect("required"); -/// assert_eq!(port, 3001); -/// ``` -/// -/// Semantics: -/// ```rust -/// # use clap_builder as clap; -/// # use std::ffi::OsStr; -/// # use clap::builder::TypedValueParser; -/// # let cmd = clap::Command::new("test"); -/// # let arg = None; -/// let value_parser = clap::builder::RangedU64ValueParser::<u32>::new().range(0..200); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("-200")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("300")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("-1")).is_err()); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), 0); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("50")).unwrap(), 50); -/// ``` -#[derive(Copy, Clone, Debug)] -pub struct RangedU64ValueParser<T: std::convert::TryFrom<u64> = u64> { - bounds: (std::ops::Bound<u64>, std::ops::Bound<u64>), - target: std::marker::PhantomData<T>, -} - -impl<T: std::convert::TryFrom<u64>> RangedU64ValueParser<T> { - /// Select full range of `u64` - pub fn new() -> Self { - Self::from(..) - } - - /// Narrow the supported range - pub fn range<B: RangeBounds<u64>>(mut self, range: B) -> Self { - // Consideration: when the user does `value_parser!(u8).range()` - // - Avoid programming mistakes by accidentally expanding the range - // - Make it convenient to limit the range like with `..10` - let start = match range.start_bound() { - l @ std::ops::Bound::Included(i) => { - debug_assert!( - self.bounds.contains(i), - "{} must be in {:?}", - i, - self.bounds - ); - l.cloned() - } - l @ std::ops::Bound::Excluded(i) => { - debug_assert!( - self.bounds.contains(&i.saturating_add(1)), - "{} must be in {:?}", - i, - self.bounds - ); - l.cloned() - } - std::ops::Bound::Unbounded => self.bounds.start_bound().cloned(), - }; - let end = match range.end_bound() { - l @ std::ops::Bound::Included(i) => { - debug_assert!( - self.bounds.contains(i), - "{} must be in {:?}", - i, - self.bounds - ); - l.cloned() - } - l @ std::ops::Bound::Excluded(i) => { - debug_assert!( - self.bounds.contains(&i.saturating_sub(1)), - "{} must be in {:?}", - i, - self.bounds - ); - l.cloned() - } - std::ops::Bound::Unbounded => self.bounds.end_bound().cloned(), - }; - self.bounds = (start, end); - self - } - - fn format_bounds(&self) -> String { - let mut result = match self.bounds.0 { - std::ops::Bound::Included(i) => i.to_string(), - std::ops::Bound::Excluded(i) => i.saturating_add(1).to_string(), - std::ops::Bound::Unbounded => u64::MIN.to_string(), - }; - result.push_str(".."); - match self.bounds.1 { - std::ops::Bound::Included(i) => { - result.push('='); - result.push_str(&i.to_string()); - } - std::ops::Bound::Excluded(i) => { - result.push_str(&i.to_string()); - } - std::ops::Bound::Unbounded => { - result.push_str(&u64::MAX.to_string()); - } - } - result - } -} - -impl<T: std::convert::TryFrom<u64> + Clone + Send + Sync + 'static> TypedValueParser - for RangedU64ValueParser<T> -where - <T as std::convert::TryFrom<u64>>::Error: Send + Sync + 'static + std::error::Error + ToString, -{ - type Value = T; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - raw_value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - let value = ok!(raw_value.to_str().ok_or_else(|| { - crate::Error::invalid_utf8( - cmd, - crate::output::Usage::new(cmd).create_usage_with_title(&[]), - ) - })); - let value = ok!(value.parse::<u64>().map_err(|err| { - let arg = arg - .map(|a| a.to_string()) - .unwrap_or_else(|| "...".to_owned()); - crate::Error::value_validation( - arg, - raw_value.to_string_lossy().into_owned(), - err.into(), - ) - .with_cmd(cmd) - })); - if !self.bounds.contains(&value) { - let arg = arg - .map(|a| a.to_string()) - .unwrap_or_else(|| "...".to_owned()); - return Err(crate::Error::value_validation( - arg, - raw_value.to_string_lossy().into_owned(), - format!("{} is not in {}", value, self.format_bounds()).into(), - ) - .with_cmd(cmd)); - } - - let value: Result<Self::Value, _> = value.try_into(); - let value = ok!(value.map_err(|err| { - let arg = arg - .map(|a| a.to_string()) - .unwrap_or_else(|| "...".to_owned()); - crate::Error::value_validation( - arg, - raw_value.to_string_lossy().into_owned(), - err.into(), - ) - .with_cmd(cmd) - })); - - Ok(value) - } -} - -impl<T: std::convert::TryFrom<u64>, B: RangeBounds<u64>> From<B> for RangedU64ValueParser<T> { - fn from(range: B) -> Self { - Self { - bounds: (range.start_bound().cloned(), range.end_bound().cloned()), - target: Default::default(), - } - } -} - -impl<T: std::convert::TryFrom<u64>> Default for RangedU64ValueParser<T> { - fn default() -> Self { - Self::new() - } -} - -/// Implementation for [`ValueParser::bool`] -/// -/// Useful for composing new [`TypedValueParser`]s -#[derive(Copy, Clone, Debug)] -#[non_exhaustive] -pub struct BoolValueParser {} - -impl BoolValueParser { - /// Implementation for [`ValueParser::bool`] - pub fn new() -> Self { - Self {} - } - - fn possible_values() -> impl Iterator<Item = crate::builder::PossibleValue> { - ["true", "false"] - .iter() - .copied() - .map(crate::builder::PossibleValue::new) - } -} - -impl TypedValueParser for BoolValueParser { - type Value = bool; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - let value = if value == std::ffi::OsStr::new("true") { - true - } else if value == std::ffi::OsStr::new("false") { - false - } else { - // Intentionally showing hidden as we hide all of them - let possible_vals = Self::possible_values() - .map(|v| v.get_name().to_owned()) - .collect::<Vec<_>>(); - - return Err(crate::Error::invalid_value( - cmd, - value.to_string_lossy().into_owned(), - &possible_vals, - arg.map(ToString::to_string) - .unwrap_or_else(|| "...".to_owned()), - )); - }; - Ok(value) - } - - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - Some(Box::new(Self::possible_values())) - } -} - -impl Default for BoolValueParser { - fn default() -> Self { - Self::new() - } -} - -/// Parse false-like string values, everything else is `true` -/// -/// See also: -/// - [`ValueParser::bool`] for assuming non-false is true -/// - [`BoolishValueParser`] for different human readable bool representations -/// -/// # Example -/// -/// Usage: -/// ```rust -/// # use clap_builder as clap; -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("append") -/// .value_parser(clap::builder::FalseyValueParser::new()) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap(); -/// let port: bool = *m.get_one("append") -/// .expect("required"); -/// assert_eq!(port, true); -/// ``` -/// -/// Semantics: -/// ```rust -/// # use clap_builder as clap; -/// # use std::ffi::OsStr; -/// # use clap::builder::TypedValueParser; -/// # let cmd = clap::Command::new("test"); -/// # let arg = None; -/// let value_parser = clap::builder::FalseyValueParser::new(); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).unwrap(), true); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("100")).unwrap(), true); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).unwrap(), false); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("false")).unwrap(), false); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("No")).unwrap(), false); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("oFF")).unwrap(), false); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), false); -/// ``` -#[derive(Copy, Clone, Debug)] -#[non_exhaustive] -pub struct FalseyValueParser {} - -impl FalseyValueParser { - /// Parse false-like string values, everything else is `true` - pub fn new() -> Self { - Self {} - } - - fn possible_values() -> impl Iterator<Item = crate::builder::PossibleValue> { - crate::util::TRUE_LITERALS - .iter() - .chain(crate::util::FALSE_LITERALS.iter()) - .copied() - .map(|l| crate::builder::PossibleValue::new(l).hide(l != "true" && l != "false")) - } -} - -impl TypedValueParser for FalseyValueParser { - type Value = bool; - - fn parse_ref( - &self, - cmd: &crate::Command, - _arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - let value = ok!(value.to_str().ok_or_else(|| { - crate::Error::invalid_utf8( - cmd, - crate::output::Usage::new(cmd).create_usage_with_title(&[]), - ) - })); - let value = if value.is_empty() { - false - } else { - crate::util::str_to_bool(value).unwrap_or(true) - }; - Ok(value) - } - - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - Some(Box::new(Self::possible_values())) - } -} - -impl Default for FalseyValueParser { - fn default() -> Self { - Self::new() - } -} - -/// Parse bool-like string values, everything else is `true` -/// -/// See also: -/// - [`ValueParser::bool`] for different human readable bool representations -/// - [`FalseyValueParser`] for assuming non-false is true -/// -/// # Example -/// -/// Usage: -/// ```rust -/// # use clap_builder as clap; -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("append") -/// .value_parser(clap::builder::BoolishValueParser::new()) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap(); -/// let port: bool = *m.get_one("append") -/// .expect("required"); -/// assert_eq!(port, true); -/// ``` -/// -/// Semantics: -/// ```rust -/// # use clap_builder as clap; -/// # use std::ffi::OsStr; -/// # use clap::builder::TypedValueParser; -/// # let cmd = clap::Command::new("test"); -/// # let arg = None; -/// let value_parser = clap::builder::BoolishValueParser::new(); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("100")).is_err()); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("true")).unwrap(), true); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("Yes")).unwrap(), true); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("oN")).unwrap(), true); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("1")).unwrap(), true); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("false")).unwrap(), false); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("No")).unwrap(), false); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("oFF")).unwrap(), false); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), false); -/// ``` -#[derive(Copy, Clone, Debug)] -#[non_exhaustive] -pub struct BoolishValueParser {} - -impl BoolishValueParser { - /// Parse bool-like string values, everything else is `true` - pub fn new() -> Self { - Self {} - } - - fn possible_values() -> impl Iterator<Item = crate::builder::PossibleValue> { - crate::util::TRUE_LITERALS - .iter() - .chain(crate::util::FALSE_LITERALS.iter()) - .copied() - .map(|l| crate::builder::PossibleValue::new(l).hide(l != "true" && l != "false")) - } -} - -impl TypedValueParser for BoolishValueParser { - type Value = bool; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - let value = ok!(value.to_str().ok_or_else(|| { - crate::Error::invalid_utf8( - cmd, - crate::output::Usage::new(cmd).create_usage_with_title(&[]), - ) - })); - let value = ok!(crate::util::str_to_bool(value).ok_or_else(|| { - let arg = arg - .map(|a| a.to_string()) - .unwrap_or_else(|| "...".to_owned()); - crate::Error::value_validation(arg, value.to_owned(), "value was not a boolean".into()) - .with_cmd(cmd) - })); - Ok(value) - } - - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - Some(Box::new(Self::possible_values())) - } -} - -impl Default for BoolishValueParser { - fn default() -> Self { - Self::new() - } -} - -/// Parse non-empty string values -/// -/// See also: -/// - [`ValueParser::string`] -/// -/// # Example -/// -/// Usage: -/// ```rust -/// # use clap_builder as clap; -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("append") -/// .value_parser(clap::builder::NonEmptyStringValueParser::new()) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap(); -/// let port: &String = m.get_one("append") -/// .expect("required"); -/// assert_eq!(port, "true"); -/// ``` -/// -/// Semantics: -/// ```rust -/// # use clap_builder as clap; -/// # use std::ffi::OsStr; -/// # use clap::builder::TypedValueParser; -/// # let cmd = clap::Command::new("test"); -/// # let arg = None; -/// let value_parser = clap::builder::NonEmptyStringValueParser::new(); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).unwrap(), "random"); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err()); -/// ``` -#[derive(Copy, Clone, Debug)] -#[non_exhaustive] -pub struct NonEmptyStringValueParser {} - -impl NonEmptyStringValueParser { - /// Parse non-empty string values - pub fn new() -> Self { - Self {} - } -} - -impl TypedValueParser for NonEmptyStringValueParser { - type Value = String; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - if value.is_empty() { - return Err(crate::Error::empty_value( - cmd, - &[], - arg.map(ToString::to_string) - .unwrap_or_else(|| "...".to_owned()), - )); - } - let value = ok!(value.to_str().ok_or_else(|| { - crate::Error::invalid_utf8( - cmd, - crate::output::Usage::new(cmd).create_usage_with_title(&[]), - ) - })); - Ok(value.to_owned()) - } -} - -impl Default for NonEmptyStringValueParser { - fn default() -> Self { - Self::new() - } -} - -/// Adapt a `TypedValueParser` from one value to another -/// -/// See [`TypedValueParser::map`] -#[derive(Clone, Debug)] -pub struct MapValueParser<P, F> { - parser: P, - func: F, -} - -impl<P, F, T> MapValueParser<P, F> -where - P: TypedValueParser, - P::Value: Send + Sync + Clone, - F: Fn(P::Value) -> T + Clone, - T: Send + Sync + Clone, -{ - fn new(parser: P, func: F) -> Self { - Self { parser, func } - } -} - -impl<P, F, T> TypedValueParser for MapValueParser<P, F> -where - P: TypedValueParser, - P::Value: Send + Sync + Clone, - F: Fn(P::Value) -> T + Clone + Send + Sync + 'static, - T: Send + Sync + Clone, -{ - type Value = T; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - let value = ok!(self.parser.parse_ref(cmd, arg, value)); - let value = (self.func)(value); - Ok(value) - } - - fn parse( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: std::ffi::OsString, - ) -> Result<Self::Value, crate::Error> { - let value = ok!(self.parser.parse(cmd, arg, value)); - let value = (self.func)(value); - Ok(value) - } - - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - self.parser.possible_values() - } -} - -/// Adapt a `TypedValueParser` from one value to another -/// -/// See [`TypedValueParser::try_map`] -#[derive(Clone, Debug)] -pub struct TryMapValueParser<P, F> { - parser: P, - func: F, -} - -impl<P, F, T, E> TryMapValueParser<P, F> -where - P: TypedValueParser, - P::Value: Send + Sync + Clone, - F: Fn(P::Value) -> Result<T, E> + Clone + Send + Sync + 'static, - T: Send + Sync + Clone, - E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>, -{ - fn new(parser: P, func: F) -> Self { - Self { parser, func } - } -} - -impl<P, F, T, E> TypedValueParser for TryMapValueParser<P, F> -where - P: TypedValueParser, - P::Value: Send + Sync + Clone, - F: Fn(P::Value) -> Result<T, E> + Clone + Send + Sync + 'static, - T: Send + Sync + Clone, - E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>, -{ - type Value = T; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - let mid_value = ok!(self.parser.parse_ref(cmd, arg, value)); - let value = ok!((self.func)(mid_value).map_err(|e| { - let arg = arg - .map(|a| a.to_string()) - .unwrap_or_else(|| "...".to_owned()); - crate::Error::value_validation(arg, value.to_string_lossy().into_owned(), e.into()) - .with_cmd(cmd) - })); - Ok(value) - } - - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - self.parser.possible_values() - } -} - -/// When encountered, report [ErrorKind::UnknownArgument][crate::error::ErrorKind::UnknownArgument] -/// -/// Useful to help users migrate, either from old versions or similar tools. -/// -/// # Examples -/// -/// ```rust -/// # use clap_builder as clap; -/// # use clap::Command; -/// # use clap::Arg; -/// let cmd = Command::new("mycmd") -/// .args([ -/// Arg::new("current-dir") -/// .short('C'), -/// Arg::new("current-dir-unknown") -/// .long("cwd") -/// .aliases(["current-dir", "directory", "working-directory", "root"]) -/// .value_parser(clap::builder::UnknownArgumentValueParser::suggest_arg("-C")) -/// .hide(true), -/// ]); -/// -/// // Use a supported version of the argument -/// let matches = cmd.clone().try_get_matches_from(["mycmd", "-C", ".."]).unwrap(); -/// assert!(matches.contains_id("current-dir")); -/// assert_eq!( -/// matches.get_many::<String>("current-dir").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(), -/// vec![".."] -/// ); -/// -/// // Use one of the invalid versions -/// let err = cmd.try_get_matches_from(["mycmd", "--cwd", ".."]).unwrap_err(); -/// assert_eq!(err.kind(), clap::error::ErrorKind::UnknownArgument); -/// ``` -#[derive(Clone, Debug)] -pub struct UnknownArgumentValueParser { - arg: Option<Str>, - suggestions: Vec<StyledStr>, -} - -impl UnknownArgumentValueParser { - /// Suggest an alternative argument - pub fn suggest_arg(arg: impl Into<Str>) -> Self { - Self { - arg: Some(arg.into()), - suggestions: Default::default(), - } - } - - /// Provide a general suggestion - pub fn suggest(text: impl Into<StyledStr>) -> Self { - Self { - arg: Default::default(), - suggestions: vec![text.into()], - } - } - - /// Extend the suggestions - pub fn and_suggest(mut self, text: impl Into<StyledStr>) -> Self { - self.suggestions.push(text.into()); - self - } -} - -impl TypedValueParser for UnknownArgumentValueParser { - type Value = String; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - TypedValueParser::parse_ref_(self, cmd, arg, value, ValueSource::CommandLine) - } - - fn parse_ref_( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - _value: &std::ffi::OsStr, - source: ValueSource, - ) -> Result<Self::Value, crate::Error> { - match source { - ValueSource::DefaultValue => { - TypedValueParser::parse_ref_(&StringValueParser::new(), cmd, arg, _value, source) - } - ValueSource::EnvVariable | ValueSource::CommandLine => { - let arg = match arg { - Some(arg) => arg.to_string(), - None => "..".to_owned(), - }; - let err = crate::Error::unknown_argument( - cmd, - arg, - self.arg.as_ref().map(|s| (s.as_str().to_owned(), None)), - false, - crate::output::Usage::new(cmd).create_usage_with_title(&[]), - ); - #[cfg(feature = "error-context")] - let err = { - debug_assert_eq!( - err.get(crate::error::ContextKind::Suggested), - None, - "Assuming `Error::unknown_argument` doesn't apply any `Suggested` so we can without caution" - ); - err.insert_context_unchecked( - crate::error::ContextKind::Suggested, - crate::error::ContextValue::StyledStrs(self.suggestions.clone()), - ) - }; - Err(err) - } - } - } -} - -/// Register a type with [value_parser!][crate::value_parser!] -/// -/// # Example -/// -/// ```rust -/// # use clap_builder as clap; -/// #[derive(Copy, Clone, Debug)] -/// pub struct Custom(u32); -/// -/// impl clap::builder::ValueParserFactory for Custom { -/// type Parser = CustomValueParser; -/// fn value_parser() -> Self::Parser { -/// CustomValueParser -/// } -/// } -/// -/// #[derive(Clone, Debug)] -/// pub struct CustomValueParser; -/// impl clap::builder::TypedValueParser for CustomValueParser { -/// type Value = Custom; -/// -/// fn parse_ref( -/// &self, -/// cmd: &clap::Command, -/// arg: Option<&clap::Arg>, -/// value: &std::ffi::OsStr, -/// ) -> Result<Self::Value, clap::Error> { -/// let inner = clap::value_parser!(u32); -/// let val = inner.parse_ref(cmd, arg, value)?; -/// Ok(Custom(val)) -/// } -/// } -/// -/// let parser: CustomValueParser = clap::value_parser!(Custom); -/// ``` -pub trait ValueParserFactory { - /// Generated parser, usually [`ValueParser`]. - /// - /// It should at least be a type that supports `Into<ValueParser>`. A non-`ValueParser` type - /// allows the caller to do further initialization on the parser. - type Parser; - - /// Create the specified [`Self::Parser`] - fn value_parser() -> Self::Parser; -} -impl ValueParserFactory for String { - type Parser = ValueParser; - fn value_parser() -> Self::Parser { - ValueParser::string() // Default `clap_derive` to optimized implementation - } -} -impl ValueParserFactory for Box<str> { - type Parser = MapValueParser<StringValueParser, fn(String) -> Box<str>>; - fn value_parser() -> Self::Parser { - StringValueParser::new().map(String::into_boxed_str) - } -} -impl ValueParserFactory for std::ffi::OsString { - type Parser = ValueParser; - fn value_parser() -> Self::Parser { - ValueParser::os_string() // Default `clap_derive` to optimized implementation - } -} -impl ValueParserFactory for Box<std::ffi::OsStr> { - type Parser = - MapValueParser<OsStringValueParser, fn(std::ffi::OsString) -> Box<std::ffi::OsStr>>; - fn value_parser() -> Self::Parser { - OsStringValueParser::new().map(std::ffi::OsString::into_boxed_os_str) - } -} -impl ValueParserFactory for std::path::PathBuf { - type Parser = ValueParser; - fn value_parser() -> Self::Parser { - ValueParser::path_buf() // Default `clap_derive` to optimized implementation - } -} -impl ValueParserFactory for Box<std::path::Path> { - type Parser = - MapValueParser<PathBufValueParser, fn(std::path::PathBuf) -> Box<std::path::Path>>; - fn value_parser() -> Self::Parser { - PathBufValueParser::new().map(std::path::PathBuf::into_boxed_path) - } -} -impl ValueParserFactory for bool { - type Parser = ValueParser; - fn value_parser() -> Self::Parser { - ValueParser::bool() // Default `clap_derive` to optimized implementation - } -} -impl ValueParserFactory for u8 { - type Parser = RangedI64ValueParser<u8>; - fn value_parser() -> Self::Parser { - let start: i64 = u8::MIN.into(); - let end: i64 = u8::MAX.into(); - RangedI64ValueParser::new().range(start..=end) - } -} -impl ValueParserFactory for i8 { - type Parser = RangedI64ValueParser<i8>; - fn value_parser() -> Self::Parser { - let start: i64 = i8::MIN.into(); - let end: i64 = i8::MAX.into(); - RangedI64ValueParser::new().range(start..=end) - } -} -impl ValueParserFactory for u16 { - type Parser = RangedI64ValueParser<u16>; - fn value_parser() -> Self::Parser { - let start: i64 = u16::MIN.into(); - let end: i64 = u16::MAX.into(); - RangedI64ValueParser::new().range(start..=end) - } -} -impl ValueParserFactory for i16 { - type Parser = RangedI64ValueParser<i16>; - fn value_parser() -> Self::Parser { - let start: i64 = i16::MIN.into(); - let end: i64 = i16::MAX.into(); - RangedI64ValueParser::new().range(start..=end) - } -} -impl ValueParserFactory for u32 { - type Parser = RangedI64ValueParser<u32>; - fn value_parser() -> Self::Parser { - let start: i64 = u32::MIN.into(); - let end: i64 = u32::MAX.into(); - RangedI64ValueParser::new().range(start..=end) - } -} -impl ValueParserFactory for i32 { - type Parser = RangedI64ValueParser<i32>; - fn value_parser() -> Self::Parser { - let start: i64 = i32::MIN.into(); - let end: i64 = i32::MAX.into(); - RangedI64ValueParser::new().range(start..=end) - } -} -impl ValueParserFactory for u64 { - type Parser = RangedU64ValueParser<u64>; - fn value_parser() -> Self::Parser { - RangedU64ValueParser::new() - } -} -impl ValueParserFactory for i64 { - type Parser = RangedI64ValueParser<i64>; - fn value_parser() -> Self::Parser { - RangedI64ValueParser::new() - } -} -impl<T> ValueParserFactory for std::num::Wrapping<T> -where - T: ValueParserFactory, - <T as ValueParserFactory>::Parser: TypedValueParser<Value = T>, - T: Send + Sync + Clone, -{ - type Parser = MapValueParser<<T as ValueParserFactory>::Parser, fn(T) -> std::num::Wrapping<T>>; - fn value_parser() -> Self::Parser { - T::value_parser().map(std::num::Wrapping) - } -} -impl<T> ValueParserFactory for Box<T> -where - T: ValueParserFactory, - <T as ValueParserFactory>::Parser: TypedValueParser<Value = T>, - T: Send + Sync + Clone, -{ - type Parser = MapValueParser<<T as ValueParserFactory>::Parser, fn(T) -> Box<T>>; - fn value_parser() -> Self::Parser { - T::value_parser().map(Box::new) - } -} -impl<T> ValueParserFactory for std::sync::Arc<T> -where - T: ValueParserFactory, - <T as ValueParserFactory>::Parser: TypedValueParser<Value = T>, - T: Send + Sync + Clone, -{ - type Parser = MapValueParser<<T as ValueParserFactory>::Parser, fn(T) -> std::sync::Arc<T>>; - fn value_parser() -> Self::Parser { - T::value_parser().map(std::sync::Arc::new) - } -} - -#[doc(hidden)] -#[derive(Debug)] -pub struct _AutoValueParser<T>(std::marker::PhantomData<T>); - -impl<T> _AutoValueParser<T> { - #[doc(hidden)] - #[allow(clippy::new_without_default)] - pub fn new() -> Self { - Self(Default::default()) - } -} - -/// Unstable [`ValueParser`] -/// -/// Implementation may change to more specific instance in the future -#[doc(hidden)] -#[derive(Debug)] -pub struct _AnonymousValueParser(ValueParser); - -#[doc(hidden)] -pub mod via_prelude { - use super::*; - - #[doc(hidden)] - pub trait _ValueParserViaFactory: private::_ValueParserViaFactorySealed { - type Parser; - fn value_parser(&self) -> Self::Parser; - } - impl<P: ValueParserFactory> _ValueParserViaFactory for &&&&&&_AutoValueParser<P> { - type Parser = P::Parser; - fn value_parser(&self) -> Self::Parser { - P::value_parser() - } - } - - #[doc(hidden)] - pub trait _ValueParserViaValueEnum: private::_ValueParserViaValueEnumSealed { - type Output; - - fn value_parser(&self) -> Self::Output; - } - impl<E: crate::ValueEnum + Clone + Send + Sync + 'static> _ValueParserViaValueEnum - for &&&&&_AutoValueParser<E> - { - type Output = EnumValueParser<E>; - - fn value_parser(&self) -> Self::Output { - EnumValueParser::<E>::new() - } - } - - #[doc(hidden)] - pub trait _ValueParserViaFromOsString: private::_ValueParserViaFromOsStringSealed { - fn value_parser(&self) -> _AnonymousValueParser; - } - impl<FromOsString> _ValueParserViaFromOsString for &&&&_AutoValueParser<FromOsString> - where - FromOsString: From<std::ffi::OsString> + std::any::Any + Clone + Send + Sync + 'static, - { - fn value_parser(&self) -> _AnonymousValueParser { - _AnonymousValueParser( - OsStringValueParser::new() - .map(|s| FromOsString::from(s)) - .into(), - ) - } - } - - #[doc(hidden)] - pub trait _ValueParserViaFromOsStr: private::_ValueParserViaFromOsStrSealed { - fn value_parser(&self) -> _AnonymousValueParser; - } - impl<FromOsStr> _ValueParserViaFromOsStr for &&&_AutoValueParser<FromOsStr> - where - FromOsStr: - for<'s> From<&'s std::ffi::OsStr> + std::any::Any + Clone + Send + Sync + 'static, - { - fn value_parser(&self) -> _AnonymousValueParser { - _AnonymousValueParser( - OsStringValueParser::new() - .map(|s| FromOsStr::from(&s)) - .into(), - ) - } - } - - #[doc(hidden)] - pub trait _ValueParserViaFromString: private::_ValueParserViaFromStringSealed { - fn value_parser(&self) -> _AnonymousValueParser; - } - impl<FromString> _ValueParserViaFromString for &&_AutoValueParser<FromString> - where - FromString: From<String> + std::any::Any + Clone + Send + Sync + 'static, - { - fn value_parser(&self) -> _AnonymousValueParser { - _AnonymousValueParser(StringValueParser::new().map(|s| FromString::from(s)).into()) - } - } - - #[doc(hidden)] - pub trait _ValueParserViaFromStr: private::_ValueParserViaFromStrSealed { - fn value_parser(&self) -> _AnonymousValueParser; - } - impl<FromStr> _ValueParserViaFromStr for &_AutoValueParser<FromStr> - where - FromStr: for<'s> From<&'s str> + std::any::Any + Clone + Send + Sync + 'static, - { - fn value_parser(&self) -> _AnonymousValueParser { - _AnonymousValueParser(StringValueParser::new().map(|s| FromStr::from(&s)).into()) - } - } - - #[doc(hidden)] - pub trait _ValueParserViaParse: private::_ValueParserViaParseSealed { - fn value_parser(&self) -> _AnonymousValueParser; - } - impl<Parse> _ValueParserViaParse for _AutoValueParser<Parse> - where - Parse: std::str::FromStr + std::any::Any + Clone + Send + Sync + 'static, - <Parse as std::str::FromStr>::Err: Into<Box<dyn std::error::Error + Send + Sync + 'static>>, - { - fn value_parser(&self) -> _AnonymousValueParser { - let func: fn(&str) -> Result<Parse, <Parse as std::str::FromStr>::Err> = - Parse::from_str; - _AnonymousValueParser(ValueParser::new(func)) - } - } -} - -/// Select a [`ValueParser`] implementation from the intended type -/// -/// Supported types -/// - [`ValueParserFactory` types][ValueParserFactory], including -/// - [Native types][ValueParser]: `bool`, `String`, `OsString`, `PathBuf` -/// - [Ranged numeric types][RangedI64ValueParser]: `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64` -/// - [`ValueEnum` types][crate::ValueEnum] -/// - [`From<OsString>` types][std::convert::From] and [`From<&OsStr>` types][std::convert::From] -/// - [`From<String>` types][std::convert::From] and [`From<&str>` types][std::convert::From] -/// - [`FromStr` types][std::str::FromStr], including usize, isize -/// -/// # Example -/// -/// Usage: -/// ```rust -/// # use clap_builder as clap; -/// # use std::path::PathBuf; -/// # use std::path::Path; -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("output") -/// .value_parser(clap::value_parser!(PathBuf)) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "file.txt"]).unwrap(); -/// let port: &PathBuf = m.get_one("output") -/// .expect("required"); -/// assert_eq!(port, Path::new("file.txt")); -/// ``` -/// -/// Example mappings: -/// ```rust -/// # use clap_builder as clap; -/// # use clap::ColorChoice; -/// // Built-in types -/// let parser = clap::value_parser!(String); -/// assert_eq!(format!("{parser:?}"), "ValueParser::string"); -/// let parser = clap::value_parser!(std::ffi::OsString); -/// assert_eq!(format!("{parser:?}"), "ValueParser::os_string"); -/// let parser = clap::value_parser!(std::path::PathBuf); -/// assert_eq!(format!("{parser:?}"), "ValueParser::path_buf"); -/// clap::value_parser!(u16).range(3000..); -/// clap::value_parser!(u64).range(3000..); -/// -/// // FromStr types -/// let parser = clap::value_parser!(usize); -/// assert_eq!(format!("{parser:?}"), "_AnonymousValueParser(ValueParser::other(usize))"); -/// -/// // ValueEnum types -/// clap::value_parser!(ColorChoice); -/// ``` -#[macro_export] -macro_rules! value_parser { - ($name:ty) => {{ - use $crate::builder::via_prelude::*; - let auto = $crate::builder::_AutoValueParser::<$name>::new(); - (&&&&&&auto).value_parser() - }}; -} - -mod private { - use super::*; - - // Prefer these so `clap_derive` defaults to optimized implementations - pub trait _ValueParserViaSelfSealed {} - impl<P: Into<ValueParser>> _ValueParserViaSelfSealed for &&&&&&&_AutoValueParser<P> {} - - pub trait _ValueParserViaFactorySealed {} - impl<P: ValueParserFactory> _ValueParserViaFactorySealed for &&&&&&_AutoValueParser<P> {} - - pub trait _ValueParserViaValueEnumSealed {} - impl<E: crate::ValueEnum> _ValueParserViaValueEnumSealed for &&&&&_AutoValueParser<E> {} - - pub trait _ValueParserViaFromOsStringSealed {} - impl<FromOsString> _ValueParserViaFromOsStringSealed for &&&&_AutoValueParser<FromOsString> where - FromOsString: From<std::ffi::OsString> + std::any::Any + Send + Sync + 'static - { - } - - pub trait _ValueParserViaFromOsStrSealed {} - impl<FromOsStr> _ValueParserViaFromOsStrSealed for &&&_AutoValueParser<FromOsStr> where - FromOsStr: for<'s> From<&'s std::ffi::OsStr> + std::any::Any + Send + Sync + 'static - { - } - - pub trait _ValueParserViaFromStringSealed {} - impl<FromString> _ValueParserViaFromStringSealed for &&_AutoValueParser<FromString> where - FromString: From<String> + std::any::Any + Send + Sync + 'static - { - } - - pub trait _ValueParserViaFromStrSealed {} - impl<FromStr> _ValueParserViaFromStrSealed for &_AutoValueParser<FromStr> where - FromStr: for<'s> From<&'s str> + std::any::Any + Send + Sync + 'static - { - } - - pub trait _ValueParserViaParseSealed {} - impl<Parse> _ValueParserViaParseSealed for _AutoValueParser<Parse> - where - Parse: std::str::FromStr + std::any::Any + Send + Sync + 'static, - <Parse as std::str::FromStr>::Err: Into<Box<dyn std::error::Error + Send + Sync + 'static>>, - { - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn ensure_typed_applies_to_parse() { - fn parse(_: &str) -> Result<usize, std::io::Error> { - Ok(10) - } - let cmd = crate::Command::new("cmd"); - let arg = None; - assert_eq!( - TypedValueParser::parse_ref(&parse, &cmd, arg, std::ffi::OsStr::new("foo")).unwrap(), - 10 - ); - } -} |