pub struct Arg { /* private fields */ }
Expand description
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.
Examples
// 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");
Implementations§
source§impl Arg
impl Arg
sourcepub fn new(id: impl Into<Id>) -> Self
pub fn new(id: impl Into<Id>) -> Self
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
Arg::new("config")
Examples found in repository?
4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308
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 information (use `--help` for more detail)")
.long_help("Print help information (use `-h` for a summary)");
} else {
arg = arg.help("Print help information");
}
// 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 information");
// 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);
}
}
sourcepub fn id(self, id: impl Into<Id>) -> Self
pub fn id(self, id: impl Into<Id>) -> Self
Set the identifier used for referencing this argument in the clap API.
See Arg::new
for more details.
sourcepub fn short(self, s: impl IntoResettable<char>) -> Self
pub fn short(self, s: impl IntoResettable<char>) -> 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
,
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
:
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:
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"));
Examples found in repository?
4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308
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 information (use `--help` for more detail)")
.long_help("Print help information (use `-h` for a summary)");
} else {
arg = arg.help("Print help information");
}
// 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 information");
// 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);
}
}
sourcepub fn long(self, l: impl IntoResettable<Str>) -> Self
pub fn long(self, l: impl IntoResettable<Str>) -> 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
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"));
Examples found in repository?
4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308
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 information (use `--help` for more detail)")
.long_help("Print help information (use `-h` for a summary)");
} else {
arg = arg.help("Print help information");
}
// 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 information");
// 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);
}
}
sourcepub fn alias(self, name: impl IntoResettable<Str>) -> Self
pub fn alias(self, name: impl IntoResettable<Str>) -> 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
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");
sourcepub fn short_alias(self, name: impl IntoResettable<char>) -> Self
pub fn short_alias(self, name: impl IntoResettable<char>) -> 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
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");
sourcepub fn aliases(self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self
pub fn aliases(self, names: impl IntoIterator<Item = impl Into<Str>>) -> 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
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_one::<bool>("test").expect("defaulted by clap"), true);
sourcepub fn short_aliases(self, names: impl IntoIterator<Item = char>) -> Self
pub fn short_aliases(self, names: impl IntoIterator<Item = char>) -> 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
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_one::<bool>("test").expect("defaulted by clap"), true);
sourcepub fn visible_alias(self, name: impl IntoResettable<Str>) -> Self
pub fn visible_alias(self, name: impl IntoResettable<Str>) -> Self
Add an alias, which functions as a visible long flag.
Like Arg::alias
, except that they are visible inside the help message.
Examples
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");
sourcepub fn visible_short_alias(self, name: impl IntoResettable<char>) -> Self
pub fn visible_short_alias(self, name: impl IntoResettable<char>) -> 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
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");
sourcepub fn visible_aliases(
self,
names: impl IntoIterator<Item = impl Into<Str>>
) -> Self
pub fn visible_aliases(
self,
names: impl IntoIterator<Item = impl Into<Str>>
) -> Self
Add aliases, which function as visible long flags.
Like Arg::aliases
, except that they are visible inside the help message.
Examples
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_one::<bool>("test").expect("defaulted by clap"), true);
sourcepub fn visible_short_aliases(self, names: impl IntoIterator<Item = char>) -> Self
pub fn visible_short_aliases(self, names: impl IntoIterator<Item = char>) -> Self
Add aliases, which function as visible short flags.
Like Arg::short_aliases
, except that they are visible inside the help message.
Examples
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_one::<bool>("test").expect("defaulted by clap"), true);
sourcepub fn index(self, idx: impl IntoResettable<usize>) -> Self
pub fn index(self, idx: impl IntoResettable<usize>) -> 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
Examples
Arg::new("config")
.index(1)
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
sourcepub fn trailing_var_arg(self, yes: bool) -> Self
pub fn trailing_var_arg(self, yes: bool) -> 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
. 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
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"]);
sourcepub fn last(self, yes: bool) -> Self
pub fn last(self, yes: bool) -> Self
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
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
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.
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.
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);
sourcepub fn required(self, yes: bool) -> Self
pub fn required(self, yes: bool) -> Self
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
Arg::new("config")
.required(true)
Setting required requires that the argument be used at runtime.
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.
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);
sourcepub fn requires(self, arg_id: impl IntoResettable<Id>) -> Self
pub fn requires(self, arg_id: impl IntoResettable<Id>) -> Self
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
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
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.
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);
sourcepub fn exclusive(self, yes: bool) -> Self
pub fn exclusive(self, yes: bool) -> Self
This argument must be passed alone; it conflicts with all other arguments.
Examples
Arg::new("config")
.exclusive(true)
Setting an exclusive argument and having any other arguments present at runtime is an error.
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);
sourcepub fn global(self, yes: bool) -> Self
pub fn global(self, yes: bool) -> Self
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.
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_one::<bool>("verb").expect("defaulted by clap"), true);
source§impl Arg
impl Arg
sourcepub fn action(self, action: impl IntoResettable<ArgAction>) -> Self
pub fn action(self, action: impl IntoResettable<ArgAction>) -> Self
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
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"]
);
Examples found in repository?
4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308
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 information (use `--help` for more detail)")
.long_help("Print help information (use `-h` for a summary)");
} else {
arg = arg.help("Print help information");
}
// 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 information");
// 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);
}
}
sourcepub fn value_parser(self, parser: impl IntoResettable<ValueParser>) -> Self
pub fn value_parser(self, parser: impl IntoResettable<ValueParser>) -> Self
Specify the typed behavior of the argument.
This allows parsing and validating a value before storing it into
ArgMatches
as the given type.
Possible value parsers include:
value_parser!(T)
for auto-selecting a value parser for a given type- Or range expressions like
0..=1
as a shorthand forRangedI64ValueParser
- Or range expressions like
Fn(&str) -> Result<T, E>
[&str]
andPossibleValuesParser
for static enumerated valuesBoolishValueParser
, andFalseyValueParser
for alternativebool
implementationsNonEmptyStringValueParser
for basic validation for strings- or any other
TypedValueParser
implementation
The default value is ValueParser::string
.
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);
sourcepub fn num_args(self, qty: impl IntoResettable<ValueRange>) -> Self
pub fn num_args(self, qty: impl IntoResettable<ValueRange>) -> 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
--
withArg::last
Examples
Option:
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)
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
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.
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.
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");
Examples found in repository?
More examples
4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308
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 information (use `--help` for more detail)")
.long_help("Print help information (use `-h` for a summary)");
} else {
arg = arg.help("Print help information");
}
// 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 information");
// 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);
}
}
sourcepub fn value_name(self, name: impl IntoResettable<Str>) -> Self
pub fn value_name(self, name: impl IntoResettable<Str>) -> Self
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
Arg::new("cfg")
.long("config")
.value_name("FILE")
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
valnames
Usage: valnames [OPTIONS]
Options:
--config <FILE> Some help text
-h, --help Print help information
-V, --version Print version information
Examples found in repository?
4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308
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 information (use `--help` for more detail)")
.long_help("Print help information (use `-h` for a summary)");
} else {
arg = arg.help("Print help information");
}
// 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 information");
// 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);
}
}
sourcepub fn value_names(self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self
pub fn value_names(self, names: impl IntoIterator<Item = impl Into<Str>>) -> 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
Arg::new("speed")
.short('s')
.value_names(["fast", "slow"]);
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
valnames
Usage: valnames [OPTIONS]
Options:
-h, --help Print help information
--io-files <INFILE> <OUTFILE> Some help text
-V, --version Print version information
sourcepub fn value_hint(self, value_hint: impl IntoResettable<ValueHint>) -> Self
pub fn value_hint(self, value_hint: impl IntoResettable<ValueHint>) -> 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:
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):
Command::new("prog")
.trailing_var_arg(true)
.arg(
Arg::new("command")
.action(ArgAction::Set)
.num_args(1..)
.value_hint(ValueHint::CommandWithArguments)
);
sourcepub fn ignore_case(self, yes: bool) -> Self
pub fn ignore_case(self, yes: bool) -> Self
Match values against 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
NOTE: To do unicode case folding, enable the unicode
feature flag.
Examples
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:
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"]);
sourcepub fn allow_hyphen_values(self, yes: bool) -> Self
pub fn allow_hyphen_values(self, yes: bool) -> Self
Allows values which start with a leading hyphen (-
)
To limit values to just numbers, see
allow_negative_numbers
.
See also trailing_var_arg
.
NOTE: Setting this requires taking values
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
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.
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);
sourcepub fn allow_negative_numbers(self, yes: bool) -> Self
pub fn allow_negative_numbers(self, yes: bool) -> Self
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
Examples
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");
sourcepub fn require_equals(self, yes: bool) -> Self
pub fn require_equals(self, yes: bool) -> Self
Requires that options use the --option=val
syntax
i.e. an equals between the option and associated value.
NOTE: Setting this requires taking values
Examples
Setting require_equals
requires that the option have an equals sign between
it and the associated value.
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.
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);
sourcepub fn value_delimiter(self, d: impl IntoResettable<char>) -> Self
pub fn value_delimiter(self, d: impl IntoResettable<char>) -> 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
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"])
sourcepub fn value_terminator(self, term: impl IntoResettable<Str>) -> Self
pub fn value_terminator(self, term: impl IntoResettable<Str>) -> 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
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
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");
sourcepub fn raw(self, yes: bool) -> Self
pub fn raw(self, yes: bool) -> 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:
--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 crate::Command::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
.
sourcepub fn default_value(self, val: impl IntoResettable<OsStr>) -> Self
pub fn default_value(self, val: impl IntoResettable<OsStr>) -> Self
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
.
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.
NOTE: This implicitly sets Arg::action(ArgAction::Set)
.
Examples
First we use the default value without providing any value at runtime.
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.
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));
sourcepub fn default_values(
self,
vals: impl IntoIterator<Item = impl Into<OsStr>>
) -> Self
pub fn default_values(
self,
vals: impl IntoIterator<Item = impl Into<OsStr>>
) -> Self
Value for the argument when not present.
See Arg::default_value
.
Examples found in repository?
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
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)
}
sourcepub fn default_missing_value(self, val: impl IntoResettable<OsStr>) -> Self
pub fn default_missing_value(self, val: impl IntoResettable<OsStr>) -> Self
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)
and the
.require_equals(true)
configuration option. These are required in
order to unambiguously determine what, if any, value was supplied for the argument.
Examples
For POSIX style --color
:
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:
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));
sourcepub fn default_missing_value_os(self, val: impl Into<OsStr>) -> Self
pub fn default_missing_value_os(self, val: impl Into<OsStr>) -> Self
Value for the argument when the flag is present but no value is specified.
sourcepub fn default_missing_values(
self,
vals: impl IntoIterator<Item = impl Into<OsStr>>
) -> Self
pub fn default_missing_values(
self,
vals: impl IntoIterator<Item = impl Into<OsStr>>
) -> Self
Value for the argument when the flag is present but no value is specified.
sourcepub fn default_missing_values_os(
self,
vals: impl IntoIterator<Item = impl Into<OsStr>>
) -> Self
pub fn default_missing_values_os(
self,
vals: impl IntoIterator<Item = impl Into<OsStr>>
) -> Self
Value for the argument when the flag is present but no value is specified.
Examples found in repository?
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
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)
}
sourcepub fn env(self, name: impl IntoResettable<OsStr>) -> Self
Available on crate feature env
only.
pub fn env(self, name: impl IntoResettable<OsStr>) -> Self
env
only.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
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
will return the default specified.
Examples
In this example, we show the variable coming from the environment:
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
. 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
.
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_one::<bool>("true_flag").unwrap());
assert!(!*m.get_one::<bool>("false_flag").unwrap());
assert!(!*m.get_one::<bool>("absent_flag").unwrap());
In this example, we show the variable coming from an option on the CLI:
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:
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:
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"]);
source§impl Arg
impl Arg
sourcepub fn help(self, h: impl IntoResettable<StyledStr>) -> Self
pub fn help(self, h: impl IntoResettable<StyledStr>) -> Self
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).
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
helptest
Usage: helptest [OPTIONS]
Options:
--config Some help text describing the --config arg
-h, --help Print help information
-V, --version Print version information
Examples found in repository?
4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308
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 information (use `--help` for more detail)")
.long_help("Print help information (use `-h` for a summary)");
} else {
arg = arg.help("Print help information");
}
// 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 information");
// 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);
}
}
sourcepub fn long_help(self, h: impl IntoResettable<StyledStr>) -> Self
pub fn long_help(self, h: impl IntoResettable<StyledStr>) -> 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).
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
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
Examples found in repository?
4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308
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 information (use `--help` for more detail)")
.long_help("Print help information (use `-h` for a summary)");
} else {
arg = arg.help("Print help information");
}
// 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 information");
// 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);
}
}
sourcepub fn display_order(self, ord: impl IntoResettable<usize>) -> Self
pub fn display_order(self, ord: impl IntoResettable<usize>) -> Self
Allows custom ordering of args within the help message.
Args with a lower value will be displayed first in the help message. This is helpful when one would like to emphasise frequently used args, or prioritize those towards the top of the list. Args with duplicate display orders will be displayed in alphabetical order.
NOTE: The default is 999 for all arguments.
NOTE: This setting is ignored for positional arguments which are always displayed in index order.
Examples
let m = Command::new("prog")
.arg(Arg::new("a") // Typically args are grouped alphabetically by name.
// Args without a display_order have a value of 999 and are
// displayed alphabetically with all other 999 valued args.
.long("long-option")
.short('o')
.action(ArgAction::Set)
.help("Some help and text"))
.arg(Arg::new("b")
.long("other-option")
.short('O')
.action(ArgAction::Set)
.display_order(1) // In order to force this arg to appear *first*
// all we have to do is give it a value lower than 999.
// Any other args with a value of 1 will be displayed
// alphabetically with this one...then 2 values, then 3, etc.
.help("I should be first!"))
.get_matches_from(vec![
"prog", "--help"
]);
The above example displays the following help message
cust-ord
Usage: cust-ord [OPTIONS]
Options:
-h, --help Print help information
-V, --version Print version information
-O, --other-option <b> I should be first!
-o, --long-option <a> Some help and text
sourcepub fn help_heading(self, heading: impl IntoResettable<Str>) -> Self
pub fn help_heading(self, heading: impl IntoResettable<Str>) -> Self
Override the current help section.
sourcepub fn next_line_help(self, yes: bool) -> Self
pub fn next_line_help(self, yes: bool) -> Self
Render the 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
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
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
sourcepub fn hide(self, yes: bool) -> Self
pub fn hide(self, yes: bool) -> Self
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
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
helptest
Usage: helptest [OPTIONS]
Options:
-h, --help Print help information
-V, --version Print version information
sourcepub fn hide_possible_values(self, yes: bool) -> Self
pub fn hide_possible_values(self, yes: bool) -> Self
Do not display the 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
To set this for all arguments, see
Command::hide_possible_values
.
Examples
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.
sourcepub fn hide_default_value(self, yes: bool) -> Self
pub fn hide_default_value(self, yes: bool) -> Self
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
Examples
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.
sourcepub fn hide_env(self, yes: bool) -> Self
Available on crate feature env
only.
pub fn hide_env(self, yes: bool) -> Self
env
only.Do not display in help the environment variable name.
This is useful when the variable option is explained elsewhere in the help text.
Examples
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.
sourcepub fn hide_env_values(self, yes: bool) -> Self
Available on crate feature env
only.
pub fn hide_env_values(self, yes: bool) -> Self
env
only.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
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.
sourcepub fn hide_short_help(self, yes: bool) -> Self
pub fn hide_short_help(self, yes: bool) -> Self
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
Arg::new("debug")
.hide_short_help(true);
Setting hide_short_help(true)
will hide the argument when displaying short help text
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
helptest
Usage: helptest [OPTIONS]
Options:
-h, --help Print help information
-V, --version Print version information
However, when –help is called
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
helptest
Usage: helptest [OPTIONS]
Options:
--config Some help text describing the --config arg
-h, --help Print help information
-V, --version Print version information
sourcepub fn hide_long_help(self, yes: bool) -> Self
pub fn hide_long_help(self, yes: bool) -> Self
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
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
helptest
Usage: helptest [OPTIONS]
Options:
-h, --help Print help information
-V, --version Print version information
However, when -h is called
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
helptest
Usage: helptest [OPTIONS]
OPTIONS:
--config Some help text describing the --config arg
-h, --help Print help information
-V, --version Print version information
source§impl Arg
impl Arg
sourcepub fn group(self, group_id: impl IntoResettable<Id>) -> Self
pub fn group(self, group_id: impl IntoResettable<Id>) -> Self
The name of the ArgGroup
the argument belongs to.
Examples
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.
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"));
sourcepub fn groups(self, group_ids: impl IntoIterator<Item = impl Into<Id>>) -> Self
pub fn groups(self, group_ids: impl IntoIterator<Item = impl Into<Id>>) -> Self
The names of ArgGroup
’s the argument belongs to.
Examples
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.
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"));
sourcepub fn default_value_if(
self,
arg_id: impl Into<Id>,
predicate: impl Into<ArgPredicate>,
default: impl IntoResettable<OsStr>
) -> Self
pub fn default_value_if(
self,
arg_id: impl Into<Id>,
predicate: impl Into<ArgPredicate>,
default: impl IntoResettable<OsStr>
) -> 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.
NOTE: This implicitly sets Arg::action(ArgAction::Set)
.
Examples
First we use the default value only if another arg is present at runtime.
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
.
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
.
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.
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.
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);
Examples found in repository?
2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874
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.
///
/// # Examples
///
/// First we use the default value only if another arg is present at runtime.
///
/// ```rust
/// # 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::{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::{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
}
sourcepub fn default_value_ifs(
self,
ifs: impl IntoIterator<Item = (impl Into<Id>, impl Into<ArgPredicate>, impl IntoResettable<OsStr>)>
) -> Self
pub fn default_value_ifs(
self,
ifs: impl IntoIterator<Item = (impl Into<Id>, impl Into<ArgPredicate>, impl IntoResettable<OsStr>)>
) -> Self
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.
Examples
First we use the default value only if another arg is present at runtime.
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
.
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”
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");
Examples found in repository?
2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893
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)
}
sourcepub fn required_unless_present(self, arg_id: impl IntoResettable<Id>) -> Self
pub fn required_unless_present(self, arg_id: impl IntoResettable<Id>) -> Self
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
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.
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.
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);
sourcepub fn required_unless_present_all(
self,
names: impl IntoIterator<Item = impl Into<Id>>
) -> Self
pub fn required_unless_present_all(
self,
names: impl IntoIterator<Item = impl Into<Id>>
) -> 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
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.
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.
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);
sourcepub fn required_unless_present_any(
self,
names: impl IntoIterator<Item = impl Into<Id>>
) -> Self
pub fn required_unless_present_any(
self,
names: impl IntoIterator<Item = impl Into<Id>>
) -> 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
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.
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.
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);
sourcepub fn required_if_eq(self, arg_id: impl Into<Id>, val: impl Into<OsStr>) -> Self
pub fn required_if_eq(self, arg_id: impl Into<Id>, val: impl Into<OsStr>) -> Self
This argument is required only if the specified arg
is present at runtime and its value
equals val
.
Examples
Arg::new("config")
.required_if_eq("other_arg", "value")
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);
sourcepub fn required_if_eq_any(
self,
ifs: impl IntoIterator<Item = (impl Into<Id>, impl Into<OsStr>)>
) -> Self
pub fn required_if_eq_any(
self,
ifs: impl IntoIterator<Item = (impl Into<Id>, impl Into<OsStr>)>
) -> 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
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.
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.
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);
sourcepub fn required_if_eq_all(
self,
ifs: impl IntoIterator<Item = (impl Into<Id>, impl Into<OsStr>)>
) -> Self
pub fn required_if_eq_all(
self,
ifs: impl IntoIterator<Item = (impl Into<Id>, impl Into<OsStr>)>
) -> 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
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.
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.
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);
sourcepub fn requires_if(
self,
val: impl Into<ArgPredicate>,
arg_id: impl Into<Id>
) -> Self
pub fn requires_if(
self,
val: impl Into<ArgPredicate>,
arg_id: impl Into<Id>
) -> 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
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.
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.
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);
sourcepub fn requires_ifs(
self,
ifs: impl IntoIterator<Item = (impl Into<ArgPredicate>, impl Into<Id>)>
) -> Self
pub fn requires_ifs(
self,
ifs: impl IntoIterator<Item = (impl Into<ArgPredicate>, impl Into<Id>)>
) -> Self
Allows multiple conditional requirements.
The requirement will only become valid if this arg’s value matches the
ArgPredicate
.
Examples
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.
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.
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);
sourcepub fn conflicts_with(self, arg_id: impl IntoResettable<Id>) -> Self
pub fn conflicts_with(self, arg_id: impl IntoResettable<Id>) -> Self
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
Arg::new("config")
.conflicts_with("debug")
Setting conflicting argument, and having both arguments present at runtime is an error.
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);
sourcepub fn conflicts_with_all(
self,
names: impl IntoIterator<Item = impl Into<Id>>
) -> Self
pub fn conflicts_with_all(
self,
names: impl IntoIterator<Item = impl Into<Id>>
) -> 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
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.
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);
sourcepub fn overrides_with(self, arg_id: impl IntoResettable<Id>) -> Self
pub fn overrides_with(self, arg_id: impl IntoResettable<Id>) -> 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.
Examples
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_one::<bool>("color").unwrap());
assert!(*m.get_one::<bool>("debug").unwrap()); // even though flag conflicts with debug, it's as if flag
// was never used because it was overridden with color
assert!(!*m.get_one::<bool>("flag").unwrap());
sourcepub fn overrides_with_all(
self,
names: impl IntoIterator<Item = impl Into<Id>>
) -> Self
pub fn overrides_with_all(
self,
names: impl IntoIterator<Item = impl Into<Id>>
) -> 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.
Examples
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_one::<bool>("color").unwrap()); // 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_one::<bool>("debug").unwrap());
assert!(!*m.get_one::<bool>("flag").unwrap());
source§impl Arg
impl Arg
sourcepub fn get_id(&self) -> &Id
pub fn get_id(&self) -> &Id
Get the name of the argument
Examples found in repository?
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
pub(crate) fn new(_cmd: &Command) -> Self {
ArgMatcher {
matches: ArgMatches {
#[cfg(debug_assertions)]
valid_args: {
let args = _cmd.get_arguments().map(|a| a.get_id().clone());
let groups = _cmd.get_groups().map(|g| g.get_id().clone());
args.chain(groups).collect()
},
#[cfg(debug_assertions)]
valid_subcommands: _cmd
.get_subcommands()
.map(|sc| sc.get_name_str().clone())
.collect(),
..Default::default()
},
pending: None,
}
}
pub(crate) fn into_inner(self) -> ArgMatches {
self.matches
}
pub(crate) fn propagate_globals(&mut self, global_arg_vec: &[Id]) {
debug!(
"ArgMatcher::get_global_values: global_arg_vec={:?}",
global_arg_vec
);
let mut vals_map = FlatMap::new();
self.fill_in_global_values(global_arg_vec, &mut vals_map);
}
fn fill_in_global_values(
&mut self,
global_arg_vec: &[Id],
vals_map: &mut FlatMap<Id, MatchedArg>,
) {
for global_arg in global_arg_vec {
if let Some(ma) = self.get(global_arg) {
// We have to check if the parent's global arg wasn't used but still exists
// such as from a default value.
//
// For example, `myprog subcommand --global-arg=value` where `--global-arg` defines
// a default value of `other` myprog would have an existing MatchedArg for
// `--global-arg` where the value is `other`
let to_update = if let Some(parent_ma) = vals_map.get(global_arg) {
if parent_ma.source() > ma.source() {
parent_ma
} else {
ma
}
} else {
ma
}
.clone();
vals_map.insert(global_arg.clone(), to_update);
}
}
if let Some(ref mut sc) = self.matches.subcommand {
let mut am = ArgMatcher {
matches: mem::take(&mut sc.matches),
pending: None,
};
am.fill_in_global_values(global_arg_vec, vals_map);
mem::swap(&mut am.matches, &mut sc.matches);
}
for (name, matched_arg) in vals_map.iter_mut() {
self.matches.args.insert(name.clone(), matched_arg.clone());
}
}
pub(crate) fn get(&self, arg: &Id) -> Option<&MatchedArg> {
self.matches.args.get(arg)
}
pub(crate) fn get_mut(&mut self, arg: &Id) -> Option<&mut MatchedArg> {
self.matches.args.get_mut(arg)
}
pub(crate) fn remove(&mut self, arg: &Id) -> bool {
self.matches.args.remove(arg).is_some()
}
pub(crate) fn contains(&self, arg: &Id) -> bool {
self.matches.args.contains_key(arg)
}
pub(crate) fn arg_ids(&self) -> std::slice::Iter<'_, Id> {
self.matches.args.keys()
}
pub(crate) fn entry(&mut self, arg: Id) -> crate::util::Entry<Id, MatchedArg> {
self.matches.args.entry(arg)
}
pub(crate) fn subcommand(&mut self, sc: SubCommand) {
self.matches.subcommand = Some(Box::new(sc));
}
pub(crate) fn subcommand_name(&self) -> Option<&str> {
self.matches.subcommand_name()
}
pub(crate) fn check_explicit(&self, arg: &Id, predicate: &ArgPredicate) -> bool {
self.get(arg).map_or(false, |a| a.check_explicit(predicate))
}
pub(crate) fn start_custom_arg(&mut self, arg: &Arg, source: ValueSource) {
let id = arg.get_id().clone();
debug!(
"ArgMatcher::start_custom_arg: id={:?}, source={:?}",
id, source
);
let ma = self.entry(id).or_insert(MatchedArg::new_arg(arg));
debug_assert_eq!(ma.type_id(), Some(arg.get_value_parser().type_id()));
ma.set_source(source);
ma.new_val_group();
}
pub(crate) fn start_custom_group(&mut self, id: Id, source: ValueSource) {
debug!(
"ArgMatcher::start_custom_arg: id={:?}, source={:?}",
id, source
);
let ma = self.entry(id).or_insert(MatchedArg::new_group());
debug_assert_eq!(ma.type_id(), None);
ma.set_source(source);
ma.new_val_group();
}
pub(crate) fn start_occurrence_of_external(&mut self, cmd: &crate::Command) {
let id = Id::from_static_ref(Id::EXTERNAL);
debug!("ArgMatcher::start_occurrence_of_external: id={:?}", id,);
let ma = self.entry(id).or_insert(MatchedArg::new_external(cmd));
debug_assert_eq!(
ma.type_id(),
Some(
cmd.get_external_subcommand_value_parser()
.expect(INTERNAL_ERROR_MSG)
.type_id()
)
);
ma.set_source(ValueSource::CommandLine);
ma.new_val_group();
}
pub(crate) fn add_val_to(&mut self, arg: &Id, val: AnyValue, raw_val: OsString) {
let ma = self.get_mut(arg).expect(INTERNAL_ERROR_MSG);
ma.append_val(val, raw_val);
}
pub(crate) fn add_index_to(&mut self, arg: &Id, idx: usize) {
let ma = self.get_mut(arg).expect(INTERNAL_ERROR_MSG);
ma.push_index(idx);
}
pub(crate) fn needs_more_vals(&self, o: &Arg) -> bool {
let num_pending = self
.pending
.as_ref()
.and_then(|p| (p.id == *o.get_id()).then(|| p.raw_vals.len()))
.unwrap_or(0);
debug!(
"ArgMatcher::needs_more_vals: o={}, pending={}",
o.get_id(),
num_pending
);
let expected = o.get_num_args().expect(INTERNAL_ERROR_MSG);
debug!(
"ArgMatcher::needs_more_vals: expected={}, actual={}",
expected, num_pending
);
expected.accepts_more(num_pending)
}
More examples
3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540
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
/// 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.term_w
}
#[cfg(feature = "help")]
pub(crate) fn get_max_term_width(&self) -> Option<usize> {
self.max_w
}
pub(crate) fn get_replacement(&self, key: &str) -> Option<&[Str]> {
self.replacers.get(key).map(|v| v.as_slice())
}
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) {
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) {
// 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.insert(AppSettings::SubcommandRequired.into());
self.settings.insert(AppSettings::DisableHelpFlag.into());
self.settings.insert(AppSettings::DisableVersionFlag.into());
}
if !cfg!(feature = "help") && self.get_override_help().is_none() {
self.settings.insert(AppSettings::DisableHelpFlag.into());
self.settings
.insert(AppSettings::DisableHelpSubcommand.into());
}
if self.is_set(AppSettings::ArgsNegateSubcommands) {
self.settings
.insert(AppSettings::SubcommandsNegateReqs.into());
}
if self.external_value_parser.is_some() {
self.settings
.insert(AppSettings::AllowExternalSubcommands.into());
}
if !self.has_subcommands() {
self.settings
.insert(AppSettings::DisableHelpSubcommand.into());
}
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.insert(ArgSettings::AllowHyphenValues.into());
}
if is_allow_negative_numbers_set && arg.is_takes_value_set() {
arg.settings
.insert(ArgSettings::AllowNegativeNumbers.into());
}
if is_trailing_var_arg_set && arg.get_index() == Some(highest_idx) {
arg.settings.insert(ArgSettings::TrailingVarArg.into());
}
}
}
#[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 mut 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.term_w = self.term_w;
sc.max_w = self.max_w;
}
}
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 information (use `--help` for more detail)")
.long_help("Print help information (use `-h` for a summary)");
} else {
arg = arg.help("Print help information");
}
// 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 information");
// 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!("{} {}\n", display_name, ver)
}
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.none("<");
styled.none(g_string);
styled.none(">");
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
}
4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257
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, required: Option<bool>) -> StyledStr {
let mut styled = StyledStr::new();
// Write the name such --long or -l
if let Some(l) = self.get_long() {
styled.literal("--");
styled.literal(l);
} else if let Some(s) = self.get_short() {
styled.literal("-");
styled.literal(s);
}
styled.extend(self.stylize_arg_suffix(required).into_iter());
styled
}
pub(crate) fn stylize_arg_suffix(&self, required: Option<bool>) -> StyledStr {
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;
if self.is_require_equals_set() {
if is_optional_val {
need_closing_bracket = true;
styled.placeholder("[=");
} else {
styled.literal("=");
}
} else if is_optional_val {
need_closing_bracket = true;
styled.placeholder(" [");
} else {
styled.placeholder(" ");
}
}
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);
styled.placeholder(arg_val);
} else if matches!(*self.get_action(), ArgAction::Count) {
styled.placeholder("...");
}
if need_closing_bracket {
styled.placeholder("]");
}
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())
}
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
fn option_sort_key(arg: &Arg) -> (usize, String) {
// Formatting key like this to ensure that:
// 1. Argument has long flags are printed just after short flags.
// 2. For two args both have short flags like `-c` and `-C`, the
// `-C` arg is printed just after the `-c` arg
// 3. For args without short or long flag, print them at last(sorted
// by arg name).
// Example order: -a, -b, -B, -s, --select-file, --select-folder, -x
let key = if let Some(x) = arg.get_short() {
let mut s = x.to_ascii_lowercase().to_string();
s.push(if x.is_ascii_lowercase() { '0' } else { '1' });
s
} else if let Some(x) = arg.get_long() {
x.to_string()
} else {
let mut s = '{'.to_string();
s.push_str(arg.get_id().as_str());
s
};
(arg.get_display_order(), key)
}
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
fn needs_options_tag(&self) -> bool {
debug!("Usage::needs_options_tag");
'outer: for f in self.cmd.get_non_positionals() {
debug!("Usage::needs_options_tag:iter: f={}", f.get_id());
// Don't print `[OPTIONS]` just for help or version
if f.get_long() == Some("help") || f.get_long() == Some("version") {
debug!("Usage::needs_options_tag:iter Option is built-in");
continue;
}
if f.is_hide_set() {
debug!("Usage::needs_options_tag:iter Option is hidden");
continue;
}
if f.is_required_set() {
debug!("Usage::needs_options_tag:iter Option is required");
continue;
}
for grp_s in self.cmd.groups_for_arg(f.get_id()) {
debug!("Usage::needs_options_tag:iter:iter: grp_s={:?}", grp_s);
if self.cmd.get_groups().any(|g| g.id == grp_s && g.required) {
debug!("Usage::needs_options_tag:iter:iter: Group is required");
continue 'outer;
}
}
debug!("Usage::needs_options_tag:iter: [OPTIONS] required");
return true;
}
debug!("Usage::needs_options_tag: [OPTIONS] not required");
false
}
// Returns the required args in usage string form by fully unrolling all groups
pub(crate) fn write_args(&self, incls: &[Id], force_optional: bool, styled: &mut StyledStr) {
for required in self.get_args(incls, force_optional) {
styled.none(" ");
styled.extend(required.into_iter());
}
}
pub(crate) fn get_args(&self, incls: &[Id], force_optional: bool) -> Vec<StyledStr> {
debug!("Usage::get_args: incls={:?}", incls,);
let required_owned;
let required = if let Some(required) = self.required {
required
} else {
required_owned = self.cmd.required_graph();
&required_owned
};
let mut unrolled_reqs = Vec::new();
for a in required.iter() {
let is_relevant = |(val, req_arg): &(ArgPredicate, Id)| -> Option<Id> {
let required = match val {
ArgPredicate::Equals(_) => false,
ArgPredicate::IsPresent => true,
};
required.then(|| req_arg.clone())
};
for aa in self.cmd.unroll_arg_requires(is_relevant, a) {
// if we don't check for duplicates here this causes duplicate error messages
// see https://github.com/clap-rs/clap/issues/2770
unrolled_reqs.push(aa);
}
// always include the required arg itself. it will not be enumerated
// by unroll_requirements_for_arg.
unrolled_reqs.push(a.clone());
}
debug!("Usage::get_args: unrolled_reqs={:?}", unrolled_reqs);
let mut required_groups_members = FlatSet::new();
let mut required_groups = FlatSet::new();
for req in unrolled_reqs.iter().chain(incls.iter()) {
if self.cmd.find_group(req).is_some() {
let group_members = self.cmd.unroll_args_in_group(req);
let elem = self.cmd.format_group(req);
required_groups.insert(elem);
required_groups_members.extend(group_members);
} else {
debug_assert!(self.cmd.find(req).is_some());
}
}
let mut required_opts = FlatSet::new();
let mut required_positionals = Vec::new();
for req in unrolled_reqs.iter().chain(incls.iter()) {
if let Some(arg) = self.cmd.find(req) {
if required_groups_members.contains(arg.get_id()) {
continue;
}
let stylized = arg.stylized(Some(!force_optional));
if let Some(index) = arg.get_index() {
let new_len = index + 1;
if required_positionals.len() < new_len {
required_positionals.resize(new_len, None);
}
required_positionals[index] = Some(stylized);
} else {
required_opts.insert(stylized);
}
} else {
debug_assert!(self.cmd.find_group(req).is_some());
}
}
for pos in self.cmd.get_positionals() {
if pos.is_hide_set() {
continue;
}
if required_groups_members.contains(pos.get_id()) {
continue;
}
let index = pos.get_index().unwrap();
let new_len = index + 1;
if required_positionals.len() < new_len {
required_positionals.resize(new_len, None);
}
if required_positionals[index].is_some() {
if pos.is_last_set() {
let styled = required_positionals[index].take().unwrap();
let mut new = StyledStr::new();
new.literal("-- ");
new.extend(styled.into_iter());
required_positionals[index] = Some(new);
}
} else {
let mut styled;
if pos.is_last_set() {
styled = StyledStr::new();
styled.literal("[-- ");
styled.extend(pos.stylized(Some(true)).into_iter());
styled.literal("]");
} else {
styled = pos.stylized(Some(false));
}
required_positionals[index] = Some(styled);
}
if pos.is_last_set() && force_optional {
required_positionals[index] = None;
}
}
let mut ret_val = Vec::new();
if !force_optional {
ret_val.extend(required_opts);
ret_val.extend(required_groups);
}
for pos in required_positionals.into_iter().flatten() {
ret_val.push(pos);
}
debug!("Usage::get_args: ret_val={:?}", ret_val);
ret_val
}
pub(crate) fn get_required_usage_from(
&self,
incls: &[Id],
matcher: Option<&ArgMatcher>,
incl_last: bool,
) -> Vec<StyledStr> {
debug!(
"Usage::get_required_usage_from: incls={:?}, matcher={:?}, incl_last={:?}",
incls,
matcher.is_some(),
incl_last
);
let required_owned;
let required = if let Some(required) = self.required {
required
} else {
required_owned = self.cmd.required_graph();
&required_owned
};
let mut unrolled_reqs = Vec::new();
for a in required.iter() {
let is_relevant = |(val, req_arg): &(ArgPredicate, Id)| -> Option<Id> {
let required = match val {
ArgPredicate::Equals(_) => {
if let Some(matcher) = matcher {
matcher.check_explicit(a, val)
} else {
false
}
}
ArgPredicate::IsPresent => true,
};
required.then(|| req_arg.clone())
};
for aa in self.cmd.unroll_arg_requires(is_relevant, a) {
// if we don't check for duplicates here this causes duplicate error messages
// see https://github.com/clap-rs/clap/issues/2770
unrolled_reqs.push(aa);
}
// always include the required arg itself. it will not be enumerated
// by unroll_requirements_for_arg.
unrolled_reqs.push(a.clone());
}
debug!(
"Usage::get_required_usage_from: unrolled_reqs={:?}",
unrolled_reqs
);
let mut required_groups_members = FlatSet::new();
let mut required_groups = FlatSet::new();
for req in unrolled_reqs.iter().chain(incls.iter()) {
if self.cmd.find_group(req).is_some() {
let group_members = self.cmd.unroll_args_in_group(req);
let is_present = matcher
.map(|m| {
group_members
.iter()
.any(|arg| m.check_explicit(arg, &ArgPredicate::IsPresent))
})
.unwrap_or(false);
debug!(
"Usage::get_required_usage_from:iter:{:?} group is_present={}",
req, is_present
);
if is_present {
continue;
}
let elem = self.cmd.format_group(req);
required_groups.insert(elem);
required_groups_members.extend(group_members);
} else {
debug_assert!(self.cmd.find(req).is_some());
}
}
let mut required_opts = FlatSet::new();
let mut required_positionals = Vec::new();
for req in unrolled_reqs.iter().chain(incls.iter()) {
if let Some(arg) = self.cmd.find(req) {
if required_groups_members.contains(arg.get_id()) {
continue;
}
let is_present = matcher
.map(|m| m.check_explicit(req, &ArgPredicate::IsPresent))
.unwrap_or(false);
debug!(
"Usage::get_required_usage_from:iter:{:?} arg is_present={}",
req, is_present
);
if is_present {
continue;
}
let stylized = arg.stylized(Some(true));
if let Some(index) = arg.get_index() {
if !arg.is_last_set() || incl_last {
let new_len = index + 1;
if required_positionals.len() < new_len {
required_positionals.resize(new_len, None);
}
required_positionals[index] = Some(stylized);
}
} else {
required_opts.insert(stylized);
}
} else {
debug_assert!(self.cmd.find_group(req).is_some());
}
}
let mut ret_val = Vec::new();
ret_val.extend(required_opts);
ret_val.extend(required_groups);
for pos in required_positionals.into_iter().flatten() {
ret_val.push(pos);
}
debug!("Usage::get_required_usage_from: ret_val={:?}", ret_val);
ret_val
}
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
pub(crate) fn validate(
&mut self,
parse_state: ParseState,
matcher: &mut ArgMatcher,
) -> ClapResult<()> {
debug!("Validator::validate");
let mut conflicts = Conflicts::new();
let has_subcmd = matcher.subcommand_name().is_some();
if let ParseState::Opt(a) = parse_state {
debug!("Validator::validate: needs_val_of={:?}", a);
let o = &self.cmd[&a];
let should_err = if let Some(v) = matcher.args.get(o.get_id()) {
v.all_val_groups_empty() && o.get_min_vals() != 0
} else {
true
};
if should_err {
return Err(Error::empty_value(
self.cmd,
&get_possible_values_cli(o)
.iter()
.filter(|pv| !pv.is_hide_set())
.map(|n| n.get_name().to_owned())
.collect::<Vec<_>>(),
o.to_string(),
));
}
}
if !has_subcmd && self.cmd.is_arg_required_else_help_set() {
let num_user_values = matcher
.arg_ids()
.filter(|arg_id| matcher.check_explicit(arg_id, &ArgPredicate::IsPresent))
.count();
if num_user_values == 0 {
let message = self.cmd.write_help_err(false);
return Err(Error::display_help_error(self.cmd, message));
}
}
if !has_subcmd && self.cmd.is_subcommand_required_set() {
let bn = self
.cmd
.get_bin_name()
.unwrap_or_else(|| self.cmd.get_name());
return Err(Error::missing_subcommand(
self.cmd,
bn.to_string(),
self.cmd
.all_subcommand_names()
.map(|s| s.to_owned())
.collect::<Vec<_>>(),
Usage::new(self.cmd)
.required(&self.required)
.create_usage_with_title(&[]),
));
}
ok!(self.validate_conflicts(matcher, &mut conflicts));
if !(self.cmd.is_subcommand_negates_reqs_set() && has_subcmd) {
ok!(self.validate_required(matcher, &mut conflicts));
}
Ok(())
}
fn validate_conflicts(
&mut self,
matcher: &ArgMatcher,
conflicts: &mut Conflicts,
) -> ClapResult<()> {
debug!("Validator::validate_conflicts");
ok!(self.validate_exclusive(matcher));
for arg_id in matcher
.arg_ids()
.filter(|arg_id| matcher.check_explicit(arg_id, &ArgPredicate::IsPresent))
.filter(|arg_id| self.cmd.find(arg_id).is_some())
{
debug!("Validator::validate_conflicts::iter: id={:?}", arg_id);
let conflicts = conflicts.gather_conflicts(self.cmd, matcher, arg_id);
ok!(self.build_conflict_err(arg_id, &conflicts, matcher));
}
Ok(())
}
fn validate_exclusive(&self, matcher: &ArgMatcher) -> ClapResult<()> {
debug!("Validator::validate_exclusive");
let args_count = matcher
.arg_ids()
.filter(|arg_id| {
matcher.check_explicit(arg_id, &crate::builder::ArgPredicate::IsPresent)
// Avoid including our own groups by checking none of them. If a group is present, the
// args for the group will be.
&& self.cmd.find(arg_id).is_some()
})
.count();
if args_count <= 1 {
// Nothing present to conflict with
return Ok(());
}
matcher
.arg_ids()
.filter(|arg_id| {
matcher.check_explicit(arg_id, &crate::builder::ArgPredicate::IsPresent)
})
.filter_map(|name| {
debug!("Validator::validate_exclusive:iter:{:?}", name);
self.cmd
.find(name)
// Find `arg`s which are exclusive but also appear with other args.
.filter(|&arg| arg.is_exclusive_set() && args_count > 1)
})
// Throw an error for the first conflict found.
.try_for_each(|arg| {
Err(Error::argument_conflict(
self.cmd,
arg.to_string(),
Vec::new(),
Usage::new(self.cmd)
.required(&self.required)
.create_usage_with_title(&[]),
))
})
}
fn build_conflict_err(
&self,
name: &Id,
conflict_ids: &[Id],
matcher: &ArgMatcher,
) -> ClapResult<()> {
if conflict_ids.is_empty() {
return Ok(());
}
debug!("Validator::build_conflict_err: name={:?}", name);
let mut seen = FlatSet::new();
let conflicts = conflict_ids
.iter()
.flat_map(|c_id| {
if self.cmd.find_group(c_id).is_some() {
self.cmd.unroll_args_in_group(c_id)
} else {
vec![c_id.clone()]
}
})
.filter_map(|c_id| {
seen.insert(c_id.clone()).then(|| {
let c_arg = self.cmd.find(&c_id).expect(INTERNAL_ERROR_MSG);
c_arg.to_string()
})
})
.collect();
let former_arg = self.cmd.find(name).expect(INTERNAL_ERROR_MSG);
let usg = self.build_conflict_err_usage(matcher, conflict_ids);
Err(Error::argument_conflict(
self.cmd,
former_arg.to_string(),
conflicts,
usg,
))
}
fn build_conflict_err_usage(
&self,
matcher: &ArgMatcher,
conflicting_keys: &[Id],
) -> Option<StyledStr> {
let used_filtered: Vec<Id> = matcher
.arg_ids()
.filter(|arg_id| matcher.check_explicit(arg_id, &ArgPredicate::IsPresent))
.filter(|n| {
// Filter out the args we don't want to specify.
self.cmd.find(n).map_or(false, |a| !a.is_hide_set())
})
.filter(|key| !conflicting_keys.contains(key))
.cloned()
.collect();
let required: Vec<Id> = used_filtered
.iter()
.filter_map(|key| self.cmd.find(key))
.flat_map(|arg| arg.requires.iter().map(|item| &item.1))
.filter(|key| !used_filtered.contains(key) && !conflicting_keys.contains(key))
.chain(used_filtered.iter())
.cloned()
.collect();
Usage::new(self.cmd)
.required(&self.required)
.create_usage_with_title(&required)
}
fn gather_requires(&mut self, matcher: &ArgMatcher) {
debug!("Validator::gather_requires");
for name in matcher
.arg_ids()
.filter(|arg_id| matcher.check_explicit(arg_id, &ArgPredicate::IsPresent))
{
debug!("Validator::gather_requires:iter:{:?}", name);
if let Some(arg) = self.cmd.find(name) {
let is_relevant = |(val, req_arg): &(ArgPredicate, Id)| -> Option<Id> {
let required = matcher.check_explicit(arg.get_id(), val);
required.then(|| req_arg.clone())
};
for req in self.cmd.unroll_arg_requires(is_relevant, arg.get_id()) {
self.required.insert(req);
}
} else if let Some(g) = self.cmd.find_group(name) {
debug!("Validator::gather_requires:iter:{:?}:group", name);
for r in &g.requires {
self.required.insert(r.clone());
}
}
}
}
fn validate_required(
&mut self,
matcher: &ArgMatcher,
conflicts: &mut Conflicts,
) -> ClapResult<()> {
debug!("Validator::validate_required: required={:?}", self.required);
self.gather_requires(matcher);
let mut missing_required = Vec::new();
let mut highest_index = 0;
let is_exclusive_present = matcher
.arg_ids()
.filter(|arg_id| matcher.check_explicit(arg_id, &ArgPredicate::IsPresent))
.any(|id| {
self.cmd
.find(id)
.map(|arg| arg.is_exclusive_set())
.unwrap_or_default()
});
debug!(
"Validator::validate_required: is_exclusive_present={}",
is_exclusive_present
);
for arg_or_group in self
.required
.iter()
.filter(|r| !matcher.check_explicit(r, &ArgPredicate::IsPresent))
{
debug!("Validator::validate_required:iter:aog={:?}", arg_or_group);
if let Some(arg) = self.cmd.find(arg_or_group) {
debug!("Validator::validate_required:iter: This is an arg");
if !is_exclusive_present && !self.is_missing_required_ok(arg, matcher, conflicts) {
debug!(
"Validator::validate_required:iter: Missing {:?}",
arg.get_id()
);
missing_required.push(arg.get_id().clone());
if !arg.is_last_set() {
highest_index = highest_index.max(arg.get_index().unwrap_or(0));
}
}
} else if let Some(group) = self.cmd.find_group(arg_or_group) {
debug!("Validator::validate_required:iter: This is a group");
if !self
.cmd
.unroll_args_in_group(&group.id)
.iter()
.any(|a| matcher.check_explicit(a, &ArgPredicate::IsPresent))
{
debug!(
"Validator::validate_required:iter: Missing {:?}",
group.get_id()
);
missing_required.push(group.get_id().clone());
}
}
}
// Validate the conditionally required args
for a in self
.cmd
.get_arguments()
.filter(|a| !matcher.check_explicit(a.get_id(), &ArgPredicate::IsPresent))
{
let mut required = false;
for (other, val) in &a.r_ifs {
if matcher.check_explicit(other, &ArgPredicate::Equals(val.into())) {
debug!(
"Validator::validate_required:iter: Missing {:?}",
a.get_id()
);
required = true;
}
}
let match_all = a.r_ifs_all.iter().all(|(other, val)| {
matcher.check_explicit(other, &ArgPredicate::Equals(val.into()))
});
if match_all && !a.r_ifs_all.is_empty() {
debug!(
"Validator::validate_required:iter: Missing {:?}",
a.get_id()
);
required = true;
}
if (!a.r_unless.is_empty() || !a.r_unless_all.is_empty())
&& self.fails_arg_required_unless(a, matcher)
{
debug!(
"Validator::validate_required:iter: Missing {:?}",
a.get_id()
);
required = true;
}
if required {
missing_required.push(a.get_id().clone());
if !a.is_last_set() {
highest_index = highest_index.max(a.get_index().unwrap_or(0));
}
}
}
// For display purposes, include all of the preceding positional arguments
if !self.cmd.is_allow_missing_positional_set() {
for pos in self
.cmd
.get_positionals()
.filter(|a| !matcher.check_explicit(a.get_id(), &ArgPredicate::IsPresent))
{
if pos.get_index() < Some(highest_index) {
debug!(
"Validator::validate_required:iter: Missing {:?}",
pos.get_id()
);
missing_required.push(pos.get_id().clone());
}
}
}
if !missing_required.is_empty() {
ok!(self.missing_required_error(matcher, missing_required));
}
Ok(())
}
fn is_missing_required_ok(
&self,
a: &Arg,
matcher: &ArgMatcher,
conflicts: &mut Conflicts,
) -> bool {
debug!("Validator::is_missing_required_ok: {}", a.get_id());
let conflicts = conflicts.gather_conflicts(self.cmd, matcher, a.get_id());
!conflicts.is_empty()
}
sourcepub fn get_help(&self) -> Option<&StyledStr>
pub fn get_help(&self) -> Option<&StyledStr>
Get the help specified for this argument, if any
Examples found in repository?
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
fn write_arg(&mut self, arg: &Arg, next_line_help: bool, longest: usize) {
let spec_vals = &self.spec_vals(arg);
self.none(TAB);
self.short(arg);
self.long(arg);
self.writer.extend(arg.stylize_arg_suffix(None).into_iter());
self.align_to_about(arg, next_line_help, longest);
let about = if self.use_long {
arg.get_long_help()
.or_else(|| arg.get_help())
.unwrap_or_default()
} else {
arg.get_help()
.or_else(|| arg.get_long_help())
.unwrap_or_default()
};
self.help(Some(arg), about, spec_vals, next_line_help, longest);
}
/// Writes argument's short command to the wrapped stream.
fn short(&mut self, arg: &Arg) {
debug!("HelpTemplate::short");
if let Some(s) = arg.get_short() {
self.literal(format!("-{}", s));
} else if arg.get_long().is_some() {
self.none(" ");
}
}
/// Writes argument's long command to the wrapped stream.
fn long(&mut self, arg: &Arg) {
debug!("HelpTemplate::long");
if let Some(long) = arg.get_long() {
if arg.get_short().is_some() {
self.none(", ");
}
self.literal(format!("--{}", long));
}
}
/// Write alignment padding between arg's switches/values and its about message.
fn align_to_about(&mut self, arg: &Arg, next_line_help: bool, longest: usize) {
debug!(
"HelpTemplate::align_to_about: arg={}, next_line_help={}, longest={}",
arg.get_id(),
next_line_help,
longest
);
if self.use_long || next_line_help {
// long help prints messages on the next line so it doesn't need to align text
debug!("HelpTemplate::align_to_about: printing long help so skip alignment");
} else if !arg.is_positional() {
let self_len = display_width(&arg.to_string());
// Since we're writing spaces from the tab point we first need to know if we
// had a long and short, or just short
let padding = if arg.get_long().is_some() {
// Only account 4 after the val
TAB_WIDTH
} else {
// Only account for ', --' + 4 after the val
TAB_WIDTH + 4
};
let spcs = longest + padding - self_len;
debug!(
"HelpTemplate::align_to_about: positional=false arg_len={}, spaces={}",
self_len, spcs
);
self.spaces(spcs);
} else {
let self_len = display_width(&arg.to_string());
let padding = TAB_WIDTH;
let spcs = longest + padding - self_len;
debug!(
"HelpTemplate::align_to_about: positional=true arg_len={}, spaces={}",
self_len, spcs
);
self.spaces(spcs);
}
}
/// Writes argument's help to the wrapped stream.
fn help(
&mut self,
arg: Option<&Arg>,
about: &StyledStr,
spec_vals: &str,
next_line_help: bool,
longest: usize,
) {
debug!("HelpTemplate::help");
// Is help on next line, if so then indent
if next_line_help {
debug!("HelpTemplate::help: Next Line...{:?}", next_line_help);
self.none("\n");
self.none(TAB);
self.none(NEXT_LINE_INDENT);
}
let spaces = if next_line_help {
TAB.len() + NEXT_LINE_INDENT.len()
} else if let Some(true) = arg.map(|a| a.is_positional()) {
longest + TAB_WIDTH * 2
} else {
longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4
};
let trailing_indent = spaces; // Don't indent any further than the first line is indented
let trailing_indent = self.get_spaces(trailing_indent);
let mut help = about.clone();
replace_newline_var(&mut help);
if !spec_vals.is_empty() {
if !help.is_empty() {
let sep = if self.use_long && arg.is_some() {
"\n\n"
} else {
" "
};
help.none(sep);
}
help.none(spec_vals);
}
let avail_chars = self.term_w.saturating_sub(spaces);
debug!(
"HelpTemplate::help: help_width={}, spaces={}, avail={}",
spaces,
help.display_width(),
avail_chars
);
help.wrap(avail_chars);
help.indent("", &trailing_indent);
let help_is_empty = help.is_empty();
self.writer.extend(help.into_iter());
if let Some(arg) = arg {
const DASH_SPACE: usize = "- ".len();
const COLON_SPACE: usize = ": ".len();
let possible_vals = arg.get_possible_values();
if self.use_long
&& !arg.is_hide_possible_values_set()
&& possible_vals.iter().any(PossibleValue::should_show_help)
{
debug!(
"HelpTemplate::help: Found possible vals...{:?}",
possible_vals
);
if !help_is_empty {
self.none("\n\n");
self.spaces(spaces);
}
self.none("Possible values:");
let longest = possible_vals
.iter()
.filter_map(|f| f.get_visible_quoted_name().map(|name| display_width(&name)))
.max()
.expect("Only called with possible value");
let help_longest = possible_vals
.iter()
.filter_map(|f| f.get_visible_help().map(|h| h.display_width()))
.max()
.expect("Only called with possible value with help");
// should new line
let taken = longest + spaces + DASH_SPACE;
let possible_value_new_line =
self.term_w >= taken && self.term_w < taken + COLON_SPACE + help_longest;
let spaces = spaces + TAB_WIDTH - DASH_SPACE;
let trailing_indent = if possible_value_new_line {
spaces + DASH_SPACE
} else {
spaces + longest + DASH_SPACE + COLON_SPACE
};
let trailing_indent = self.get_spaces(trailing_indent);
for pv in possible_vals.iter().filter(|pv| !pv.is_hide_set()) {
self.none("\n");
self.spaces(spaces);
self.none("- ");
self.literal(pv.get_name());
if let Some(help) = pv.get_help() {
debug!("HelpTemplate::help: Possible Value help");
if possible_value_new_line {
self.none(":\n");
self.spaces(trailing_indent.len());
} else {
self.none(": ");
// To align help messages
self.spaces(longest - display_width(pv.get_name()));
}
let avail_chars = if self.term_w > trailing_indent.len() {
self.term_w - trailing_indent.len()
} else {
usize::MAX
};
let mut help = help.clone();
replace_newline_var(&mut help);
help.wrap(avail_chars);
help.indent("", &trailing_indent);
self.writer.extend(help.into_iter());
}
}
}
}
}
/// Will use next line help on writing args.
fn will_args_wrap(&self, args: &[&Arg], longest: usize) -> bool {
args.iter()
.filter(|arg| should_show_arg(self.use_long, arg))
.any(|arg| {
let spec_vals = &self.spec_vals(arg);
self.arg_next_line_help(arg, spec_vals, longest)
})
}
fn arg_next_line_help(&self, arg: &Arg, spec_vals: &str, longest: usize) -> bool {
if self.next_line_help || arg.is_next_line_help_set() || self.use_long {
// setting_next_line
true
} else {
// force_next_line
let h = arg.get_help().unwrap_or_default();
let h_w = h.display_width() + display_width(spec_vals);
let taken = if arg.is_positional() {
longest + TAB_WIDTH * 2
} else {
longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4
};
self.term_w >= taken
&& (taken as f32 / self.term_w as f32) > 0.40
&& h_w > (self.term_w - taken)
}
}
More examples
4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146
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);
}
}
sourcepub fn get_long_help(&self) -> Option<&StyledStr>
pub fn get_long_help(&self) -> Option<&StyledStr>
Get the long help specified for this argument, if any
Examples
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()));
Examples found in repository?
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
fn write_arg(&mut self, arg: &Arg, next_line_help: bool, longest: usize) {
let spec_vals = &self.spec_vals(arg);
self.none(TAB);
self.short(arg);
self.long(arg);
self.writer.extend(arg.stylize_arg_suffix(None).into_iter());
self.align_to_about(arg, next_line_help, longest);
let about = if self.use_long {
arg.get_long_help()
.or_else(|| arg.get_help())
.unwrap_or_default()
} else {
arg.get_help()
.or_else(|| arg.get_long_help())
.unwrap_or_default()
};
self.help(Some(arg), about, spec_vals, next_line_help, longest);
}
More examples
4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610
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.term_w = self.term_w;
sc.max_w = self.max_w;
}
}
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 information (use `--help` for more detail)")
.long_help("Print help information (use `-h` for a summary)");
} else {
arg = arg.help("Print help information");
}
// 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 information");
// 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!("{} {}\n", display_name, ver)
}
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.none("<");
styled.none(g_string);
styled.none(">");
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);
let mut styled = StyledStr::new();
styled.none(msg);
styled
}
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.get_long_help().is_some()
|| v.is_hide_long_help_set()
|| v.is_hide_short_help_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)
}
sourcepub fn get_help_heading(&self) -> Option<&str>
pub fn get_help_heading(&self) -> Option<&str>
Get the help heading specified for this argument, if any
Examples found in repository?
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
pub(crate) fn write_all_args(&mut self) {
debug!("HelpTemplate::write_all_args");
let pos = self
.cmd
.get_positionals()
.filter(|a| a.get_help_heading().is_none())
.filter(|arg| should_show_arg(self.use_long, arg))
.collect::<Vec<_>>();
let non_pos = self
.cmd
.get_non_positionals()
.filter(|a| a.get_help_heading().is_none())
.filter(|arg| should_show_arg(self.use_long, arg))
.collect::<Vec<_>>();
let subcmds = self.cmd.has_visible_subcommands();
let custom_headings = self
.cmd
.get_arguments()
.filter_map(|arg| arg.get_help_heading())
.collect::<FlatSet<_>>();
let mut first = true;
if subcmds {
if !first {
self.none("\n\n");
}
first = false;
let default_help_heading = Str::from("Commands");
self.header(
self.cmd
.get_subcommand_help_heading()
.unwrap_or(&default_help_heading),
);
self.header(":\n");
self.write_subcommands(self.cmd);
}
if !pos.is_empty() {
if !first {
self.none("\n\n");
}
first = false;
// Write positional args if any
self.header("Arguments:\n");
self.write_args(&pos, "Arguments", positional_sort_key);
}
if !non_pos.is_empty() {
if !first {
self.none("\n\n");
}
first = false;
self.header("Options:\n");
self.write_args(&non_pos, "Options", option_sort_key);
}
if !custom_headings.is_empty() {
for heading in custom_headings {
let args = self
.cmd
.get_arguments()
.filter(|a| {
if let Some(help_heading) = a.get_help_heading() {
return help_heading == heading;
}
false
})
.filter(|arg| should_show_arg(self.use_long, arg))
.collect::<Vec<_>>();
if !args.is_empty() {
if !first {
self.none("\n\n");
}
first = false;
self.header(format!("{}:\n", heading));
self.write_args(&args, heading, option_sort_key);
}
}
}
}
sourcepub fn get_short(&self) -> Option<char>
pub fn get_short(&self) -> Option<char>
Get the short option name for this argument, if any
Examples found in repository?
3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146
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
/// 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, required: Option<bool>) -> StyledStr {
let mut styled = StyledStr::new();
// Write the name such --long or -l
if let Some(l) = self.get_long() {
styled.literal("--");
styled.literal(l);
} else if let Some(s) = self.get_short() {
styled.literal("-");
styled.literal(s);
}
styled.extend(self.stylize_arg_suffix(required).into_iter());
styled
}
More examples
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
fn short(&mut self, arg: &Arg) {
debug!("HelpTemplate::short");
if let Some(s) = arg.get_short() {
self.literal(format!("-{}", s));
} else if arg.get_long().is_some() {
self.none(" ");
}
}
/// Writes argument's long command to the wrapped stream.
fn long(&mut self, arg: &Arg) {
debug!("HelpTemplate::long");
if let Some(long) = arg.get_long() {
if arg.get_short().is_some() {
self.none(", ");
}
self.literal(format!("--{}", long));
}
}
/// Write alignment padding between arg's switches/values and its about message.
fn align_to_about(&mut self, arg: &Arg, next_line_help: bool, longest: usize) {
debug!(
"HelpTemplate::align_to_about: arg={}, next_line_help={}, longest={}",
arg.get_id(),
next_line_help,
longest
);
if self.use_long || next_line_help {
// long help prints messages on the next line so it doesn't need to align text
debug!("HelpTemplate::align_to_about: printing long help so skip alignment");
} else if !arg.is_positional() {
let self_len = display_width(&arg.to_string());
// Since we're writing spaces from the tab point we first need to know if we
// had a long and short, or just short
let padding = if arg.get_long().is_some() {
// Only account 4 after the val
TAB_WIDTH
} else {
// Only account for ', --' + 4 after the val
TAB_WIDTH + 4
};
let spcs = longest + padding - self_len;
debug!(
"HelpTemplate::align_to_about: positional=false arg_len={}, spaces={}",
self_len, spcs
);
self.spaces(spcs);
} else {
let self_len = display_width(&arg.to_string());
let padding = TAB_WIDTH;
let spcs = longest + padding - self_len;
debug!(
"HelpTemplate::align_to_about: positional=true arg_len={}, spaces={}",
self_len, spcs
);
self.spaces(spcs);
}
}
/// Writes argument's help to the wrapped stream.
fn help(
&mut self,
arg: Option<&Arg>,
about: &StyledStr,
spec_vals: &str,
next_line_help: bool,
longest: usize,
) {
debug!("HelpTemplate::help");
// Is help on next line, if so then indent
if next_line_help {
debug!("HelpTemplate::help: Next Line...{:?}", next_line_help);
self.none("\n");
self.none(TAB);
self.none(NEXT_LINE_INDENT);
}
let spaces = if next_line_help {
TAB.len() + NEXT_LINE_INDENT.len()
} else if let Some(true) = arg.map(|a| a.is_positional()) {
longest + TAB_WIDTH * 2
} else {
longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4
};
let trailing_indent = spaces; // Don't indent any further than the first line is indented
let trailing_indent = self.get_spaces(trailing_indent);
let mut help = about.clone();
replace_newline_var(&mut help);
if !spec_vals.is_empty() {
if !help.is_empty() {
let sep = if self.use_long && arg.is_some() {
"\n\n"
} else {
" "
};
help.none(sep);
}
help.none(spec_vals);
}
let avail_chars = self.term_w.saturating_sub(spaces);
debug!(
"HelpTemplate::help: help_width={}, spaces={}, avail={}",
spaces,
help.display_width(),
avail_chars
);
help.wrap(avail_chars);
help.indent("", &trailing_indent);
let help_is_empty = help.is_empty();
self.writer.extend(help.into_iter());
if let Some(arg) = arg {
const DASH_SPACE: usize = "- ".len();
const COLON_SPACE: usize = ": ".len();
let possible_vals = arg.get_possible_values();
if self.use_long
&& !arg.is_hide_possible_values_set()
&& possible_vals.iter().any(PossibleValue::should_show_help)
{
debug!(
"HelpTemplate::help: Found possible vals...{:?}",
possible_vals
);
if !help_is_empty {
self.none("\n\n");
self.spaces(spaces);
}
self.none("Possible values:");
let longest = possible_vals
.iter()
.filter_map(|f| f.get_visible_quoted_name().map(|name| display_width(&name)))
.max()
.expect("Only called with possible value");
let help_longest = possible_vals
.iter()
.filter_map(|f| f.get_visible_help().map(|h| h.display_width()))
.max()
.expect("Only called with possible value with help");
// should new line
let taken = longest + spaces + DASH_SPACE;
let possible_value_new_line =
self.term_w >= taken && self.term_w < taken + COLON_SPACE + help_longest;
let spaces = spaces + TAB_WIDTH - DASH_SPACE;
let trailing_indent = if possible_value_new_line {
spaces + DASH_SPACE
} else {
spaces + longest + DASH_SPACE + COLON_SPACE
};
let trailing_indent = self.get_spaces(trailing_indent);
for pv in possible_vals.iter().filter(|pv| !pv.is_hide_set()) {
self.none("\n");
self.spaces(spaces);
self.none("- ");
self.literal(pv.get_name());
if let Some(help) = pv.get_help() {
debug!("HelpTemplate::help: Possible Value help");
if possible_value_new_line {
self.none(":\n");
self.spaces(trailing_indent.len());
} else {
self.none(": ");
// To align help messages
self.spaces(longest - display_width(pv.get_name()));
}
let avail_chars = if self.term_w > trailing_indent.len() {
self.term_w - trailing_indent.len()
} else {
usize::MAX
};
let mut help = help.clone();
replace_newline_var(&mut help);
help.wrap(avail_chars);
help.indent("", &trailing_indent);
self.writer.extend(help.into_iter());
}
}
}
}
}
/// Will use next line help on writing args.
fn will_args_wrap(&self, args: &[&Arg], longest: usize) -> bool {
args.iter()
.filter(|arg| should_show_arg(self.use_long, arg))
.any(|arg| {
let spec_vals = &self.spec_vals(arg);
self.arg_next_line_help(arg, spec_vals, longest)
})
}
fn arg_next_line_help(&self, arg: &Arg, spec_vals: &str, longest: usize) -> bool {
if self.next_line_help || arg.is_next_line_help_set() || self.use_long {
// setting_next_line
true
} else {
// force_next_line
let h = arg.get_help().unwrap_or_default();
let h_w = h.display_width() + display_width(spec_vals);
let taken = if arg.is_positional() {
longest + TAB_WIDTH * 2
} else {
longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4
};
self.term_w >= taken
&& (taken as f32 / self.term_w as f32) > 0.40
&& h_w > (self.term_w - taken)
}
}
fn spec_vals(&self, a: &Arg) -> String {
debug!("HelpTemplate::spec_vals: a={}", a);
let mut spec_vals = Vec::new();
#[cfg(feature = "env")]
if let Some(ref env) = a.env {
if !a.is_hide_env_set() {
debug!(
"HelpTemplate::spec_vals: Found environment variable...[{:?}:{:?}]",
env.0, env.1
);
let env_val = if !a.is_hide_env_values_set() {
format!(
"={}",
env.1
.as_ref()
.map(|s| s.to_string_lossy())
.unwrap_or_default()
)
} else {
Default::default()
};
let env_info = format!("[env: {}{}]", env.0.to_string_lossy(), env_val);
spec_vals.push(env_info);
}
}
if a.is_takes_value_set() && !a.is_hide_default_value_set() && !a.default_vals.is_empty() {
debug!(
"HelpTemplate::spec_vals: Found default value...[{:?}]",
a.default_vals
);
let pvs = a
.default_vals
.iter()
.map(|pvs| pvs.to_string_lossy())
.map(|pvs| {
if pvs.contains(char::is_whitespace) {
Cow::from(format!("{:?}", pvs))
} else {
pvs
}
})
.collect::<Vec<_>>()
.join(" ");
spec_vals.push(format!("[default: {}]", pvs));
}
let als = a
.aliases
.iter()
.filter(|&als| als.1) // visible
.map(|als| als.0.as_str()) // name
.collect::<Vec<_>>()
.join(", ");
if !als.is_empty() {
debug!("HelpTemplate::spec_vals: Found aliases...{:?}", a.aliases);
spec_vals.push(format!("[aliases: {}]", als));
}
let als = a
.short_aliases
.iter()
.filter(|&als| als.1) // visible
.map(|&als| als.0.to_string()) // name
.collect::<Vec<_>>()
.join(", ");
if !als.is_empty() {
debug!(
"HelpTemplate::spec_vals: Found short aliases...{:?}",
a.short_aliases
);
spec_vals.push(format!("[short aliases: {}]", als));
}
let possible_vals = a.get_possible_values();
if !(a.is_hide_possible_values_set()
|| possible_vals.is_empty()
|| self.use_long && possible_vals.iter().any(PossibleValue::should_show_help))
{
debug!(
"HelpTemplate::spec_vals: Found possible vals...{:?}",
possible_vals
);
let pvs = possible_vals
.iter()
.filter_map(PossibleValue::get_visible_quoted_name)
.collect::<Vec<_>>()
.join(", ");
spec_vals.push(format!("[possible values: {}]", pvs));
}
let connector = if self.use_long { "\n" } else { " " };
spec_vals.join(connector)
}
fn header<T: Into<String>>(&mut self, msg: T) {
self.writer.header(msg);
}
fn literal<T: Into<String>>(&mut self, msg: T) {
self.writer.literal(msg);
}
fn none<T: Into<String>>(&mut self, msg: T) {
self.writer.none(msg);
}
fn get_spaces(&self, n: usize) -> String {
" ".repeat(n)
}
fn spaces(&mut self, n: usize) {
self.none(self.get_spaces(n));
}
}
/// Subcommand handling
impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> {
/// Writes help for subcommands of a Parser Object to the wrapped stream.
fn write_subcommands(&mut self, cmd: &Command) {
debug!("HelpTemplate::write_subcommands");
// The shortest an arg can legally be is 2 (i.e. '-x')
let mut longest = 2;
let mut ord_v = Vec::new();
for subcommand in cmd
.get_subcommands()
.filter(|subcommand| should_show_subcommand(subcommand))
{
let mut styled = StyledStr::new();
styled.literal(subcommand.get_name());
if let Some(short) = subcommand.get_short_flag() {
styled.none(", ");
styled.literal(format!("-{}", short));
}
if let Some(long) = subcommand.get_long_flag() {
styled.none(", ");
styled.literal(format!("--{}", long));
}
longest = longest.max(styled.display_width());
ord_v.push((subcommand.get_display_order(), styled, subcommand));
}
ord_v.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));
debug!("HelpTemplate::write_subcommands longest = {}", longest);
let next_line_help = self.will_subcommands_wrap(cmd.get_subcommands(), longest);
let mut first = true;
for (_, sc_str, sc) in ord_v {
if first {
first = false;
} else {
self.none("\n");
}
self.write_subcommand(sc_str, sc, next_line_help, longest);
}
}
/// Will use next line help on writing subcommands.
fn will_subcommands_wrap<'a>(
&self,
subcommands: impl IntoIterator<Item = &'a Command>,
longest: usize,
) -> bool {
subcommands
.into_iter()
.filter(|&subcommand| should_show_subcommand(subcommand))
.any(|subcommand| {
let spec_vals = &self.sc_spec_vals(subcommand);
self.subcommand_next_line_help(subcommand, spec_vals, longest)
})
}
fn write_subcommand(
&mut self,
sc_str: StyledStr,
cmd: &Command,
next_line_help: bool,
longest: usize,
) {
debug!("HelpTemplate::write_subcommand");
let spec_vals = &self.sc_spec_vals(cmd);
let about = cmd
.get_about()
.or_else(|| cmd.get_long_about())
.unwrap_or_default();
self.subcmd(sc_str, next_line_help, longest);
self.help(None, about, spec_vals, next_line_help, longest)
}
fn sc_spec_vals(&self, a: &Command) -> String {
debug!("HelpTemplate::sc_spec_vals: a={}", a.get_name());
let mut spec_vals = vec![];
let mut short_als = a
.get_visible_short_flag_aliases()
.map(|a| format!("-{}", a))
.collect::<Vec<_>>();
let als = a.get_visible_aliases().map(|s| s.to_string());
short_als.extend(als);
let all_als = short_als.join(", ");
if !all_als.is_empty() {
debug!(
"HelpTemplate::spec_vals: Found aliases...{:?}",
a.get_all_aliases().collect::<Vec<_>>()
);
debug!(
"HelpTemplate::spec_vals: Found short flag aliases...{:?}",
a.get_all_short_flag_aliases().collect::<Vec<_>>()
);
spec_vals.push(format!("[aliases: {}]", all_als));
}
spec_vals.join(" ")
}
fn subcommand_next_line_help(&self, cmd: &Command, spec_vals: &str, longest: usize) -> bool {
if self.next_line_help | self.use_long {
// setting_next_line
true
} else {
// force_next_line
let h = cmd.get_about().unwrap_or_default();
let h_w = h.display_width() + display_width(spec_vals);
let taken = longest + TAB_WIDTH * 2;
self.term_w >= taken
&& (taken as f32 / self.term_w as f32) > 0.40
&& h_w > (self.term_w - taken)
}
}
/// Writes subcommand to the wrapped stream.
fn subcmd(&mut self, sc_str: StyledStr, next_line_help: bool, longest: usize) {
let width = sc_str.display_width();
self.none(TAB);
self.writer.extend(sc_str.into_iter());
if !next_line_help {
self.spaces(longest + TAB_WIDTH - width);
}
}
}
const NEXT_LINE_INDENT: &str = " ";
type ArgSortKey = fn(arg: &Arg) -> (usize, String);
fn positional_sort_key(arg: &Arg) -> (usize, String) {
(arg.get_index().unwrap_or(0), String::new())
}
fn option_sort_key(arg: &Arg) -> (usize, String) {
// Formatting key like this to ensure that:
// 1. Argument has long flags are printed just after short flags.
// 2. For two args both have short flags like `-c` and `-C`, the
// `-C` arg is printed just after the `-c` arg
// 3. For args without short or long flag, print them at last(sorted
// by arg name).
// Example order: -a, -b, -B, -s, --select-file, --select-folder, -x
let key = if let Some(x) = arg.get_short() {
let mut s = x.to_ascii_lowercase().to_string();
s.push(if x.is_ascii_lowercase() { '0' } else { '1' });
s
} else if let Some(x) = arg.get_long() {
x.to_string()
} else {
let mut s = '{'.to_string();
s.push_str(arg.get_id().as_str());
s
};
(arg.get_display_order(), key)
}
pub(crate) fn dimensions() -> (Option<usize>, Option<usize>) {
#[cfg(not(feature = "wrap_help"))]
return (None, None);
#[cfg(feature = "wrap_help")]
terminal_size::terminal_size()
.map(|(w, h)| (Some(w.0.into()), Some(h.0.into())))
.unwrap_or_else(|| (parse_env("COLUMNS"), parse_env("LINES")))
}
#[cfg(feature = "wrap_help")]
fn parse_env(var: &str) -> Option<usize> {
some!(some!(std::env::var_os(var)).to_str())
.parse::<usize>()
.ok()
}
fn should_show_arg(use_long: bool, arg: &Arg) -> bool {
debug!(
"should_show_arg: use_long={:?}, arg={}",
use_long,
arg.get_id()
);
if arg.is_hide_set() {
return false;
}
(!arg.is_hide_long_help_set() && use_long)
|| (!arg.is_hide_short_help_set() && !use_long)
|| arg.is_next_line_help_set()
}
fn should_show_subcommand(subcommand: &Command) -> bool {
!subcommand.is_hide_set()
}
fn replace_newline_var(styled: &mut StyledStr) {
for (_, content) in styled.iter_mut() {
*content = content.replace("{n}", "\n");
}
}
fn longest_filter(arg: &Arg) -> bool {
arg.is_takes_value_set() || arg.get_long().is_some() || arg.get_short().is_none()
}
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
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() {
let derive_hint = if cfg!(feature = "derive") {
" (note: `Args` implicitly creates `ArgGroup`s; disable with `#[group(skip)]`"
} else {
""
};
// 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(),
derive_hint
);
// 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(),
derive_hint
);
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
);
}
}
// 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"
);
}
cmd._panic_on_missing_help(cmd.is_help_expected_set());
assert_app_flags(cmd);
}
sourcepub fn get_visible_short_aliases(&self) -> Option<Vec<char>>
pub fn get_visible_short_aliases(&self) -> Option<Vec<char>>
Get visible short aliases for this argument, if any
sourcepub fn get_all_short_aliases(&self) -> Option<Vec<char>>
pub fn get_all_short_aliases(&self) -> Option<Vec<char>>
Get all short aliases for this argument, if any, both visible and hidden.
sourcepub fn get_short_and_visible_aliases(&self) -> Option<Vec<char>>
pub fn get_short_and_visible_aliases(&self) -> Option<Vec<char>>
Get the short option name and its visible aliases, if any
sourcepub fn get_long(&self) -> Option<&str>
pub fn get_long(&self) -> Option<&str>
Get the long option name for this argument, if any
Examples found in repository?
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
fn short(&mut self, arg: &Arg) {
debug!("HelpTemplate::short");
if let Some(s) = arg.get_short() {
self.literal(format!("-{}", s));
} else if arg.get_long().is_some() {
self.none(" ");
}
}
/// Writes argument's long command to the wrapped stream.
fn long(&mut self, arg: &Arg) {
debug!("HelpTemplate::long");
if let Some(long) = arg.get_long() {
if arg.get_short().is_some() {
self.none(", ");
}
self.literal(format!("--{}", long));
}
}
/// Write alignment padding between arg's switches/values and its about message.
fn align_to_about(&mut self, arg: &Arg, next_line_help: bool, longest: usize) {
debug!(
"HelpTemplate::align_to_about: arg={}, next_line_help={}, longest={}",
arg.get_id(),
next_line_help,
longest
);
if self.use_long || next_line_help {
// long help prints messages on the next line so it doesn't need to align text
debug!("HelpTemplate::align_to_about: printing long help so skip alignment");
} else if !arg.is_positional() {
let self_len = display_width(&arg.to_string());
// Since we're writing spaces from the tab point we first need to know if we
// had a long and short, or just short
let padding = if arg.get_long().is_some() {
// Only account 4 after the val
TAB_WIDTH
} else {
// Only account for ', --' + 4 after the val
TAB_WIDTH + 4
};
let spcs = longest + padding - self_len;
debug!(
"HelpTemplate::align_to_about: positional=false arg_len={}, spaces={}",
self_len, spcs
);
self.spaces(spcs);
} else {
let self_len = display_width(&arg.to_string());
let padding = TAB_WIDTH;
let spcs = longest + padding - self_len;
debug!(
"HelpTemplate::align_to_about: positional=true arg_len={}, spaces={}",
self_len, spcs
);
self.spaces(spcs);
}
}
/// Writes argument's help to the wrapped stream.
fn help(
&mut self,
arg: Option<&Arg>,
about: &StyledStr,
spec_vals: &str,
next_line_help: bool,
longest: usize,
) {
debug!("HelpTemplate::help");
// Is help on next line, if so then indent
if next_line_help {
debug!("HelpTemplate::help: Next Line...{:?}", next_line_help);
self.none("\n");
self.none(TAB);
self.none(NEXT_LINE_INDENT);
}
let spaces = if next_line_help {
TAB.len() + NEXT_LINE_INDENT.len()
} else if let Some(true) = arg.map(|a| a.is_positional()) {
longest + TAB_WIDTH * 2
} else {
longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4
};
let trailing_indent = spaces; // Don't indent any further than the first line is indented
let trailing_indent = self.get_spaces(trailing_indent);
let mut help = about.clone();
replace_newline_var(&mut help);
if !spec_vals.is_empty() {
if !help.is_empty() {
let sep = if self.use_long && arg.is_some() {
"\n\n"
} else {
" "
};
help.none(sep);
}
help.none(spec_vals);
}
let avail_chars = self.term_w.saturating_sub(spaces);
debug!(
"HelpTemplate::help: help_width={}, spaces={}, avail={}",
spaces,
help.display_width(),
avail_chars
);
help.wrap(avail_chars);
help.indent("", &trailing_indent);
let help_is_empty = help.is_empty();
self.writer.extend(help.into_iter());
if let Some(arg) = arg {
const DASH_SPACE: usize = "- ".len();
const COLON_SPACE: usize = ": ".len();
let possible_vals = arg.get_possible_values();
if self.use_long
&& !arg.is_hide_possible_values_set()
&& possible_vals.iter().any(PossibleValue::should_show_help)
{
debug!(
"HelpTemplate::help: Found possible vals...{:?}",
possible_vals
);
if !help_is_empty {
self.none("\n\n");
self.spaces(spaces);
}
self.none("Possible values:");
let longest = possible_vals
.iter()
.filter_map(|f| f.get_visible_quoted_name().map(|name| display_width(&name)))
.max()
.expect("Only called with possible value");
let help_longest = possible_vals
.iter()
.filter_map(|f| f.get_visible_help().map(|h| h.display_width()))
.max()
.expect("Only called with possible value with help");
// should new line
let taken = longest + spaces + DASH_SPACE;
let possible_value_new_line =
self.term_w >= taken && self.term_w < taken + COLON_SPACE + help_longest;
let spaces = spaces + TAB_WIDTH - DASH_SPACE;
let trailing_indent = if possible_value_new_line {
spaces + DASH_SPACE
} else {
spaces + longest + DASH_SPACE + COLON_SPACE
};
let trailing_indent = self.get_spaces(trailing_indent);
for pv in possible_vals.iter().filter(|pv| !pv.is_hide_set()) {
self.none("\n");
self.spaces(spaces);
self.none("- ");
self.literal(pv.get_name());
if let Some(help) = pv.get_help() {
debug!("HelpTemplate::help: Possible Value help");
if possible_value_new_line {
self.none(":\n");
self.spaces(trailing_indent.len());
} else {
self.none(": ");
// To align help messages
self.spaces(longest - display_width(pv.get_name()));
}
let avail_chars = if self.term_w > trailing_indent.len() {
self.term_w - trailing_indent.len()
} else {
usize::MAX
};
let mut help = help.clone();
replace_newline_var(&mut help);
help.wrap(avail_chars);
help.indent("", &trailing_indent);
self.writer.extend(help.into_iter());
}
}
}
}
}
/// Will use next line help on writing args.
fn will_args_wrap(&self, args: &[&Arg], longest: usize) -> bool {
args.iter()
.filter(|arg| should_show_arg(self.use_long, arg))
.any(|arg| {
let spec_vals = &self.spec_vals(arg);
self.arg_next_line_help(arg, spec_vals, longest)
})
}
fn arg_next_line_help(&self, arg: &Arg, spec_vals: &str, longest: usize) -> bool {
if self.next_line_help || arg.is_next_line_help_set() || self.use_long {
// setting_next_line
true
} else {
// force_next_line
let h = arg.get_help().unwrap_or_default();
let h_w = h.display_width() + display_width(spec_vals);
let taken = if arg.is_positional() {
longest + TAB_WIDTH * 2
} else {
longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4
};
self.term_w >= taken
&& (taken as f32 / self.term_w as f32) > 0.40
&& h_w > (self.term_w - taken)
}
}
fn spec_vals(&self, a: &Arg) -> String {
debug!("HelpTemplate::spec_vals: a={}", a);
let mut spec_vals = Vec::new();
#[cfg(feature = "env")]
if let Some(ref env) = a.env {
if !a.is_hide_env_set() {
debug!(
"HelpTemplate::spec_vals: Found environment variable...[{:?}:{:?}]",
env.0, env.1
);
let env_val = if !a.is_hide_env_values_set() {
format!(
"={}",
env.1
.as_ref()
.map(|s| s.to_string_lossy())
.unwrap_or_default()
)
} else {
Default::default()
};
let env_info = format!("[env: {}{}]", env.0.to_string_lossy(), env_val);
spec_vals.push(env_info);
}
}
if a.is_takes_value_set() && !a.is_hide_default_value_set() && !a.default_vals.is_empty() {
debug!(
"HelpTemplate::spec_vals: Found default value...[{:?}]",
a.default_vals
);
let pvs = a
.default_vals
.iter()
.map(|pvs| pvs.to_string_lossy())
.map(|pvs| {
if pvs.contains(char::is_whitespace) {
Cow::from(format!("{:?}", pvs))
} else {
pvs
}
})
.collect::<Vec<_>>()
.join(" ");
spec_vals.push(format!("[default: {}]", pvs));
}
let als = a
.aliases
.iter()
.filter(|&als| als.1) // visible
.map(|als| als.0.as_str()) // name
.collect::<Vec<_>>()
.join(", ");
if !als.is_empty() {
debug!("HelpTemplate::spec_vals: Found aliases...{:?}", a.aliases);
spec_vals.push(format!("[aliases: {}]", als));
}
let als = a
.short_aliases
.iter()
.filter(|&als| als.1) // visible
.map(|&als| als.0.to_string()) // name
.collect::<Vec<_>>()
.join(", ");
if !als.is_empty() {
debug!(
"HelpTemplate::spec_vals: Found short aliases...{:?}",
a.short_aliases
);
spec_vals.push(format!("[short aliases: {}]", als));
}
let possible_vals = a.get_possible_values();
if !(a.is_hide_possible_values_set()
|| possible_vals.is_empty()
|| self.use_long && possible_vals.iter().any(PossibleValue::should_show_help))
{
debug!(
"HelpTemplate::spec_vals: Found possible vals...{:?}",
possible_vals
);
let pvs = possible_vals
.iter()
.filter_map(PossibleValue::get_visible_quoted_name)
.collect::<Vec<_>>()
.join(", ");
spec_vals.push(format!("[possible values: {}]", pvs));
}
let connector = if self.use_long { "\n" } else { " " };
spec_vals.join(connector)
}
fn header<T: Into<String>>(&mut self, msg: T) {
self.writer.header(msg);
}
fn literal<T: Into<String>>(&mut self, msg: T) {
self.writer.literal(msg);
}
fn none<T: Into<String>>(&mut self, msg: T) {
self.writer.none(msg);
}
fn get_spaces(&self, n: usize) -> String {
" ".repeat(n)
}
fn spaces(&mut self, n: usize) {
self.none(self.get_spaces(n));
}
}
/// Subcommand handling
impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> {
/// Writes help for subcommands of a Parser Object to the wrapped stream.
fn write_subcommands(&mut self, cmd: &Command) {
debug!("HelpTemplate::write_subcommands");
// The shortest an arg can legally be is 2 (i.e. '-x')
let mut longest = 2;
let mut ord_v = Vec::new();
for subcommand in cmd
.get_subcommands()
.filter(|subcommand| should_show_subcommand(subcommand))
{
let mut styled = StyledStr::new();
styled.literal(subcommand.get_name());
if let Some(short) = subcommand.get_short_flag() {
styled.none(", ");
styled.literal(format!("-{}", short));
}
if let Some(long) = subcommand.get_long_flag() {
styled.none(", ");
styled.literal(format!("--{}", long));
}
longest = longest.max(styled.display_width());
ord_v.push((subcommand.get_display_order(), styled, subcommand));
}
ord_v.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));
debug!("HelpTemplate::write_subcommands longest = {}", longest);
let next_line_help = self.will_subcommands_wrap(cmd.get_subcommands(), longest);
let mut first = true;
for (_, sc_str, sc) in ord_v {
if first {
first = false;
} else {
self.none("\n");
}
self.write_subcommand(sc_str, sc, next_line_help, longest);
}
}
/// Will use next line help on writing subcommands.
fn will_subcommands_wrap<'a>(
&self,
subcommands: impl IntoIterator<Item = &'a Command>,
longest: usize,
) -> bool {
subcommands
.into_iter()
.filter(|&subcommand| should_show_subcommand(subcommand))
.any(|subcommand| {
let spec_vals = &self.sc_spec_vals(subcommand);
self.subcommand_next_line_help(subcommand, spec_vals, longest)
})
}
fn write_subcommand(
&mut self,
sc_str: StyledStr,
cmd: &Command,
next_line_help: bool,
longest: usize,
) {
debug!("HelpTemplate::write_subcommand");
let spec_vals = &self.sc_spec_vals(cmd);
let about = cmd
.get_about()
.or_else(|| cmd.get_long_about())
.unwrap_or_default();
self.subcmd(sc_str, next_line_help, longest);
self.help(None, about, spec_vals, next_line_help, longest)
}
fn sc_spec_vals(&self, a: &Command) -> String {
debug!("HelpTemplate::sc_spec_vals: a={}", a.get_name());
let mut spec_vals = vec![];
let mut short_als = a
.get_visible_short_flag_aliases()
.map(|a| format!("-{}", a))
.collect::<Vec<_>>();
let als = a.get_visible_aliases().map(|s| s.to_string());
short_als.extend(als);
let all_als = short_als.join(", ");
if !all_als.is_empty() {
debug!(
"HelpTemplate::spec_vals: Found aliases...{:?}",
a.get_all_aliases().collect::<Vec<_>>()
);
debug!(
"HelpTemplate::spec_vals: Found short flag aliases...{:?}",
a.get_all_short_flag_aliases().collect::<Vec<_>>()
);
spec_vals.push(format!("[aliases: {}]", all_als));
}
spec_vals.join(" ")
}
fn subcommand_next_line_help(&self, cmd: &Command, spec_vals: &str, longest: usize) -> bool {
if self.next_line_help | self.use_long {
// setting_next_line
true
} else {
// force_next_line
let h = cmd.get_about().unwrap_or_default();
let h_w = h.display_width() + display_width(spec_vals);
let taken = longest + TAB_WIDTH * 2;
self.term_w >= taken
&& (taken as f32 / self.term_w as f32) > 0.40
&& h_w > (self.term_w - taken)
}
}
/// Writes subcommand to the wrapped stream.
fn subcmd(&mut self, sc_str: StyledStr, next_line_help: bool, longest: usize) {
let width = sc_str.display_width();
self.none(TAB);
self.writer.extend(sc_str.into_iter());
if !next_line_help {
self.spaces(longest + TAB_WIDTH - width);
}
}
}
const NEXT_LINE_INDENT: &str = " ";
type ArgSortKey = fn(arg: &Arg) -> (usize, String);
fn positional_sort_key(arg: &Arg) -> (usize, String) {
(arg.get_index().unwrap_or(0), String::new())
}
fn option_sort_key(arg: &Arg) -> (usize, String) {
// Formatting key like this to ensure that:
// 1. Argument has long flags are printed just after short flags.
// 2. For two args both have short flags like `-c` and `-C`, the
// `-C` arg is printed just after the `-c` arg
// 3. For args without short or long flag, print them at last(sorted
// by arg name).
// Example order: -a, -b, -B, -s, --select-file, --select-folder, -x
let key = if let Some(x) = arg.get_short() {
let mut s = x.to_ascii_lowercase().to_string();
s.push(if x.is_ascii_lowercase() { '0' } else { '1' });
s
} else if let Some(x) = arg.get_long() {
x.to_string()
} else {
let mut s = '{'.to_string();
s.push_str(arg.get_id().as_str());
s
};
(arg.get_display_order(), key)
}
pub(crate) fn dimensions() -> (Option<usize>, Option<usize>) {
#[cfg(not(feature = "wrap_help"))]
return (None, None);
#[cfg(feature = "wrap_help")]
terminal_size::terminal_size()
.map(|(w, h)| (Some(w.0.into()), Some(h.0.into())))
.unwrap_or_else(|| (parse_env("COLUMNS"), parse_env("LINES")))
}
#[cfg(feature = "wrap_help")]
fn parse_env(var: &str) -> Option<usize> {
some!(some!(std::env::var_os(var)).to_str())
.parse::<usize>()
.ok()
}
fn should_show_arg(use_long: bool, arg: &Arg) -> bool {
debug!(
"should_show_arg: use_long={:?}, arg={}",
use_long,
arg.get_id()
);
if arg.is_hide_set() {
return false;
}
(!arg.is_hide_long_help_set() && use_long)
|| (!arg.is_hide_short_help_set() && !use_long)
|| arg.is_next_line_help_set()
}
fn should_show_subcommand(subcommand: &Command) -> bool {
!subcommand.is_hide_set()
}
fn replace_newline_var(styled: &mut StyledStr) {
for (_, content) in styled.iter_mut() {
*content = content.replace("{n}", "\n");
}
}
fn longest_filter(arg: &Arg) -> bool {
arg.is_takes_value_set() || arg.get_long().is_some() || arg.get_short().is_none()
}
More examples
3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146
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 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 == crate::parser::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 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::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
///
/// ```
/// # 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
/// 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, required: Option<bool>) -> StyledStr {
let mut styled = StyledStr::new();
// Write the name such --long or -l
if let Some(l) = self.get_long() {
styled.literal("--");
styled.literal(l);
} else if let Some(s) = self.get_short() {
styled.literal("-");
styled.literal(s);
}
styled.extend(self.stylize_arg_suffix(required).into_iter());
styled
}
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
fn needs_options_tag(&self) -> bool {
debug!("Usage::needs_options_tag");
'outer: for f in self.cmd.get_non_positionals() {
debug!("Usage::needs_options_tag:iter: f={}", f.get_id());
// Don't print `[OPTIONS]` just for help or version
if f.get_long() == Some("help") || f.get_long() == Some("version") {
debug!("Usage::needs_options_tag:iter Option is built-in");
continue;
}
if f.is_hide_set() {
debug!("Usage::needs_options_tag:iter Option is hidden");
continue;
}
if f.is_required_set() {
debug!("Usage::needs_options_tag:iter Option is required");
continue;
}
for grp_s in self.cmd.groups_for_arg(f.get_id()) {
debug!("Usage::needs_options_tag:iter:iter: grp_s={:?}", grp_s);
if self.cmd.get_groups().any(|g| g.id == grp_s && g.required) {
debug!("Usage::needs_options_tag:iter:iter: Group is required");
continue 'outer;
}
}
debug!("Usage::needs_options_tag:iter: [OPTIONS] required");
return true;
}
debug!("Usage::needs_options_tag: [OPTIONS] not required");
false
}
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
fn parse_long_arg(
&mut self,
matcher: &mut ArgMatcher,
long_arg: Result<&str, &RawOsStr>,
long_value: Option<&RawOsStr>,
parse_state: &ParseState,
pos_counter: usize,
valid_arg_found: &mut bool,
) -> ClapResult<ParseResult> {
// maybe here lifetime should be 'a
debug!("Parser::parse_long_arg");
#[allow(clippy::blocks_in_if_conditions)]
if matches!(parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if
self.cmd[opt].is_allow_hyphen_values_set())
{
debug!("Parser::parse_long_arg: prior arg accepts hyphenated values",);
return Ok(ParseResult::MaybeHyphenValue);
}
debug!("Parser::parse_long_arg: Does it contain '='...");
let long_arg = match long_arg {
Ok(long_arg) => long_arg,
Err(long_arg) => {
return Ok(ParseResult::NoMatchingArg {
arg: long_arg.to_str_lossy().into_owned(),
});
}
};
if long_arg.is_empty() {
debug_assert!(
long_value.is_some(),
"`--` should be filtered out before this point"
);
}
let arg = if let Some(arg) = self.cmd.get_keymap().get(long_arg) {
debug!("Parser::parse_long_arg: Found valid arg or flag '{}'", arg);
Some((long_arg, arg))
} else if self.cmd.is_infer_long_args_set() {
self.cmd.get_arguments().find_map(|a| {
if let Some(long) = a.get_long() {
if long.starts_with(long_arg) {
return Some((long, a));
}
}
a.aliases
.iter()
.find_map(|(alias, _)| alias.starts_with(long_arg).then(|| (alias.as_str(), a)))
})
} else {
None
};
if let Some((_long_arg, arg)) = arg {
let ident = Identifier::Long;
*valid_arg_found = true;
if arg.is_takes_value_set() {
debug!(
"Parser::parse_long_arg({:?}): Found an arg with value '{:?}'",
long_arg, &long_value
);
let has_eq = long_value.is_some();
self.parse_opt_value(ident, long_value, arg, matcher, has_eq)
} else if let Some(rest) = long_value {
let required = self.cmd.required_graph();
debug!(
"Parser::parse_long_arg({:?}): Got invalid literal `{:?}`",
long_arg, rest
);
let mut used: Vec<Id> = matcher
.arg_ids()
.filter(|arg_id| {
matcher.check_explicit(arg_id, &crate::builder::ArgPredicate::IsPresent)
})
.filter(|&n| {
self.cmd.find(n).map_or(true, |a| {
!(a.is_hide_set() || required.contains(a.get_id()))
})
})
.cloned()
.collect();
used.push(arg.get_id().clone());
Ok(ParseResult::UnneededAttachedValue {
rest: rest.to_str_lossy().into_owned(),
used,
arg: arg.to_string(),
})
} else {
debug!("Parser::parse_long_arg({:?}): Presence validated", long_arg);
let trailing_idx = None;
self.react(
Some(ident),
ValueSource::CommandLine,
arg,
vec![],
trailing_idx,
matcher,
)
}
} else if let Some(sc_name) = self.possible_long_flag_subcommand(long_arg) {
Ok(ParseResult::FlagSubCommand(sc_name.to_string()))
} else if self
.cmd
.get_keymap()
.get(&pos_counter)
.map_or(false, |arg| {
arg.is_allow_hyphen_values_set() && !arg.is_last_set()
})
{
debug!(
"Parser::parse_long_args: positional at {} allows hyphens",
pos_counter
);
Ok(ParseResult::MaybeHyphenValue)
} else {
Ok(ParseResult::NoMatchingArg {
arg: long_arg.to_owned(),
})
}
}
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
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() {
let derive_hint = if cfg!(feature = "derive") {
" (note: `Args` implicitly creates `ArgGroup`s; disable with `#[group(skip)]`"
} else {
""
};
// 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(),
derive_hint
);
// 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(),
derive_hint
);
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
);
}
}
// 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"
);
}
cmd._panic_on_missing_help(cmd.is_help_expected_set());
assert_app_flags(cmd);
}
sourcepub fn get_visible_aliases(&self) -> Option<Vec<&str>>
pub fn get_visible_aliases(&self) -> Option<Vec<&str>>
Get visible aliases for this argument, if any
sourcepub fn get_all_aliases(&self) -> Option<Vec<&str>>
pub fn get_all_aliases(&self) -> Option<Vec<&str>>
Get all aliases for this argument, if any, both visible and hidden.
sourcepub fn get_long_and_visible_aliases(&self) -> Option<Vec<&str>>
pub fn get_long_and_visible_aliases(&self) -> Option<Vec<&str>>
Get the long option name and its visible aliases, if any
sourcepub fn get_possible_values(&self) -> Vec<PossibleValue>
pub fn get_possible_values(&self) -> Vec<PossibleValue>
Get the names of possible values for this argument. Only useful for user facing applications, such as building help messages or man files
Examples found in repository?
4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610
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.get_long_help().is_some()
|| v.is_hide_long_help_set()
|| v.is_hide_short_help_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)
}
More examples
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
fn help(
&mut self,
arg: Option<&Arg>,
about: &StyledStr,
spec_vals: &str,
next_line_help: bool,
longest: usize,
) {
debug!("HelpTemplate::help");
// Is help on next line, if so then indent
if next_line_help {
debug!("HelpTemplate::help: Next Line...{:?}", next_line_help);
self.none("\n");
self.none(TAB);
self.none(NEXT_LINE_INDENT);
}
let spaces = if next_line_help {
TAB.len() + NEXT_LINE_INDENT.len()
} else if let Some(true) = arg.map(|a| a.is_positional()) {
longest + TAB_WIDTH * 2
} else {
longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4
};
let trailing_indent = spaces; // Don't indent any further than the first line is indented
let trailing_indent = self.get_spaces(trailing_indent);
let mut help = about.clone();
replace_newline_var(&mut help);
if !spec_vals.is_empty() {
if !help.is_empty() {
let sep = if self.use_long && arg.is_some() {
"\n\n"
} else {
" "
};
help.none(sep);
}
help.none(spec_vals);
}
let avail_chars = self.term_w.saturating_sub(spaces);
debug!(
"HelpTemplate::help: help_width={}, spaces={}, avail={}",
spaces,
help.display_width(),
avail_chars
);
help.wrap(avail_chars);
help.indent("", &trailing_indent);
let help_is_empty = help.is_empty();
self.writer.extend(help.into_iter());
if let Some(arg) = arg {
const DASH_SPACE: usize = "- ".len();
const COLON_SPACE: usize = ": ".len();
let possible_vals = arg.get_possible_values();
if self.use_long
&& !arg.is_hide_possible_values_set()
&& possible_vals.iter().any(PossibleValue::should_show_help)
{
debug!(
"HelpTemplate::help: Found possible vals...{:?}",
possible_vals
);
if !help_is_empty {
self.none("\n\n");
self.spaces(spaces);
}
self.none("Possible values:");
let longest = possible_vals
.iter()
.filter_map(|f| f.get_visible_quoted_name().map(|name| display_width(&name)))
.max()
.expect("Only called with possible value");
let help_longest = possible_vals
.iter()
.filter_map(|f| f.get_visible_help().map(|h| h.display_width()))
.max()
.expect("Only called with possible value with help");
// should new line
let taken = longest + spaces + DASH_SPACE;
let possible_value_new_line =
self.term_w >= taken && self.term_w < taken + COLON_SPACE + help_longest;
let spaces = spaces + TAB_WIDTH - DASH_SPACE;
let trailing_indent = if possible_value_new_line {
spaces + DASH_SPACE
} else {
spaces + longest + DASH_SPACE + COLON_SPACE
};
let trailing_indent = self.get_spaces(trailing_indent);
for pv in possible_vals.iter().filter(|pv| !pv.is_hide_set()) {
self.none("\n");
self.spaces(spaces);
self.none("- ");
self.literal(pv.get_name());
if let Some(help) = pv.get_help() {
debug!("HelpTemplate::help: Possible Value help");
if possible_value_new_line {
self.none(":\n");
self.spaces(trailing_indent.len());
} else {
self.none(": ");
// To align help messages
self.spaces(longest - display_width(pv.get_name()));
}
let avail_chars = if self.term_w > trailing_indent.len() {
self.term_w - trailing_indent.len()
} else {
usize::MAX
};
let mut help = help.clone();
replace_newline_var(&mut help);
help.wrap(avail_chars);
help.indent("", &trailing_indent);
self.writer.extend(help.into_iter());
}
}
}
}
}
/// Will use next line help on writing args.
fn will_args_wrap(&self, args: &[&Arg], longest: usize) -> bool {
args.iter()
.filter(|arg| should_show_arg(self.use_long, arg))
.any(|arg| {
let spec_vals = &self.spec_vals(arg);
self.arg_next_line_help(arg, spec_vals, longest)
})
}
fn arg_next_line_help(&self, arg: &Arg, spec_vals: &str, longest: usize) -> bool {
if self.next_line_help || arg.is_next_line_help_set() || self.use_long {
// setting_next_line
true
} else {
// force_next_line
let h = arg.get_help().unwrap_or_default();
let h_w = h.display_width() + display_width(spec_vals);
let taken = if arg.is_positional() {
longest + TAB_WIDTH * 2
} else {
longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4
};
self.term_w >= taken
&& (taken as f32 / self.term_w as f32) > 0.40
&& h_w > (self.term_w - taken)
}
}
fn spec_vals(&self, a: &Arg) -> String {
debug!("HelpTemplate::spec_vals: a={}", a);
let mut spec_vals = Vec::new();
#[cfg(feature = "env")]
if let Some(ref env) = a.env {
if !a.is_hide_env_set() {
debug!(
"HelpTemplate::spec_vals: Found environment variable...[{:?}:{:?}]",
env.0, env.1
);
let env_val = if !a.is_hide_env_values_set() {
format!(
"={}",
env.1
.as_ref()
.map(|s| s.to_string_lossy())
.unwrap_or_default()
)
} else {
Default::default()
};
let env_info = format!("[env: {}{}]", env.0.to_string_lossy(), env_val);
spec_vals.push(env_info);
}
}
if a.is_takes_value_set() && !a.is_hide_default_value_set() && !a.default_vals.is_empty() {
debug!(
"HelpTemplate::spec_vals: Found default value...[{:?}]",
a.default_vals
);
let pvs = a
.default_vals
.iter()
.map(|pvs| pvs.to_string_lossy())
.map(|pvs| {
if pvs.contains(char::is_whitespace) {
Cow::from(format!("{:?}", pvs))
} else {
pvs
}
})
.collect::<Vec<_>>()
.join(" ");
spec_vals.push(format!("[default: {}]", pvs));
}
let als = a
.aliases
.iter()
.filter(|&als| als.1) // visible
.map(|als| als.0.as_str()) // name
.collect::<Vec<_>>()
.join(", ");
if !als.is_empty() {
debug!("HelpTemplate::spec_vals: Found aliases...{:?}", a.aliases);
spec_vals.push(format!("[aliases: {}]", als));
}
let als = a
.short_aliases
.iter()
.filter(|&als| als.1) // visible
.map(|&als| als.0.to_string()) // name
.collect::<Vec<_>>()
.join(", ");
if !als.is_empty() {
debug!(
"HelpTemplate::spec_vals: Found short aliases...{:?}",
a.short_aliases
);
spec_vals.push(format!("[short aliases: {}]", als));
}
let possible_vals = a.get_possible_values();
if !(a.is_hide_possible_values_set()
|| possible_vals.is_empty()
|| self.use_long && possible_vals.iter().any(PossibleValue::should_show_help))
{
debug!(
"HelpTemplate::spec_vals: Found possible vals...{:?}",
possible_vals
);
let pvs = possible_vals
.iter()
.filter_map(PossibleValue::get_visible_quoted_name)
.collect::<Vec<_>>()
.join(", ");
spec_vals.push(format!("[possible values: {}]", pvs));
}
let connector = if self.use_long { "\n" } else { " " };
spec_vals.join(connector)
}
sourcepub fn get_value_names(&self) -> Option<&[Str]>
pub fn get_value_names(&self) -> Option<&[Str]>
Get the names of values for this argument.
Examples found in repository?
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
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, it must take a value{}",
arg.get_id(),
if arg.get_id() == Id::HELP {
<