Struct Command
struct Command { ... }
Build a command-line interface.
This includes defining arguments, subcommands, parser behavior, and help output.
Once all configuration is complete,
the Command::get_matches family of methods starts the runtime-parsing
process. These methods then return information about the user supplied
arguments (or lack thereof).
When deriving a [Parser][crate::Parser], you can use
[CommandFactory::command][crate::CommandFactory::command] to access the
Command.
- [Basic API][crate::Command#basic-api]
- [Application-wide Settings][crate::Command#application-wide-settings]
- [Command-specific Settings][crate::Command#command-specific-settings]
- [Subcommand-specific Settings][crate::Command#subcommand-specific-settings]
- [Reflection][crate::Command#reflection]
Examples
# use clap_builder as clap;
# use clap::{Command, Arg};
let m = Command::new("My Program")
.author("Me, me@mail.com")
.version("1.0.2")
.about("Explains in brief what the program does")
.arg(
Arg::new("in_file")
)
.after_help("Longer explanation to appear after the options when \
displaying the help information from --help or -h")
.get_matches();
// Your program logic starts here...
Implementations
impl Command
fn new<impl Into<Str>: Into<Str>>(name: impl Into<Str>) -> SelfCreates a new instance of an
Command.It is common, but not required, to use binary name as the
name. This name will only be displayed to the user when they request to print version or help and usage information.See also
command!andcrate_name!.Examples
# use clap_builder as clap; # use Command; new # ;fn arg<impl Into<Arg>: Into<Arg>>(self: Self, a: impl Into<Arg>) -> SelfAdds an argument to the list of valid possibilities.
Examples
# use clap_builder as clap; # use ; new // Adding a single "flag" argument with a short and help text, using Arg::new() .arg // Adding a single "option" argument with a short, a long, and help text using the less // verbose Arg::from() .arg # ;fn args<impl Into<Arg>: Into<Arg>, impl IntoIterator<Item = impl Into<Arg>>: IntoIterator<Item = impl Into<Arg>>>(self: Self, args: impl IntoIterator<Item = impl Into<Arg>>) -> SelfAdds multiple arguments to the list of valid possibilities.
Examples
# use clap_builder as clap; # use ; new .args # ;fn mut_arg<F, impl AsRef<str>: AsRef<str>>(self: Self, arg_id: impl AsRef<str>, f: F) -> Self where F: FnOnce(Arg) -> ArgAllows one to mutate an
Argafter it's been added to aCommand.Panics
If the argument is undefined
Examples
# use clap_builder as clap; # use ; let mut cmd = new .arg .mut_arg; let res = cmd.try_get_matches_from_mut; // Since we changed `bar`'s short to "B" this should err as there // is no `-b` anymore, only `-B` assert!; let res = cmd.try_get_matches_from_mut; assert!;fn mut_args<F>(self: Self, f: F) -> Self where F: FnMut(Arg) -> ArgAllows one to mutate all
Args after they've been added to aCommand.This does not affect the built-in
--helpor--versionarguments.Examples
# use clap_builder as clap; # use clap::{Command, Arg, ArgAction}; let mut cmd = Command::new("foo") .arg(Arg::new("bar") .long("bar") .action(ArgAction::SetTrue)) .arg(Arg::new("baz") .long("baz") .action(ArgAction::SetTrue)) .mut_args(|a| { if let Some(l) = a.get_long().map(|l| format!("prefix-{l}")) { a.long(l) } else { a } }); let res = cmd.try_get_matches_from_mut(vec!["foo", "--bar"]); // Since we changed `bar`'s long to "prefix-bar" this should err as there // is no `--bar` anymore, only `--prefix-bar`. assert!(res.is_err()); let res = cmd.try_get_matches_from_mut(vec!["foo", "--prefix-bar"]); assert!(res.is_ok());fn mut_group<F, impl AsRef<str>: AsRef<str>>(self: Self, arg_id: impl AsRef<str>, f: F) -> Self where F: FnOnce(ArgGroup) -> ArgGroupAllows one to mutate an
ArgGroupafter it's been added to aCommand.Panics
If the argument is undefined
Examples
# use clap_builder as clap; # use ; new .arg .arg .arg .arg .group .mut_group;fn mut_subcommand<F, impl AsRef<str>: AsRef<str>>(self: Self, name: impl AsRef<str>, f: F) -> Self where F: FnOnce(Self) -> SelfAllows one to mutate a
Commandafter it's been added as a subcommand.This can be useful for modifying auto-generated arguments of nested subcommands with
Command::mut_arg.Panics
If the subcommand is undefined
Examples
# use clap_builder as clap; # use Command; let mut cmd = new .subcommand .mut_subcommand; let res = cmd.try_get_matches_from_mut; // Since we disabled the help flag on the "bar" subcommand, this should err. assert!; let res = cmd.try_get_matches_from_mut; assert!;fn group<impl Into<ArgGroup>: Into<ArgGroup>>(self: Self, group: impl Into<ArgGroup>) -> SelfAdds an
ArgGroupto the application.ArgGroups are a family of related arguments. By placing them in a logical group, you can build easier requirement and exclusion rules.Example use cases:
- Make an entire
ArgGrouprequired, meaning that one (and only one) argument from that group must be present at runtime. - Name an
ArgGroupas a conflict to another argument. Meaning any of the arguments that belong to that group will cause a failure if present with the conflicting argument. - Ensure exclusion between arguments.
- Extract a value from a group instead of determining exactly which argument was used.
Examples
The following example demonstrates using an
ArgGroupto ensure that one, and only one, of the arguments from the specified group is present at runtime.# use clap_builder as clap; # use ; new .arg .arg .arg .arg .group # ;- Make an entire
fn groups<impl Into<ArgGroup>: Into<ArgGroup>, impl IntoIterator<Item = impl Into<ArgGroup>>: IntoIterator<Item = impl Into<ArgGroup>>>(self: Self, groups: impl IntoIterator<Item = impl Into<ArgGroup>>) -> SelfAdds multiple
ArgGroups to theCommandat once.Examples
# use clap_builder as clap; # use ; new .arg .arg .arg .arg .arg .arg .groups # ;fn subcommand<impl Into<Command>: Into<Command>>(self: Self, subcmd: impl Into<Command>) -> SelfAdds a subcommand to the list of valid possibilities.
Subcommands are effectively sub-
Commands, because they can contain their own arguments, subcommands, version, usage, etc. They also function just likeCommands, in that they get their own auto generated help, version, and usage.A subcommand's
Command::namewill be used for:- The argument the user passes in
- Programmatically looking up the subcommand
Examples
# use clap_builder as clap; # use ; new .subcommand # ;fn subcommands<impl Into<Self>: Into<Self>, impl IntoIterator<Item = impl Into<Self>>: IntoIterator<Item = impl Into<Self>>>(self: Self, subcmds: impl IntoIterator<Item = impl Into<Self>>) -> SelfAdds multiple subcommands to the list of valid possibilities.
Examples
# use clap_builder as clap; # use ; # new .subcommands # ;fn defer(self: Self, deferred: fn(_: Command) -> Command) -> SelfDelay initialization for parts of the
CommandThis is useful for large applications to delay definitions of subcommands until they are being invoked.
Examples
# use clap_builder as clap; # use ; new .subcommand # ;fn debug_assert(self: Self)Catch problems earlier in the development cycle.
Most error states are handled as asserts under the assumption they are programming mistake and not something to handle at runtime. Rather than relying on tests (manual or automated) that exhaustively test your CLI to ensure the asserts are evaluated, this will run those asserts in a way convenient for running as a test.
Note: This will not help with asserts in
ArgMatches, those will need exhaustive testing of your CLI.Examples
# use clap_builder as clap; # use ;fn error<impl fmt::Display: fmt::Display>(self: &mut Self, kind: ErrorKind, message: impl fmt::Display) -> ErrorCustom error message for post-parsing validation
Examples
# use clap_builder as clap; # use ; let mut cmd = new; let err = cmd.error;fn get_matches(self: Self) -> ArgMatchesParse
env::args_os, [exiting][Error::exit] on failure.Panics
If contradictory arguments or settings exist (debug builds).
Examples
# use clap_builder as clap; # use clap::{Command, Arg}; let matches = Command::new("myprog") // Args and options go here... .get_matches();fn get_matches_mut(self: &mut Self) -> ArgMatchesParse
env::args_os, [exiting][Error::exit] on failure.Like
Command::get_matchesbut doesn't consume theCommand.Panics
If contradictory arguments or settings exist (debug builds).
Examples
# use clap_builder as clap; # use clap::{Command, Arg}; let mut cmd = Command::new("myprog") // Args and options go here... ; let matches = cmd.get_matches_mut();fn try_get_matches(self: Self) -> ClapResult<ArgMatches>Parse
env::args_os, returning aclap::Resulton failure.NOTE: This method WILL NOT exit when
--helpor--version(or short versions) are used. It will return aclap::Error, where thekindis aErrorKind::DisplayHelporErrorKind::DisplayVersionrespectively. You must callError::exitor perform astd::process::exit.Panics
If contradictory arguments or settings exist (debug builds).
Examples
# use clap_builder as clap; # use clap::{Command, Arg}; let matches = Command::new("myprog") // Args and options go here... .try_get_matches() .unwrap_or_else(|e| e.exit());fn get_matches_from<I, T>(self: Self, itr: I) -> ArgMatches where I: IntoIterator<Item = T>, T: Into<OsString> + CloneParse the specified arguments, [exiting][Error::exit] on failure.
NOTE: The first argument will be parsed as the binary name unless
Command::no_binary_nameis used.Panics
If contradictory arguments or settings exist (debug builds).
Examples
# use clap_builder as clap; # use clap::{Command, Arg}; let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; let matches = Command::new("myprog") // Args and options go here... .get_matches_from(arg_vec);fn try_get_matches_from<I, T>(self: Self, itr: I) -> ClapResult<ArgMatches> where I: IntoIterator<Item = T>, T: Into<OsString> + CloneParse the specified arguments, returning a
clap::Resulton failure.NOTE: This method WILL NOT exit when
--helpor--version(or short versions) are used. It will return aclap::Error, where thekindis aErrorKind::DisplayHelporErrorKind::DisplayVersionrespectively. You must callError::exitor perform astd::process::exityourself.NOTE: The first argument will be parsed as the binary name unless
Command::no_binary_nameis used.Panics
If contradictory arguments or settings exist (debug builds).
Examples
# use clap_builder as clap; # use clap::{Command, Arg}; let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; let matches = Command::new("myprog") // Args and options go here... .try_get_matches_from(arg_vec) .unwrap_or_else(|e| e.exit());fn try_get_matches_from_mut<I, T>(self: &mut Self, itr: I) -> ClapResult<ArgMatches> where I: IntoIterator<Item = T>, T: Into<OsString> + CloneParse the specified arguments, returning a
clap::Resulton failure.Like
Command::try_get_matches_frombut doesn't consume theCommand.NOTE: This method WILL NOT exit when
--helpor--version(or short versions) are used. It will return aclap::Error, where thekindis aErrorKind::DisplayHelporErrorKind::DisplayVersionrespectively. You must callError::exitor perform astd::process::exityourself.NOTE: The first argument will be parsed as the binary name unless
Command::no_binary_nameis used.Panics
If contradictory arguments or settings exist (debug builds).
Examples
# use clap_builder as clap; # use clap::{Command, Arg}; let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; let mut cmd = Command::new("myprog"); // Args and options go here... let matches = cmd.try_get_matches_from_mut(arg_vec) .unwrap_or_else(|e| e.exit());fn print_help(self: &mut Self) -> io::Result<()>Prints the short help message (
-h) toio::stdout().See also
Command::print_long_help.Examples
# use clap_builder as clap; # use Command; let mut cmd = new; cmd.print_help;fn print_long_help(self: &mut Self) -> io::Result<()>Prints the long help message (
--help) toio::stdout().See also
Command::print_help.Examples
# use clap_builder as clap; # use Command; let mut cmd = new; cmd.print_long_help;fn render_help(self: &mut Self) -> StyledStrRender the short help message (
-h) to aStyledStrSee also
Command::render_long_help.Examples
# use clap_builder as clap; # use Command; use io; let mut cmd = new; let mut out = stdout; let help = cmd.render_help; println!;fn render_long_help(self: &mut Self) -> StyledStrRender the long help message (
--help) to aStyledStr.See also
Command::render_help.Examples
# use clap_builder as clap; # use Command; use io; let mut cmd = new; let mut out = stdout; let help = cmd.render_long_help; println!;fn render_version(self: &Self) -> StringVersion message rendered as if the user ran
-V.See also
Command::render_long_version.Coloring
This function does not try to color the message nor it inserts any ANSI escape codes.
Examples
# use clap_builder as clap; # use Command; use io; let cmd = new; println!;fn render_long_version(self: &Self) -> StringVersion message rendered as if the user ran
--version.See also
Command::render_version.Coloring
This function does not try to color the message nor it inserts any ANSI escape codes.
Examples
# use clap_builder as clap; # use Command; use io; let cmd = new; println!;fn render_usage(self: &mut Self) -> StyledStrUsage statement
Examples
# use clap_builder as clap; # use Command; use io; let mut cmd = new; println!;
impl Command
fn short_flag<impl IntoResettable<char>: IntoResettable<char>>(self: Self, short: impl IntoResettable<char>) -> SelfSets the short version of the subcommand flag without the preceding
-.Allows the subcommand to be used as if it were an
Arg::short.Examples
# use clap_builder as clap; # use ; let matches = new .subcommand .get_matches_from; assert_eq!; let sync_matches = matches.subcommand_matches.unwrap; assert!;fn long_flag<impl Into<Str>: Into<Str>>(self: Self, long: impl Into<Str>) -> SelfSets the long version of the subcommand flag without the preceding
--.Allows the subcommand to be used as if it were an
Arg::long.NOTE: Any leading
-characters will be stripped.Examples
To set
long_flaguse a word containing valid UTF-8 codepoints. If you supply a double leading--such as--syncthey will be stripped. Hyphens in the middle of the word; however, will not be stripped (i.e.sync-fileis allowed).# use clap_builder as clap; # use ; let matches = new .subcommand .get_matches_from; assert_eq!; let sync_matches = matches.subcommand_matches.unwrap; assert!;fn alias<impl IntoResettable<Str>: IntoResettable<Str>>(self: Self, name: impl IntoResettable<Str>) -> SelfSets a hidden alias to this subcommand.
This allows the subcommand to be accessed via either the original name, or this given alias. This is more efficient and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all aliased variants.
NOTE: Aliases defined with this method are hidden from the help message. If you're looking for aliases that will be displayed in the help message, see
Command::visible_alias.NOTE: When using aliases and checking for the existence of a particular subcommand within an
ArgMatchesstruct, one only needs to search for the original name and not all aliases.Examples
# use clap_builder as clap; # use ; let m = new .subcommand .get_matches_from; assert_eq!;fn short_flag_alias<impl IntoResettable<char>: IntoResettable<char>>(self: Self, name: impl IntoResettable<char>) -> SelfAdd an alias, which functions as "hidden" short flag subcommand
This will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.
Examples
# use clap_builder as clap; # use ; let m = new .subcommand .get_matches_from; assert_eq!;fn long_flag_alias<impl IntoResettable<Str>: IntoResettable<Str>>(self: Self, name: impl IntoResettable<Str>) -> SelfAdd an alias, which functions as a "hidden" long flag subcommand.
This will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.
Examples
# use clap_builder as clap; # use ; let m = new .subcommand .get_matches_from; assert_eq!;fn aliases<impl Into<Str>: Into<Str>, impl IntoIterator<Item = impl Into<Str>>: IntoIterator<Item = impl Into<Str>>>(self: Self, names: impl IntoIterator<Item = impl Into<Str>>) -> SelfSets multiple hidden aliases to this subcommand.
This allows the subcommand to be accessed via either the original name or any of the given aliases. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command and not all aliased variants.
NOTE: Aliases defined with this method are hidden from the help message. If looking for aliases that will be displayed in the help message, see
Command::visible_aliases.NOTE: When using aliases and checking for the existence of a particular subcommand within an
ArgMatchesstruct, one only needs to search for the original name and not all aliases.Examples
# use clap_builder as clap; # use ; let m = new .subcommand .arg .get_matches_from; assert_eq!;fn short_flag_aliases<impl IntoIterator<Item = char>: IntoIterator<Item = char>>(self: Self, names: impl IntoIterator<Item = char>) -> SelfAdd aliases, which function as "hidden" short flag subcommands.
These will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.
Examples
# use clap_builder as clap; # use ; let m = new .subcommand .arg .get_matches_from; assert_eq!;fn long_flag_aliases<impl Into<Str>: Into<Str>, impl IntoIterator<Item = impl Into<Str>>: IntoIterator<Item = impl Into<Str>>>(self: Self, names: impl IntoIterator<Item = impl Into<Str>>) -> SelfAdd aliases, which function as "hidden" long flag subcommands.
These will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.
Examples
# use clap_builder as clap; # use ; let m = new .subcommand .arg .get_matches_from; assert_eq!;fn visible_alias<impl IntoResettable<Str>: IntoResettable<Str>>(self: Self, name: impl IntoResettable<Str>) -> SelfSets a visible alias to this subcommand.
This allows the subcommand to be accessed via either the original name or the given alias. This is more efficient and easier than creating hidden subcommands as one only needs to check for the existence of this command and not all aliased variants.
NOTE: The alias defined with this method is visible from the help message and displayed as if it were just another regular subcommand. If looking for an alias that will not be displayed in the help message, see
Command::alias.NOTE: When using aliases and checking for the existence of a particular subcommand within an
ArgMatchesstruct, one only needs to search for the original name and not all aliases.Examples
# use clap_builder as clap; # use ; let m = new .subcommand .get_matches_from; assert_eq!;fn visible_short_flag_alias<impl IntoResettable<char>: IntoResettable<char>>(self: Self, name: impl IntoResettable<char>) -> SelfAdd an alias, which functions as "visible" short flag subcommand
This will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.
See also
Command::short_flag_alias.Examples
# use clap_builder as clap; # use ; let m = new .subcommand .get_matches_from; assert_eq!;fn visible_long_flag_alias<impl IntoResettable<Str>: IntoResettable<Str>>(self: Self, name: impl IntoResettable<Str>) -> SelfAdd an alias, which functions as a "visible" long flag subcommand.
This will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.
See also
Command::long_flag_alias.Examples
# use clap_builder as clap; # use ; let m = new .subcommand .get_matches_from; assert_eq!;fn visible_aliases<impl Into<Str>: Into<Str>, impl IntoIterator<Item = impl Into<Str>>: IntoIterator<Item = impl Into<Str>>>(self: Self, names: impl IntoIterator<Item = impl Into<Str>>) -> SelfSets multiple visible aliases to this subcommand.
This allows the subcommand to be accessed via either the original name or any of the given aliases. This is more efficient and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command and not all aliased variants.
NOTE: The alias defined with this method is visible from the help message and displayed as if it were just another regular subcommand. If looking for an alias that will not be displayed in the help message, see
Command::alias.NOTE: When using aliases, and checking for the existence of a particular subcommand within an
ArgMatchesstruct, one only needs to search for the original name and not all aliases.Examples
# use clap_builder as clap; # use ; let m = new .subcommand .get_matches_from; assert_eq!;fn visible_short_flag_aliases<impl IntoIterator<Item = char>: IntoIterator<Item = char>>(self: Self, names: impl IntoIterator<Item = char>) -> SelfAdd aliases, which function as visible short flag subcommands.
See
Command::short_flag_aliases.Examples
# use clap_builder as clap; # use ; let m = new .subcommand .get_matches_from; assert_eq!;fn visible_long_flag_aliases<impl Into<Str>: Into<Str>, impl IntoIterator<Item = impl Into<Str>>: IntoIterator<Item = impl Into<Str>>>(self: Self, names: impl IntoIterator<Item = impl Into<Str>>) -> SelfAdd aliases, which function as visible long flag subcommands.
See
Command::long_flag_aliases.Examples
# use clap_builder as clap; # use ; let m = new .subcommand .get_matches_from; assert_eq!;fn display_order<impl IntoResettable<usize>: IntoResettable<usize>>(self: Self, ord: impl IntoResettable<usize>) -> SelfSet the placement of this subcommand within the help.
Subcommands with a lower value will be displayed first in the help message. Those with the same display order will be sorted.
Commands are automatically assigned a display order based on the order they are added to their parentCommand. Overriding this is helpful when the order commands are added in isn't the same as the display order, whether in one-off cases or to automatically sort commands.Examples
#The above example displays the following help message
cust-ord Usage: cust-ord [OPTIONS] Commands: alpha I should be first! beta Some help and text help Print help for the subcommand(s) Options: -h, --help Print help -V, --version Print versionfn hide(self: Self, yes: bool) -> SelfSpecifies that this
subcommandshould be hidden from help messagesExamples
# use clap_builder as clap; # use ; new .subcommand # ;fn subcommand_required(self: Self, yes: bool) -> SelfIf no
subcommandis present at runtime, error and exit gracefully.Examples
# use clap_builder as clap; # use ; let err = new .subcommand_required .subcommand .try_get_matches_from; assert!; assert_eq!; # ;fn allow_external_subcommands(self: Self, yes: bool) -> SelfAssume unexpected positional arguments are a
subcommand.Arguments will be stored in the
""argument in theArgMatchesNOTE: Use this setting with caution, as a truly unexpected argument (i.e. one that is NOT an external subcommand) will not cause an error and instead be treated as a potential subcommand. One should check for such cases manually and inform the user appropriately.
NOTE: A built-in subcommand will be parsed as an external subcommand when escaped with
--.Examples
# use clap_builder as clap; # use OsString; # use Command; // Assume there is an external subcommand named "subcmd" let m = new .allow_external_subcommands .get_matches_from; // All trailing arguments will be stored under the subcommand's sub-matches using an empty // string argument name match m.subcommandfn external_subcommand_value_parser<impl IntoResettable<super::ValueParser>: IntoResettable<super::ValueParser>>(self: Self, parser: impl IntoResettable<super::ValueParser>) -> SelfSpecifies how to parse external subcommand arguments.
The default parser is for
OsString. This can be used to switch it toStringor another type.NOTE: Setting this requires
Command::allow_external_subcommandsExamples
## use clap_builder as clap; # use Command; # use value_parser; // Assume there is an external subcommand named "subcmd" let m = new .external_subcommand_value_parser .get_matches_from; // All trailing arguments will be stored under the subcommand's sub-matches using an empty // string argument name match m.subcommandfn args_conflicts_with_subcommands(self: Self, yes: bool) -> SelfSpecifies that use of an argument prevents the use of
subcommands.By default
clapallows arguments between subcommands such as<cmd> [cmd_args] <subcmd> [subcmd_args] <subsubcmd> [subsubcmd_args].This setting disables that functionality and says that arguments can only follow the final subcommand. For instance using this setting makes only the following invocations possible:
<cmd> <subcmd> <subsubcmd> [subsubcmd_args]<cmd> <subcmd> [subcmd_args]<cmd> [cmd_args]
Examples
# use clap_builder as clap; # use Command; new .args_conflicts_with_subcommands;fn subcommand_precedence_over_arg(self: Self, yes: bool) -> SelfPrevent subcommands from being consumed as an arguments value.
By default, if an option taking multiple values is followed by a subcommand, the subcommand will be parsed as another value.
cmd --foo val1 val2 subcommand --------- ---------- values another valueThis setting instructs the parser to stop when encountering a subcommand instead of greedily consuming arguments.
cmd --foo val1 val2 subcommand --------- ---------- values subcommandExamples
# use clap_builder as clap; # use ; let cmd = new.subcommand.arg; let matches = cmd .clone .try_get_matches_from .unwrap; assert_eq!; assert!; let matches = cmd .subcommand_precedence_over_arg .try_get_matches_from .unwrap; assert_eq!; assert!;fn subcommand_negates_reqs(self: Self, yes: bool) -> SelfAllows
subcommandsto override all requirements of the parent command.For example, if you had a subcommand or top level application with a required argument that is only required as long as there is no subcommand present, using this setting would allow you to set those arguments to
Arg::required(true)and yet receive no error so long as the user uses a valid subcommand instead.NOTE: This defaults to false (using subcommand does not negate requirements)
Examples
This first example shows that it is an error to not use a required argument
# use clap_builder as clap; # use ; let err = new .subcommand_negates_reqs .arg .subcommand .try_get_matches_from; assert!; assert_eq!; # ;This next example shows that it is no longer error to not use a required argument if a valid subcommand is used.
# use clap_builder as clap; # use ; let noerr = new .subcommand_negates_reqs .arg .subcommand .try_get_matches_from; assert!; # ;fn multicall(self: Self, yes: bool) -> SelfMultiple-personality program dispatched on the binary name (
argv[0])A "multicall" executable is a single executable that contains a variety of applets, and decides which applet to run based on the name of the file. The executable can be called from different names by creating hard links or symbolic links to it.
This is desirable for:
- Easy distribution, a single binary that can install hardlinks to access the different personalities.
- Minimal binary size by sharing common code (e.g. standard library, clap)
- Custom shells or REPLs where there isn't a single top-level command
Setting
multicallwill causeargv[0]to be stripped to the base name and parsed as the first argument, as if [Command::no_binary_name][Command::no_binary_name] was set.- Help and errors to report subcommands as if they were the top-level command
When the subcommand is not present, there are several strategies you may employ, depending on your needs:
- Let the error percolate up normally
- Print a specialized error message using the
[
Error::context][crate::Error::context] - Print the [help][Command::write_help] but this might be ambiguous
- Disable
multicalland re-parse it - Disable
multicalland re-parse it with a specific subcommand
When detecting the error condition, the
ErrorKindisn't sufficient as a sub-subcommand might report the same error. Enable [allow_external_subcommands][Command::allow_external_subcommands] if you want to specifically get the unrecognized binary name.NOTE: Multicall can't be used with
no_binary_namesince they interpret the command name in incompatible ways.NOTE: The multicall command cannot have arguments.
NOTE: Applets are slightly semantically different from subcommands, so it's recommended to use
Command::subcommand_help_headingandCommand::subcommand_value_nameto change the descriptive text as above.Examples
hostnameis an example of a multicall executable. Bothhostnameanddnsdomainnameare provided by the same executable and which behaviour to use is based on the executable file name.This is desirable when the executable has a primary purpose but there is related functionality that would be convenient to provide and implement it to be in the same executable.
The name of the cmd is essentially unused and may be the same as the name of a subcommand.
The names of the immediate subcommands of the Command are matched against the basename of the first argument, which is conventionally the path of the executable.
This does not allow the subcommand to be passed as the first non-path argument.
# use clap_builder as clap; # use ; let mut cmd = new .multicall .subcommand .subcommand; let m = cmd.try_get_matches_from_mut; assert!; assert_eq!; let m = cmd.get_matches_from; assert_eq!;Busybox is another common example of a multicall executable with a subcommmand for each applet that can be run directly, e.g. with the
catapplet being run by runningbusybox cat, or withcatas a link to thebusyboxbinary.This is desirable when the launcher program has additional options or it is useful to run the applet without installing a symlink e.g. to test the applet without installing it or there may already be a command of that name installed.
To make an applet usable as both a multicall link and a subcommand the subcommands must be defined both in the top-level Command and as subcommands of the "main" applet.
# use clap_builder as clap; # use Command; let mut cmd = new .multicall .subcommand .subcommands; // When called from the executable's canonical name // its applets can be matched as subcommands. let m = cmd.try_get_matches_from_mut.unwrap; assert_eq!; assert_eq!; // When called from a link named after an applet that applet is matched. let m = cmd.get_matches_from; assert_eq!;fn subcommand_value_name<impl IntoResettable<Str>: IntoResettable<Str>>(self: Self, value_name: impl IntoResettable<Str>) -> SelfSets the value name used for subcommands when printing usage and help.
By default, this is "COMMAND".
See also
Command::subcommand_help_headingExamples
# use clap_builder as clap; # use ; new .subcommand .print_help # ;will produce
myprog Usage: myprog [COMMAND] Commands: help Print this message or the help of the given subcommand(s) sub1 Options: -h, --help Print help -V, --version Print versionbut usage of
subcommand_value_name# use clap_builder as clap; # use ; new .subcommand .subcommand_value_name .print_help # ;will produce
myprog Usage: myprog [THING] Commands: help Print this message or the help of the given subcommand(s) sub1 Options: -h, --help Print help -V, --version Print versionfn subcommand_help_heading<impl IntoResettable<Str>: IntoResettable<Str>>(self: Self, heading: impl IntoResettable<Str>) -> SelfSets the help heading used for subcommands when printing usage and help.
By default, this is "Commands".
See also
Command::subcommand_value_nameExamples
# use clap_builder as clap; # use ; new .subcommand .print_help # ;will produce
myprog Usage: myprog [COMMAND] Commands: help Print this message or the help of the given subcommand(s) sub1 Options: -h, --help Print help -V, --version Print versionbut usage of
subcommand_help_heading# use clap_builder as clap; # use ; new .subcommand .subcommand_help_heading .print_help # ;will produce
myprog Usage: myprog [COMMAND] Things: help Print this message or the help of the given subcommand(s) sub1 Options: -h, --help Print help -V, --version Print version
impl Command
fn name<impl Into<Str>: Into<Str>>(self: Self, name: impl Into<Str>) -> Self(Re)Sets the program's name.
See
Command::newfor more details.Examples
let cmd = clap::command!() .name("foo"); // continued logic goes here, such as `cmd.get_matches()` etc.fn bin_name<impl IntoResettable<String>: IntoResettable<String>>(self: Self, name: impl IntoResettable<String>) -> SelfOverrides the runtime-determined name of the binary for help and error messages.
This should only be used when absolutely necessary, such as when the binary name for your application is misleading, or perhaps not how the user should invoke your program.
TIP: When building things such as third party
cargosubcommands, this setting should be used!NOTE: This does not change or set the name of the binary file on disk. It only changes what clap thinks the name is for the purposes of error or help messages.
Examples
# use clap_builder as clap; # use Command; new .bin_name # ;fn display_name<impl IntoResettable<String>: IntoResettable<String>>(self: Self, name: impl IntoResettable<String>) -> SelfOverrides the runtime-determined display name of the program for help and error messages.
Examples
# use clap_builder as clap; # use Command; new .display_name # ;fn author<impl IntoResettable<Str>: IntoResettable<Str>>(self: Self, author: impl IntoResettable<Str>) -> SelfSets the author(s) for the help message.
TIP: Use
claps convenience macro [crate_authors!] to automatically set your application's author(s) to the same thing as your crate at compile time.NOTE: A custom [
help_template][Command::help_template] is needed for author to show up.Examples
# use clap_builder as clap; # use Command; new .author # ;fn about<impl IntoResettable<StyledStr>: IntoResettable<StyledStr>>(self: Self, about: impl IntoResettable<StyledStr>) -> SelfSets the program's description for the short help (
-h).If
Command::long_aboutis not specified, this message will be displayed for--help.See also
crate_description!.Examples
# use clap_builder as clap; # use Command; new .about # ;fn long_about<impl IntoResettable<StyledStr>: IntoResettable<StyledStr>>(self: Self, long_about: impl IntoResettable<StyledStr>) -> SelfSets the program's description for the long help (
--help).If not set,
Command::aboutwill be used for long help in addition to short help (-h).NOTE: Only
Command::about(short format) is used in completion script generation in order to be concise.Examples
# use clap_builder as clap; # use Command; new .long_about # ;fn after_help<impl IntoResettable<StyledStr>: IntoResettable<StyledStr>>(self: Self, help: impl IntoResettable<StyledStr>) -> SelfFree-form help text for after auto-generated short help (
-h).This is often used to describe how to use the arguments, caveats to be noted, or license and contact information.
If
Command::after_long_helpis not specified, this message will be displayed for--help.Examples
# use clap_builder as clap; # use Command; new .after_help # ;fn after_long_help<impl IntoResettable<StyledStr>: IntoResettable<StyledStr>>(self: Self, help: impl IntoResettable<StyledStr>) -> SelfFree-form help text for after auto-generated long help (
--help).This is often used to describe how to use the arguments, caveats to be noted, or license and contact information.
If not set,
Command::after_helpwill be used for long help in addition to short help (-h).Examples
# use clap_builder as clap; # use Command; new .after_long_help # ;fn before_help<impl IntoResettable<StyledStr>: IntoResettable<StyledStr>>(self: Self, help: impl IntoResettable<StyledStr>) -> SelfFree-form help text for before auto-generated short help (
-h).This is often used for header, copyright, or license information.
If
Command::before_long_helpis not specified, this message will be displayed for--help.Examples
# use clap_builder as clap; # use Command; new .before_help # ;fn before_long_help<impl IntoResettable<StyledStr>: IntoResettable<StyledStr>>(self: Self, help: impl IntoResettable<StyledStr>) -> SelfFree-form help text for before auto-generated long help (
--help).This is often used for header, copyright, or license information.
If not set,
Command::before_helpwill be used for long help in addition to short help (-h).Examples
# use clap_builder as clap; # use Command; new .before_long_help # ;fn version<impl IntoResettable<Str>: IntoResettable<Str>>(self: Self, ver: impl IntoResettable<Str>) -> SelfSets the version for the short version (
-V) and help messages.If
Command::long_versionis not specified, this message will be displayed for--version.TIP: Use
claps convenience macro [crate_version!] to automatically set your application's version to the same thing as your crate at compile time.Examples
# use clap_builder as clap; # use Command; new .version # ;fn long_version<impl IntoResettable<Str>: IntoResettable<Str>>(self: Self, ver: impl IntoResettable<Str>) -> SelfSets the version for the long version (
--version) and help messages.If
Command::versionis not specified, this message will be displayed for-V.TIP: Use
claps convenience macro [crate_version!] to automatically set your application's version to the same thing as your crate at compile time.Examples
# use clap_builder as clap; # use Command; new .long_version # ;fn override_usage<impl IntoResettable<StyledStr>: IntoResettable<StyledStr>>(self: Self, usage: impl IntoResettable<StyledStr>) -> SelfOverrides the
clapgenerated usage string for help and error messages.NOTE: Using this setting disables
claps "context-aware" usage strings. After this setting is set, this will be the only usage string displayed to the user!NOTE: Multiple usage lines may be present in the usage argument, but some rules need to be followed to ensure the usage lines are formatted correctly by the default help formatter:
- Do not indent the first usage line.
- Indent all subsequent usage lines with seven spaces.
- The last line must not end with a newline.
Examples
# use clap_builder as clap; # use ; new .override_usage # ;Or for multiple usage lines:
# use clap_builder as clap; # use ; new .override_usage # ;fn override_help<impl IntoResettable<StyledStr>: IntoResettable<StyledStr>>(self: Self, help: impl IntoResettable<StyledStr>) -> SelfOverrides the
clapgenerated help message (both-hand--help).This should only be used when the auto-generated message does not suffice.
NOTE: This only replaces the help message for the current command, meaning if you are using subcommands, those help messages will still be auto-generated unless you specify a
Command::override_helpfor them as well.Examples
# use clap_builder as clap; # use ; new .override_help # ;fn help_template<impl IntoResettable<StyledStr>: IntoResettable<StyledStr>>(self: Self, s: impl IntoResettable<StyledStr>) -> SelfSets the help template to be used, overriding the default format.
Tags are given inside curly brackets.
Valid tags are:
{name}- Display name for the (sub-)command.{bin}- Binary name.(deprecated){version}- Version number.{author}- Author information.{author-with-newline}- Author followed by\n.{author-section}- Author preceded and followed by\n.{about}- General description (fromCommand::aboutorCommand::long_about).{about-with-newline}- About followed by\n.{about-section}- About preceded and followed by '\n'.{usage-heading}- Automatically generated usage heading.{usage}- Automatically generated or given usage string.{all-args}- Help for all arguments (options, flags, positional arguments, and subcommands) including titles.{options}- Help for options.{positionals}- Help for positional arguments.{subcommands}- Help for subcommands.{tab}- Standard tab sized used within clap{after-help}- Help fromCommand::after_helporCommand::after_long_help.{before-help}- Help fromCommand::before_helporCommand::before_long_help.
Examples
For a very brief help:
# use clap_builder as clap; # use Command; new .version .help_template # ;For showing more application context:
# use clap_builder as clap; # use Command; new .version .help_template # ;fn flatten_help(self: Self, yes: bool) -> SelfFlatten subcommand help into the current command's help
This shows a summary of subcommands within the usage and help for the current command, similar to
git stash --helpshowing information onpush,pop, etc. To see more information, a user can still pass--helpto the individual subcommands.fn next_help_heading<impl IntoResettable<Str>: IntoResettable<Str>>(self: Self, heading: impl IntoResettable<Str>) -> SelfSet the default section heading for future args.
This will be used for any arg that hasn't had
Arg::help_headingcalled.This is useful if the default
OptionsorArgumentsheadings are not specific enough for one's use case.For subcommands, see
Command::subcommand_help_headingfn next_display_order<impl IntoResettable<usize>: IntoResettable<usize>>(self: Self, disp_ord: impl IntoResettable<usize>) -> SelfChange the starting value for assigning future display orders for args.
This will be used for any arg that hasn't had
Arg::display_ordercalled.fn arg_required_else_help(self: Self, yes: bool) -> SelfExit gracefully if no arguments are present (e.g.
$ myprog).NOTE:
subcommandscount as argumentsExamples
# use clap_builder as clap; # use ; new .arg_required_else_help;fn allow_missing_positional(self: Self, yes: bool) -> SelfAllows one to implement two styles of CLIs where positionals can be used out of order.
The first example is a CLI where the second to last positional argument is optional, but the final positional argument is required. Such as
$ prog [optional] <required>where one of the two following usages is allowed:$ prog [optional] <required>$ prog <required>
This would otherwise not be allowed. This is useful when
[optional]has a default value.Note: when using this style of "missing positionals" the final positional must be required if
--will not be used to skip to the final positional argument.Note: This style also only allows a single positional argument to be "skipped" without the use of
--. To skip more than one, see the second example.The second example is when one wants to skip multiple optional positional arguments, and use of the
--operator is OK (but not required if all arguments will be specified anyways).For example, imagine a CLI which has three positional arguments
[foo] [bar] [baz]...wherebazaccepts multiple values (similar to manARGS...style training arguments).With this setting the following invocations are possible:
$ prog foo bar baz1 baz2 baz3$ prog foo -- baz1 baz2 baz3$ prog -- baz1 baz2 baz3
Examples
Style number one from above:
# use clap_builder as clap; # use ; // Assume there is an external subcommand named "subcmd" let m = new .allow_missing_positional .arg .arg .get_matches_from; assert_eq!; assert_eq!;Now the same example, but using a default value for the first optional positional argument
# use clap_builder as clap; # use ; // Assume there is an external subcommand named "subcmd" let m = new .allow_missing_positional .arg .arg .get_matches_from; assert_eq!; assert_eq!;Style number two from above:
# use clap_builder as clap; # use ; // Assume there is an external subcommand named "subcmd" let m = new .allow_missing_positional .arg .arg .arg .get_matches_from; assert_eq!; assert_eq!; assert_eq!;Now nofice if we don't specify
fooorbazbut use the--operator.# use clap_builder as clap; # use ; // Assume there is an external subcommand named "subcmd" let m = new .allow_missing_positional .arg .arg .arg .get_matches_from; assert_eq!; assert_eq!; assert_eq!;
impl Command
fn get_display_name(self: &Self) -> Option<&str>Get the name of the binary.
fn get_bin_name(self: &Self) -> Option<&str>Get the name of the binary.
fn set_bin_name<impl Into<String>: Into<String>>(self: &mut Self, name: impl Into<String>)Set binary name. Uses
&mut selfinstead ofself.fn get_name(self: &Self) -> &strGet the name of the cmd.
fn get_name_and_visible_aliases(self: &Self) -> Vec<&str>Get all known names of the cmd (i.e. primary name and visible aliases).
fn get_version(self: &Self) -> Option<&str>Get the version of the cmd.
fn get_long_version(self: &Self) -> Option<&str>Get the long version of the cmd.
fn get_display_order(self: &Self) -> usizeGet the placement within help
fn get_author(self: &Self) -> Option<&str>Get the authors of the cmd.
fn get_short_flag(self: &Self) -> Option<char>Get the short flag of the subcommand.
fn get_long_flag(self: &Self) -> Option<&str>Get the long flag of the subcommand.
fn get_about(self: &Self) -> Option<&StyledStr>Get the help message specified via
Command::about.fn get_long_about(self: &Self) -> Option<&StyledStr>Get the help message specified via
Command::long_about.fn is_flatten_help_set(self: &Self) -> boolGet the custom section heading specified via
Command::flatten_help.fn get_next_help_heading(self: &Self) -> Option<&str>Get the custom section heading specified via
Command::next_help_heading.fn get_visible_aliases(self: &Self) -> impl Iterator<Item = &str> + '_Iterate through the visible aliases for this subcommand.
fn get_visible_short_flag_aliases(self: &Self) -> impl Iterator<Item = char> + '_Iterate through the visible short aliases for this subcommand.
fn get_visible_long_flag_aliases(self: &Self) -> impl Iterator<Item = &str> + '_Iterate through the visible long aliases for this subcommand.
fn get_all_aliases(self: &Self) -> impl Iterator<Item = &str> + '_Iterate through the set of all the aliases for this subcommand, both visible and hidden.
fn get_all_short_flag_aliases(self: &Self) -> impl Iterator<Item = char> + '_Iterate through the set of all the short aliases for this subcommand, both visible and hidden.
fn get_all_long_flag_aliases(self: &Self) -> impl Iterator<Item = &str> + '_Iterate through the set of all the long aliases for this subcommand, both visible and hidden.
fn get_aliases(self: &Self) -> impl Iterator<Item = &str> + '_Iterate through the hidden aliases for this subcommand.
fn get_color(self: &Self) -> ColorChoiceShould we color the output?
fn get_styles(self: &Self) -> &StylesReturn the current
Stylesfor theCommandfn get_subcommands(self: &Self) -> impl Iterator<Item = &Command>Iterate through the set of subcommands, getting a reference to each.
fn get_subcommands_mut(self: &mut Self) -> impl Iterator<Item = &mut Command>Iterate through the set of subcommands, getting a mutable reference to each.
fn has_subcommands(self: &Self) -> boolReturns
trueif thisCommandhas subcommands.fn get_subcommand_help_heading(self: &Self) -> Option<&str>Returns the help heading for listing subcommands.
fn get_subcommand_value_name(self: &Self) -> Option<&str>Returns the subcommand value name.
fn get_before_help(self: &Self) -> Option<&StyledStr>Returns the help heading for listing subcommands.
fn get_before_long_help(self: &Self) -> Option<&StyledStr>Returns the help heading for listing subcommands.
fn get_after_help(self: &Self) -> Option<&StyledStr>Returns the help heading for listing subcommands.
fn get_after_long_help(self: &Self) -> Option<&StyledStr>Returns the help heading for listing subcommands.
fn find_subcommand<impl AsRef<std::ffi::OsStr>: AsRef<std::ffi::OsStr>>(self: &Self, name: impl AsRef<std::ffi::OsStr>) -> Option<&Command>Find subcommand such that its name or one of aliases equals
name.This does not recurse through subcommands of subcommands.
fn find_subcommand_mut<impl AsRef<std::ffi::OsStr>: AsRef<std::ffi::OsStr>>(self: &mut Self, name: impl AsRef<std::ffi::OsStr>) -> Option<&mut Command>Find subcommand such that its name or one of aliases equals
name, returning a mutable reference to the subcommand.This does not recurse through subcommands of subcommands.
fn get_groups(self: &Self) -> impl Iterator<Item = &ArgGroup>Iterate through the set of groups.
fn get_arguments(self: &Self) -> impl Iterator<Item = &Arg>Iterate through the set of arguments.
fn get_positionals(self: &Self) -> impl Iterator<Item = &Arg>Iterate through the positionals arguments.
fn get_opts(self: &Self) -> impl Iterator<Item = &Arg>Iterate through the options.
fn get_arg_conflicts_with(self: &Self, arg: &Arg) -> Vec<&Arg>Get a list of all arguments the given argument conflicts with.
If the provided argument is declared as global, the conflicts will be determined based on the propagation rules of global arguments.
Panics
If the given arg contains a conflict with an argument that is unknown to this
Command.fn is_no_binary_name_set(self: &Self) -> boolReport whether
Command::no_binary_nameis setfn is_dont_delimit_trailing_values_set(self: &Self) -> boolReport whether
Command::dont_delimit_trailing_valuesis setfn is_disable_version_flag_set(self: &Self) -> boolReport whether
Command::disable_version_flagis setfn is_propagate_version_set(self: &Self) -> boolReport whether
Command::propagate_versionis setfn is_next_line_help_set(self: &Self) -> boolReport whether
Command::next_line_helpis setfn is_disable_help_flag_set(self: &Self) -> boolReport whether
Command::disable_help_flagis setfn is_disable_help_subcommand_set(self: &Self) -> boolReport whether
Command::disable_help_subcommandis setfn is_disable_colored_help_set(self: &Self) -> boolReport whether
Command::disable_colored_helpis setfn is_arg_required_else_help_set(self: &Self) -> boolReport whether
Command::arg_required_else_helpis setfn is_allow_missing_positional_set(self: &Self) -> boolReport whether
Command::allow_missing_positionalis setfn is_hide_set(self: &Self) -> boolReport whether
Command::hideis setfn is_subcommand_required_set(self: &Self) -> boolReport whether
Command::subcommand_requiredis setfn is_allow_external_subcommands_set(self: &Self) -> boolReport whether
Command::allow_external_subcommandsis setfn get_external_subcommand_value_parser(self: &Self) -> Option<&super::ValueParser>Configured parser for values passed to an external subcommand
Example
# use clap_builder as clap; let cmd = new .external_subcommand_value_parser; let value_parser = cmd.get_external_subcommand_value_parser; println!;fn is_args_conflicts_with_subcommands_set(self: &Self) -> boolReport whether
Command::args_conflicts_with_subcommandsis setfn is_subcommand_precedence_over_arg_set(self: &Self) -> boolReport whether
Command::subcommand_precedence_over_argis setfn is_subcommand_negates_reqs_set(self: &Self) -> boolReport whether
Command::subcommand_negates_reqsis setfn is_multicall_set(self: &Self) -> boolReport whether
Command::multicallis set
impl Command
fn no_binary_name(self: Self, yes: bool) -> SelfSpecifies that the parser should not assume the first argument passed is the binary name.
This is normally the case when using a "daemon" style mode. For shells / REPLs, see [
Command::multicall][Command::multicall].Examples
# use clap_builder as clap; # use ; let m = new .no_binary_name .arg .get_matches_from; let cmds: = m..unwrap.collect; assert_eq!;fn ignore_errors(self: Self, yes: bool) -> SelfTry not to fail on parse errors, like missing option values.
NOTE: This choice is propagated to all child subcommands.
Examples
# use clap_builder as clap; # use ; let cmd = new .ignore_errors .arg .arg .arg; let r = cmd.try_get_matches_from; assert!; let m = r.unwrap; assert_eq!; assert!; assert_eq!;fn args_override_self(self: Self, yes: bool) -> SelfReplace prior occurrences of arguments rather than error
For any argument that would conflict with itself by default (e.g.
ArgAction::Set, it will now override itself.This is the equivalent to saying the
fooarg usingArg::overrides_with("foo")for all defined arguments.NOTE: This choice is propagated to all child subcommands.
fn dont_delimit_trailing_values(self: Self, yes: bool) -> SelfDisables the automatic delimiting of values after
--or whenArg::trailing_var_argwas used.NOTE: The same thing can be done manually by setting the final positional argument to
Arg::value_delimiter(None). Using this setting is safer, because it's easier to locate when making changes.NOTE: This choice is propagated to all child subcommands.
Examples
# use clap_builder as clap; # use clap::{Command, Arg}; Command::new("myprog") .dont_delimit_trailing_values(true) .get_matches();fn color(self: Self, color: ColorChoice) -> SelfSets when to color output.
To customize how the output is styled, see
Command::styles.NOTE: This choice is propagated to all child subcommands.
NOTE: Default behaviour is
ColorChoice::Auto.Examples
# use clap_builder as clap; # use clap::{Command, ColorChoice}; Command::new("myprog") .color(ColorChoice::Never) .get_matches();fn styles(self: Self, styles: Styles) -> SelfSets the
Stylesfor terminal outputNOTE: This choice is propagated to all child subcommands.
NOTE: Default behaviour is
Styles::default.Examples
# use clap_builder as clap; # use clap::{Command, ColorChoice, builder::styling}; const STYLES: styling::Styles = styling::Styles::styled() .header(styling::AnsiColor::Green.on_default().bold()) .usage(styling::AnsiColor::Green.on_default().bold()) .literal(styling::AnsiColor::Blue.on_default().bold()) .placeholder(styling::AnsiColor::Cyan.on_default()); Command::new("myprog") .styles(STYLES) .get_matches();fn term_width(self: Self, width: usize) -> SelfSets the terminal width at which to wrap help messages.
Using
0will ignore terminal widths and use source formatting.Defaults to current terminal width when
wrap_helpfeature flag is enabled. If current width cannot be determined, the default is 100.unstable-v5feature: Defaults to unbound, being subject toCommand::max_term_width.NOTE: This setting applies globally and not on a per-command basis.
NOTE: This requires the
wrap_helpfeatureExamples
# use clap_builder as clap; # use Command; new .term_width # ;fn max_term_width(self: Self, width: usize) -> SelfLimit the line length for wrapping help when using the current terminal's width.
This only applies when [
term_width][Command::term_width] is unset so that the current terminal's width will be used. SeeCommand::term_widthfor more details.Using
0will ignore this, always respectingCommand::term_width(default).unstable-v5feature: Defaults to 100.NOTE: This setting applies globally and not on a per-command basis.
NOTE: This requires the
wrap_helpfeatureExamples
# use clap_builder as clap; # use Command; new .max_term_width # ;fn disable_version_flag(self: Self, yes: bool) -> SelfDisables
-Vand--versionflag.Examples
# use clap_builder as clap; # use ; let res = new .version .disable_version_flag .try_get_matches_from; assert!; assert_eq!;You can create a custom version flag with
ArgAction::Version# use clap_builder as clap; # use ; let mut cmd = new .version // Remove the `-V` short flag .disable_version_flag .arg; let res = cmd.try_get_matches_from_mut; assert!; assert_eq!; let res = cmd.try_get_matches_from_mut; assert!; assert_eq!;fn propagate_version(self: Self, yes: bool) -> SelfSpecifies to use the version of the current command for all
subcommands.Defaults to
false; subcommands have independent version strings from their parents.NOTE: This choice is propagated to all child subcommands.
Examples
# use clap_builder as clap; # use clap::{Command, Arg}; Command::new("myprog") .version("v1.1") .propagate_version(true) .subcommand(Command::new("test")) .get_matches(); // running `$ myprog test --version` will display // "myprog-test v1.1"fn next_line_help(self: Self, yes: bool) -> SelfPlaces the help string for all arguments and subcommands on the line after them.
NOTE: This choice is propagated to all child subcommands.
Examples
# use clap_builder as clap; # use clap::{Command, Arg}; Command::new("myprog") .next_line_help(true) .get_matches();fn disable_help_flag(self: Self, yes: bool) -> SelfDisables
-hand--helpflag.NOTE: This choice is propagated to all child subcommands.
Examples
# use clap_builder as clap; # use ; let res = new .disable_help_flag .try_get_matches_from; assert!; assert_eq!;You can create a custom help flag with
ArgAction::Help,ArgAction::HelpShort, orArgAction::HelpLong# use clap_builder as clap; # use ; let mut cmd = new // Change help short flag to `?` .disable_help_flag .arg; let res = cmd.try_get_matches_from_mut; assert!; assert_eq!; let res = cmd.try_get_matches_from_mut; assert!; assert_eq!;fn disable_help_subcommand(self: Self, yes: bool) -> SelfDisables the
helpsubcommand.NOTE: This choice is propagated to all child subcommands.
Examples
# use clap_builder as clap; # use ; let res = new .disable_help_subcommand // Normally, creating a subcommand causes a `help` subcommand to automatically // be generated as well .subcommand .try_get_matches_from; assert!; assert_eq!;fn disable_colored_help(self: Self, yes: bool) -> SelfDisables colorized help messages.
NOTE: This choice is propagated to all child subcommands.
Examples
# use clap_builder as clap; # use clap::Command; Command::new("myprog") .disable_colored_help(true) .get_matches();fn help_expected(self: Self, yes: bool) -> SelfPanic if help descriptions are omitted.
NOTE: When deriving [
Parser][crate::Parser], you could instead check this at compile-time with#![deny(missing_docs)]NOTE: This choice is propagated to all child subcommands.
Examples
# use clap_builder as clap; # use ; new .help_expected .arg # .get_matches;Panics
On debug builds:
# use clap_builder as clap; # use ; new .help_expected .arg # .get_matches;fn hide_possible_values(self: Self, yes: bool) -> SelfTells
clapnot to print possible values when displaying help information.This can be useful if there are many values, or they are explained elsewhere.
To set this per argument, see [
Arg::hide_possible_values][crate::Arg::hide_possible_values].NOTE: This choice is propagated to all child subcommands.
fn infer_long_args(self: Self, yes: bool) -> SelfAllow partial matches of long arguments or their aliases.
For example, to match an argument named
--test, one could use--t,--te,--tes, and--test.NOTE: The match must not be ambiguous at all in order to succeed. i.e. to match
--teto--testthere could not also be another argument or alias--tempbecause both start with--teNOTE: This choice is propagated to all child subcommands.
fn infer_subcommands(self: Self, yes: bool) -> SelfAllow partial matches of subcommand names and their aliases.
For example, to match a subcommand named
test, one could uset,te,tes, andtest.NOTE: The match must not be ambiguous at all in order to succeed. i.e. to match
tetotestthere could not also be a subcommand or aliastempbecause both start withteWARNING: This setting can interfere with positional/free arguments, take care when designing CLIs which allow inferred subcommands and have potential positional/free arguments whose values could start with the same characters as subcommands. If this is the case, it's recommended to use settings such as
Command::args_conflicts_with_subcommandsin conjunction with this setting.NOTE: This choice is propagated to all child subcommands.
Examples
# use clap_builder as clap; # use clap::{Command, Arg}; let m = Command::new("prog") .infer_subcommands(true) .subcommand(Command::new("test")) .get_matches_from(vec![ "prog", "te" ]); assert_eq!(m.subcommand_name(), Some("test"));
impl Command
impl Clone for Command
fn clone(self: &Self) -> Command
impl Debug for Command
fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<'_>) -> $crate::fmt::Result
impl Default for Command
fn default() -> Self
impl Display for Command
fn fmt(self: &Self, f: &mut fmt::Formatter<'_>) -> fmt::Result
impl Freeze for Command
impl From for Command
fn from(cmd: &Command) -> Self
impl Index for Command
fn index(self: &Self, key: &Id) -> &<Self as >::Output
impl RefUnwindSafe for Command
impl Send for Command
impl Sync for Command
impl Unpin for Command
impl UnwindSafe for Command
impl<T> Any for Command
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for Command
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for Command
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for Command
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> From for Command
fn from(t: T) -> TReturns the argument unchanged.
impl<T> ToOwned for Command
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T> ToString for Command
fn to_string(self: &Self) -> String
impl<T, U> Into for Command
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for Command
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for Command
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>