pub struct App<'help> { /* private fields */ }
Replaced with Command
Expand description
Deprecated, replaced with Command
Implementations
sourceimpl<'help> App<'help>
impl<'help> App<'help>
sourcepub fn new<S: Into<String>>(name: S) -> Self
pub fn new<S: Into<String>>(name: S) -> Self
Creates a new instance of an Command
.
It is common, but not required, to use binary name as the name
. This
name will only be displayed to the user when they request to print
version or help and usage information.
See also command!
and crate_name!
.
Examples
Command::new("My Program")
sourcepub fn arg<A: Into<Arg<'help>>>(self, a: A) -> Self
pub fn arg<A: Into<Arg<'help>>>(self, a: A) -> Self
Adds an argument to the list of valid possibilities.
Examples
Command::new("myprog")
// Adding a single "flag" argument with a short and help text, using Arg::new()
.arg(
Arg::new("debug")
.short('d')
.help("turns on debugging mode")
)
// Adding a single "option" argument with a short, a long, and help text using the less
// verbose Arg::from()
.arg(
arg!(-c --config <CONFIG> "Optionally sets a config file to use")
)
sourcepub fn args<I, T>(self, args: I) -> Self where
I: IntoIterator<Item = T>,
T: Into<Arg<'help>>,
pub fn args<I, T>(self, args: I) -> Self where
I: IntoIterator<Item = T>,
T: Into<Arg<'help>>,
sourcepub fn mut_arg<T, F>(self, arg_id: T, f: F) -> Self where
F: FnOnce(Arg<'help>) -> Arg<'help>,
T: Key + Into<&'help str>,
pub fn mut_arg<T, F>(self, arg_id: T, f: F) -> Self where
F: FnOnce(Arg<'help>) -> Arg<'help>,
T: Key + Into<&'help str>,
Allows one to mutate an Arg
after it’s been added to a Command
.
This can be useful for modifying the auto-generated help or version arguments.
Examples
let mut cmd = Command::new("foo")
.arg(Arg::new("bar")
.short('b'))
.mut_arg("bar", |a| a.short('B'));
let res = cmd.try_get_matches_from_mut(vec!["foo", "-b"]);
// Since we changed `bar`'s short to "B" this should err as there
// is no `-b` anymore, only `-B`
assert!(res.is_err());
let res = cmd.try_get_matches_from_mut(vec!["foo", "-B"]);
assert!(res.is_ok());
sourcepub fn group<G: Into<ArgGroup<'help>>>(self, group: G) -> Self
pub fn group<G: Into<ArgGroup<'help>>>(self, group: G) -> Self
Adds an ArgGroup
to the application.
ArgGroup
s are a family of related arguments.
By placing them in a logical group, you can build easier requirement and exclusion rules.
Example use cases:
- Make an entire
ArgGroup
required, meaning that one (and only one) argument from that group must be present at runtime. - Name an
ArgGroup
as a conflict to another argument. Meaning any of the arguments that belong to that group will cause a failure if present with the conflicting argument. - Ensure exclusion between arguments.
- Extract a value from a group instead of determining exactly which argument was used.
Examples
The following example demonstrates using an ArgGroup
to ensure that one, and only one,
of the arguments from the specified group is present at runtime.
Command::new("cmd")
.arg(arg!("--set-ver [ver] 'set the version manually'"))
.arg(arg!("--major 'auto increase major'"))
.arg(arg!("--minor 'auto increase minor'"))
.arg(arg!("--patch 'auto increase patch'"))
.group(ArgGroup::new("vers")
.args(&["set-ver", "major", "minor","patch"])
.required(true))
sourcepub fn groups<I, T>(self, groups: I) -> Self where
I: IntoIterator<Item = T>,
T: Into<ArgGroup<'help>>,
pub fn groups<I, T>(self, groups: I) -> Self where
I: IntoIterator<Item = T>,
T: Into<ArgGroup<'help>>,
Adds multiple ArgGroup
s to the Command
at once.
Examples
Command::new("cmd")
.arg(arg!("--set-ver [ver] 'set the version manually'"))
.arg(arg!("--major 'auto increase major'"))
.arg(arg!("--minor 'auto increase minor'"))
.arg(arg!("--patch 'auto increase patch'"))
.arg(arg!("-c [FILE] 'a config file'"))
.arg(arg!("-i [IFACE] 'an interface'"))
.groups(&[
ArgGroup::new("vers")
.args(&["set-ver", "major", "minor","patch"])
.required(true),
ArgGroup::new("input")
.args(&["c", "i"])
])
sourcepub fn subcommand<S: Into<App<'help>>>(self, subcmd: S) -> Self
pub fn subcommand<S: Into<App<'help>>>(self, subcmd: S) -> Self
Adds a subcommand to the list of valid possibilities.
Subcommands are effectively sub-Command
s, because they can contain their own arguments,
subcommands, version, usage, etc. They also function just like Command
s, in that they get
their own auto generated help, version, and usage.
A subcommand’s Command::name
will be used for:
- The argument the user passes in
- Programmatically looking up the subcommand
Examples
Command::new("myprog")
.subcommand(Command::new("config")
.about("Controls configuration features")
.arg(arg!("<config> 'Required configuration file to use'")))
sourcepub fn subcommands<I, T>(self, subcmds: I) -> Self where
I: IntoIterator<Item = T>,
T: Into<App<'help>>,
pub fn subcommands<I, T>(self, subcmds: I) -> Self where
I: IntoIterator<Item = T>,
T: Into<App<'help>>,
Adds multiple subcommands to the list of valid possibilities.
Examples
.subcommands( vec![
Command::new("config").about("Controls configuration functionality")
.arg(Arg::new("config_file")),
Command::new("debug").about("Controls debug functionality")])
sourcepub fn debug_assert(self)
pub fn debug_assert(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
fn cmd() -> Command<'static> {
Command::new("foo")
.arg(Arg::new("bar").short('b')
)
}
#[test]
fn verify_app() {
cmd().debug_assert();
}
fn main() {
let m = cmd().get_matches_from(vec!["foo", "-b"]);
println!("{}", m.is_present("bar"));
}
sourcepub fn error(&mut self, kind: ErrorKind, message: impl Display) -> Error
pub fn error(&mut self, kind: ErrorKind, message: impl Display) -> Error
Custom error message for post-parsing validation
Examples
let mut cmd = Command::new("myprog");
let err = cmd.error(ErrorKind::InvalidValue, "Some failure case");
sourcepub fn get_matches(self) -> ArgMatches
pub fn get_matches(self) -> ArgMatches
Parse env::args_os
, exiting on failure.
Panics
If contradictory arguments or settings exist.
Examples
let matches = Command::new("myprog")
// Args and options go here...
.get_matches();
sourcepub fn get_matches_mut(&mut self) -> ArgMatches
pub fn get_matches_mut(&mut self) -> ArgMatches
Parse env::args_os
, exiting on failure.
Like App::get_matches
but doesn’t consume the Command
.
Panics
If contradictory arguments or settings exist.
Examples
let mut cmd = Command::new("myprog")
// Args and options go here...
;
let matches = cmd.get_matches_mut();
sourcepub fn try_get_matches(self) -> ClapResult<ArgMatches>
pub fn try_get_matches(self) -> ClapResult<ArgMatches>
Parse env::args_os
, returning a clap::Result
on failure.
NOTE: This method WILL NOT exit when --help
or --version
(or short versions) are
used. It will return a clap::Error
, where the kind
is a
ErrorKind::DisplayHelp
or ErrorKind::DisplayVersion
respectively. You must call
Error::exit
or perform a std::process::exit
.
Panics
If contradictory arguments or settings exist.
Examples
let matches = Command::new("myprog")
// Args and options go here...
.try_get_matches()
.unwrap_or_else(|e| e.exit());
sourcepub fn get_matches_from<I, T>(self, itr: I) -> ArgMatches where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
pub fn get_matches_from<I, T>(self, itr: I) -> ArgMatches where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
Parse the specified arguments, exiting on failure.
NOTE: The first argument will be parsed as the binary name unless
Command::no_binary_name
is used.
Panics
If contradictory arguments or settings exist.
Examples
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);
sourcepub fn try_get_matches_from<I, T>(self, itr: I) -> ClapResult<ArgMatches> where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
pub fn try_get_matches_from<I, T>(self, itr: I) -> ClapResult<ArgMatches> where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
Parse the specified arguments, returning a clap::Result
on failure.
NOTE: This method WILL NOT exit when --help
or --version
(or short versions) are
used. It will return a clap::Error
, where the kind
is a ErrorKind::DisplayHelp
or ErrorKind::DisplayVersion
respectively. You must call Error::exit
or
perform a std::process::exit
yourself.
NOTE: The first argument will be parsed as the binary name unless
Command::no_binary_name
is used.
Panics
If contradictory arguments or settings exist.
Examples
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());
sourcepub fn try_get_matches_from_mut<I, T>(
&mut self,
itr: I
) -> ClapResult<ArgMatches> where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
pub fn try_get_matches_from_mut<I, T>(
&mut self,
itr: I
) -> ClapResult<ArgMatches> where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
Parse the specified arguments, returning a clap::Result
on failure.
Like App::try_get_matches_from
but doesn’t consume the Command
.
NOTE: This method WILL NOT exit when --help
or --version
(or short versions) are
used. It will return a clap::Error
, where the kind
is a ErrorKind::DisplayHelp
or ErrorKind::DisplayVersion
respectively. You must call Error::exit
or
perform a std::process::exit
yourself.
NOTE: The first argument will be parsed as the binary name unless
Command::no_binary_name
is used.
Panics
If contradictory arguments or settings exist.
Examples
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());
sourcepub fn print_help(&mut self) -> Result<()>
pub fn print_help(&mut self) -> Result<()>
Prints the short help message (-h
) to io::stdout()
.
See also Command::print_long_help
.
Examples
let mut cmd = Command::new("myprog");
cmd.print_help();
sourcepub fn print_long_help(&mut self) -> Result<()>
pub fn print_long_help(&mut self) -> Result<()>
Prints the long help message (--help
) to io::stdout()
.
See also Command::print_help
.
Examples
let mut cmd = Command::new("myprog");
cmd.print_long_help();
sourcepub fn write_help<W: Write>(&mut self, w: &mut W) -> Result<()>
pub fn write_help<W: Write>(&mut self, w: &mut W) -> Result<()>
Writes the short help message (-h
) to a io::Write
object.
See also Command::write_long_help
.
Examples
use std::io;
let mut cmd = Command::new("myprog");
let mut out = io::stdout();
cmd.write_help(&mut out).expect("failed to write to stdout");
sourcepub fn write_long_help<W: Write>(&mut self, w: &mut W) -> Result<()>
pub fn write_long_help<W: Write>(&mut self, w: &mut W) -> Result<()>
Writes the long help message (--help
) to a io::Write
object.
See also Command::write_help
.
Examples
use std::io;
let mut cmd = Command::new("myprog");
let mut out = io::stdout();
cmd.write_long_help(&mut out).expect("failed to write to stdout");
sourcepub fn render_version(&self) -> String
pub fn render_version(&self) -> String
Version message rendered as if the user ran -V
.
See also Command::render_long_version
.
Coloring
This function does not try to color the message nor it inserts any ANSI escape codes.
Examples
use std::io;
let cmd = Command::new("myprog");
println!("{}", cmd.render_version());
sourcepub fn render_long_version(&self) -> String
pub fn render_long_version(&self) -> String
Version message rendered as if the user ran --version
.
See also Command::render_version
.
Coloring
This function does not try to color the message nor it inserts any ANSI escape codes.
Examples
use std::io;
let cmd = Command::new("myprog");
println!("{}", cmd.render_long_version());
sourcepub fn render_usage(&mut self) -> String
pub fn render_usage(&mut self) -> String
Usage statement
Examples
use std::io;
let mut cmd = Command::new("myprog");
println!("{}", cmd.render_usage());
sourceimpl<'help> App<'help>
impl<'help> App<'help>
Application-wide Settings
These settings will apply to the top-level command and all subcommands, by default. Some settings can be overridden in subcommands.
sourcepub fn no_binary_name(self, yes: bool) -> Self
pub fn no_binary_name(self, yes: bool) -> Self
Specifies that the parser should not assume the first argument passed is the binary name.
This is normally the case when using a “daemon” style mode. For shells / REPLs, see
[Command::multicall
][App::multicall].
Examples
let m = Command::new("myprog")
.no_binary_name(true)
.arg(arg!(<cmd> ... "commands to run"))
.get_matches_from(vec!["command", "set"]);
let cmds: Vec<&str> = m.values_of("cmd").unwrap().collect();
assert_eq!(cmds, ["command", "set"]);
sourcepub fn ignore_errors(self, yes: bool) -> Self
pub fn ignore_errors(self, yes: bool) -> Self
Try not to fail on parse errors, like missing option values.
Note: Make sure you apply it as global_setting
if you want this setting
to be propagated to subcommands and sub-subcommands!
NOTE: This choice is propagated to all child subcommands.
Examples
let cmd = Command::new("cmd")
.ignore_errors(true)
.arg(arg!(-c --config <FILE> "Sets a custom config file").required(false))
.arg(arg!(-x --stuff <FILE> "Sets a custom stuff file").required(false))
.arg(arg!(f: -f "Flag"));
let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]);
assert!(r.is_ok(), "unexpected error: {:?}", r);
let m = r.unwrap();
assert_eq!(m.value_of("config"), Some("file"));
assert!(m.is_present("f"));
assert_eq!(m.value_of("stuff"), None);
sourcepub fn args_override_self(self, yes: bool) -> Self
pub fn args_override_self(self, yes: bool) -> Self
Specifies that all arguments override themselves.
This is the equivalent to saying the foo
arg using Arg::overrides_with("foo")
for all
defined arguments.
NOTE: This will not be applied when [Arg::multiple_occurrences(true)
].
NOTE: This choice is propagated to all child subcommands.
sourcepub fn dont_delimit_trailing_values(self, yes: bool) -> Self
pub fn dont_delimit_trailing_values(self, yes: bool) -> Self
Disables the automatic delimiting of values after --
or when Command::trailing_var_arg
was used.
NOTE: The same thing can be done manually by setting the final positional argument to
Arg::use_value_delimiter(false)
. Using this setting is safer, because it’s easier to locate
when making changes.
NOTE: This choice is propagated to all child subcommands.
Examples
Command::new("myprog")
.dont_delimit_trailing_values(true)
.get_matches();
sourcepub fn color(self, color: ColorChoice) -> Self
pub fn color(self, color: ColorChoice) -> Self
Sets when to color output.
NOTE: This choice is propagated to all child subcommands.
NOTE: Default behaviour is ColorChoice::Auto
.
Examples
Command::new("myprog")
.color(ColorChoice::Never)
.get_matches();
sourcepub fn term_width(self, width: usize) -> Self
pub fn term_width(self, width: usize) -> Self
Sets the terminal width at which to wrap help messages.
Using 0
will ignore terminal widths and use source formatting.
Defaults to current terminal width when wrap_help
feature flag is enabled. If the flag
is disabled or it cannot be determined, the default is 100.
NOTE: This setting applies globally and not on a per-command basis.
Examples
Command::new("myprog")
.term_width(80)
sourcepub fn max_term_width(self, w: usize) -> Self
pub fn max_term_width(self, w: usize) -> Self
Sets the maximum terminal width at which to wrap help messages.
This only applies when setting the current terminal width. See Command::term_width
for
more details.
Using 0
will ignore terminal widths and use source formatting.
NOTE: This setting applies globally and not on a per-command basis.
Examples
Command::new("myprog")
.max_term_width(100)
sourcepub fn disable_version_flag(self, yes: bool) -> Self
pub fn disable_version_flag(self, yes: bool) -> Self
Disables -V
and --version
flag.
Examples
let res = Command::new("myprog")
.disable_version_flag(true)
.try_get_matches_from(vec![
"myprog", "-V"
]);
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
sourcepub fn propagate_version(self, yes: bool) -> Self
pub fn propagate_version(self, yes: bool) -> Self
Specifies to use the version of the current command for all subcommands
.
Defaults to false
; subcommands have independent version strings from their parents.
Note: Make sure you apply it as global_setting
if you want this setting
to be propagated to subcommands and sub-subcommands!
NOTE: This choice is propagated to all child subcommands.
Examples
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"
sourcepub fn next_line_help(self, yes: bool) -> Self
pub fn next_line_help(self, yes: bool) -> Self
Places the help string for all arguments and subcommands on the line after them.
NOTE: This choice is propagated to all child subcommands.
Examples
Command::new("myprog")
.next_line_help(true)
.get_matches();
sourcepub fn disable_help_flag(self, yes: bool) -> Self
pub fn disable_help_flag(self, yes: bool) -> Self
Disables -h
and --help
flag.
NOTE: This choice is propagated to all child subcommands.
Examples
let res = Command::new("myprog")
.disable_help_flag(true)
.try_get_matches_from(vec![
"myprog", "-h"
]);
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
sourcepub fn disable_help_subcommand(self, yes: bool) -> Self
pub fn disable_help_subcommand(self, yes: bool) -> Self
Disables the help
subcommand
.
Examples
let res = Command::new("myprog")
.disable_help_subcommand(true)
// Normally, creating a subcommand causes a `help` subcommand to automatically
// be generated as well
.subcommand(Command::new("test"))
.try_get_matches_from(vec![
"myprog", "help"
]);
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
sourcepub fn disable_colored_help(self, yes: bool) -> Self
pub fn disable_colored_help(self, yes: bool) -> Self
Disables colorized help messages.
NOTE: This choice is propagated to all child subcommands.
Examples
Command::new("myprog")
.disable_colored_help(true)
.get_matches();
sourcepub fn help_expected(self, yes: bool) -> Self
pub fn help_expected(self, yes: bool) -> Self
Panic if help descriptions are omitted.
NOTE: When deriving Parser
, you could instead check this at
compile-time with #![deny(missing_docs)]
NOTE: This choice is propagated to all child subcommands.
Examples
Command::new("myprog")
.help_expected(true)
.arg(
Arg::new("foo").help("It does foo stuff")
// As required via `help_expected`, a help message was supplied
)
Panics
Command::new("myapp")
.help_expected(true)
.arg(
Arg::new("foo")
// Someone forgot to put .about("...") here
// Since the setting `help_expected` is activated, this will lead to
// a panic (if you are in debug mode)
)
sourcepub fn dont_collapse_args_in_usage(self, yes: bool) -> Self
pub fn dont_collapse_args_in_usage(self, yes: bool) -> Self
Disables the automatic collapsing of positional args into [ARGS]
inside the usage string.
NOTE: This choice is propagated to all child subcommands.
Examples
Command::new("myprog")
.dont_collapse_args_in_usage(true)
.get_matches();
sourcepub fn hide_possible_values(self, yes: bool) -> Self
pub fn hide_possible_values(self, yes: bool) -> Self
Tells clap
not to print possible values when displaying help information.
This can be useful if there are many values, or they are explained elsewhere.
To set this per argument, see
Arg::hide_possible_values
.
NOTE: This choice is propagated to all child subcommands.
sourcepub fn infer_long_args(self, yes: bool) -> Self
pub fn infer_long_args(self, yes: bool) -> Self
Allow partial matches of long arguments or their aliases.
For example, to match an argument named --test
, one could use --t
, --te
, --tes
, and
--test
.
NOTE: The match must not be ambiguous at all in order to succeed. i.e. to match
--te
to --test
there could not also be another argument or alias --temp
because both
start with --te
NOTE: This choice is propagated to all child subcommands.
sourcepub fn infer_subcommands(self, yes: bool) -> Self
pub fn infer_subcommands(self, yes: bool) -> Self
Allow partial matches of subcommand names and their aliases.
For example, to match a subcommand named test
, one could use t
, te
, tes
, and
test
.
NOTE: The match must not be ambiguous at all in order to succeed. i.e. to match te
to test
there could not also be a subcommand or alias temp
because both start with te
CAUTION: This setting can interfere with positional/free arguments, take care when
designing CLIs which allow inferred subcommands and have potential positional/free
arguments whose values could start with the same characters as subcommands. If this is the
case, it’s recommended to use settings such as Command::args_conflicts_with_subcommands
in
conjunction with this setting.
NOTE: This choice is propagated to all child subcommands.
Examples
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"));
sourceimpl<'help> App<'help>
impl<'help> App<'help>
Command-specific Settings
These apply only to the current command and are not inherited by subcommands.
sourcepub fn name<S: Into<String>>(self, name: S) -> Self
pub fn name<S: Into<String>>(self, name: S) -> Self
(Re)Sets the program’s name.
See Command::new
for more details.
Examples
let yaml = load_yaml!("cmd.yaml");
let cmd = Command::from(yaml)
.name(crate_name!());
// continued logic goes here, such as `cmd.get_matches()` etc.
sourcepub fn bin_name<S: Into<String>>(self, name: S) -> Self
pub fn bin_name<S: Into<String>>(self, name: S) -> Self
Overrides the runtime-determined name of the binary for help and error messages.
This should only be used when absolutely necessary, such as when the binary name for your application is misleading, or perhaps not how the user should invoke your program.
Pro-tip: When building things such as third party cargo
subcommands, this setting should be used!
NOTE: This does not change or set the name of the binary file on disk. It only changes what clap thinks the name is for the purposes of error or help messages.
Examples
Command::new("My Program")
.bin_name("my_binary")
sourcepub fn display_name<S: Into<String>>(self, name: S) -> Self
pub fn display_name<S: Into<String>>(self, name: S) -> Self
Overrides the runtime-determined display name of the program for help and error messages.
Examples
Command::new("My Program")
.display_name("my_program")
Sets the author(s) for the help message.
Pro-tip: Use clap
s convenience macro crate_authors!
to
automatically set your application’s author(s) to the same thing as your
crate at compile time.
Examples
Command::new("myprog")
.author("Me, me@mymain.com")
sourcepub fn about<O: Into<Option<&'help str>>>(self, about: O) -> Self
pub fn about<O: Into<Option<&'help str>>>(self, about: O) -> Self
Sets the program’s description for the short help (-h
).
If Command::long_about
is not specified, this message will be displayed for --help
.
NOTE: Only Command::about
(short format) is used in completion
script generation in order to be concise.
See also crate_description!
.
Examples
Command::new("myprog")
.about("Does really amazing things for great people")
sourcepub fn long_about<O: Into<Option<&'help str>>>(self, long_about: O) -> Self
pub fn long_about<O: Into<Option<&'help str>>>(self, long_about: O) -> Self
Sets the program’s description for the long help (--help
).
If Command::about
is not specified, this message will be displayed for -h
.
NOTE: Only Command::about
(short format) is used in completion
script generation in order to be concise.
Examples
Command::new("myprog")
.long_about(
"Does really amazing things to great people. Now let's talk a little
more in depth about how this subcommand really works. It may take about
a few lines of text, but that's ok!")
sourcepub fn after_help<S: Into<&'help str>>(self, help: S) -> Self
pub fn after_help<S: Into<&'help str>>(self, help: S) -> Self
Free-form help text for after auto-generated short help (-h
).
This is often used to describe how to use the arguments, caveats to be noted, or license and contact information.
If Command::after_long_help
is not specified, this message will be displayed for --help
.
Examples
Command::new("myprog")
.after_help("Does really amazing things for great people... but be careful with -R!")
sourcepub fn after_long_help<S: Into<&'help str>>(self, help: S) -> Self
pub fn after_long_help<S: Into<&'help str>>(self, help: S) -> Self
Free-form help text for after auto-generated long help (--help
).
This is often used to describe how to use the arguments, caveats to be noted, or license and contact information.
If Command::after_help
is not specified, this message will be displayed for -h
.
Examples
Command::new("myprog")
.after_long_help("Does really amazing things to great people... but be careful with -R, \
like, for real, be careful with this!")
sourcepub fn before_help<S: Into<&'help str>>(self, help: S) -> Self
pub fn before_help<S: Into<&'help str>>(self, help: S) -> Self
Free-form help text for before auto-generated short help (-h
).
This is often used for header, copyright, or license information.
If Command::before_long_help
is not specified, this message will be displayed for --help
.
Examples
Command::new("myprog")
.before_help("Some info I'd like to appear before the help info")
sourcepub fn before_long_help<S: Into<&'help str>>(self, help: S) -> Self
pub fn before_long_help<S: Into<&'help str>>(self, help: S) -> Self
Free-form help text for before auto-generated long help (--help
).
This is often used for header, copyright, or license information.
If Command::before_help
is not specified, this message will be displayed for -h
.
Examples
Command::new("myprog")
.before_long_help("Some verbose and long info I'd like to appear before the help info")
sourcepub fn version<S: Into<&'help str>>(self, ver: S) -> Self
pub fn version<S: Into<&'help str>>(self, ver: S) -> Self
Sets the version for the short version (-V
) and help messages.
If Command::long_version
is not specified, this message will be displayed for --version
.
Pro-tip: Use clap
s convenience macro crate_version!
to
automatically set your application’s version to the same thing as your
crate at compile time.
Examples
Command::new("myprog")
.version("v0.1.24")
sourcepub fn long_version<S: Into<&'help str>>(self, ver: S) -> Self
pub fn long_version<S: Into<&'help str>>(self, ver: S) -> Self
Sets the version for the long version (--version
) and help messages.
If Command::version
is not specified, this message will be displayed for -V
.
Pro-tip: Use clap
s convenience macro crate_version!
to
automatically set your application’s version to the same thing as your
crate at compile time.
Examples
Command::new("myprog")
.long_version(
"v0.1.24
commit: abcdef89726d
revision: 123
release: 2
binary: myprog")
sourcepub fn override_usage<S: Into<&'help str>>(self, usage: S) -> Self
pub fn override_usage<S: Into<&'help str>>(self, usage: S) -> Self
Overrides the clap
generated usage string for help and error messages.
NOTE: Using this setting disables clap
s “context-aware” usage
strings. After this setting is set, this will be the only usage string
displayed to the user!
Examples
Command::new("myprog")
.override_usage("myapp [-clDas] <some_file>")
sourcepub fn override_help<S: Into<&'help str>>(self, help: S) -> Self
pub fn override_help<S: Into<&'help str>>(self, help: S) -> Self
Overrides the clap
generated help message (both -h
and --help
).
This should only be used when the auto-generated message does not suffice.
NOTE: This only replaces the help message for the current
command, meaning if you are using subcommands, those help messages will
still be auto-generated unless you specify a Command::override_help
for
them as well.
Examples
Command::new("myapp")
.override_help("myapp v1.0\n\
Does awesome things\n\
(C) me@mail.com\n\n\
USAGE: myapp <opts> <command>\n\n\
Options:\n\
-h, --help Display this message\n\
-V, --version Display version info\n\
-s <stuff> Do something with stuff\n\
-v Be verbose\n\n\
Commands:\n\
help Print this message\n\
work Do some work")
sourcepub fn help_template<S: Into<&'help str>>(self, s: S) -> Self
pub fn help_template<S: Into<&'help str>>(self, s: S) -> Self
Sets the help template to be used, overriding the default format.
NOTE: The template system is by design very simple. Therefore, the tags have to be written in the lowercase and without spacing.
Tags are given inside curly brackets.
Valid tags are:
{name}
- Display name for the (sub-)command.{bin}
- Binary name.{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::about
orCommand::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.{after-help}
- Help fromApp::after_help
orCommand::after_long_help
.{before-help}
- Help fromApp::before_help
orCommand::before_long_help
.
Examples
Command::new("myprog")
.version("1.0")
.help_template("{bin} ({version}) - {usage}")
sourcepub fn setting<F>(self, setting: F) -> Self where
F: Into<AppFlags>,
pub fn setting<F>(self, setting: F) -> Self where
F: Into<AppFlags>,
Apply a setting for the current command or subcommand.
See Command::global_setting
to apply a setting to this command and all subcommands.
See AppSettings
for a full list of possibilities and examples.
Examples
Command::new("myprog")
.setting(AppSettings::SubcommandRequired)
.setting(AppSettings::AllowLeadingHyphen)
or
Command::new("myprog")
.setting(AppSettings::SubcommandRequired | AppSettings::AllowLeadingHyphen)
sourcepub fn unset_setting<F>(self, setting: F) -> Self where
F: Into<AppFlags>,
pub fn unset_setting<F>(self, setting: F) -> Self where
F: Into<AppFlags>,
Remove a setting for the current command or subcommand.
See AppSettings
for a full list of possibilities and examples.
Examples
Command::new("myprog")
.unset_setting(AppSettings::SubcommandRequired)
.setting(AppSettings::AllowLeadingHyphen)
or
Command::new("myprog")
.unset_setting(AppSettings::SubcommandRequired | AppSettings::AllowLeadingHyphen)
sourcepub fn global_setting(self, setting: AppSettings) -> Self
pub fn global_setting(self, setting: AppSettings) -> Self
Apply a setting for the current command and all subcommands.
See Command::setting
to apply a setting only to this command.
See AppSettings
for a full list of possibilities and examples.
Examples
Command::new("myprog")
.global_setting(AppSettings::AllowNegativeNumbers)
sourcepub fn unset_global_setting(self, setting: AppSettings) -> Self
pub fn unset_global_setting(self, setting: AppSettings) -> Self
Remove a setting and stop propagating down to subcommands.
See AppSettings
for a full list of possibilities and examples.
Examples
Command::new("myprog")
.unset_global_setting(AppSettings::AllowNegativeNumbers)
sourcepub fn help_heading<O>(self, heading: O) -> Self where
O: Into<Option<&'help str>>,
👎 Deprecated since 3.1.0: Replaced with App::next_help_heading
pub fn help_heading<O>(self, heading: O) -> Self where
O: Into<Option<&'help str>>,
Replaced with App::next_help_heading
Deprecated, replaced with Command::next_help_heading
sourcepub fn next_help_heading<O>(self, heading: O) -> Self where
O: Into<Option<&'help str>>,
pub fn next_help_heading<O>(self, heading: O) -> Self where
O: Into<Option<&'help str>>,
Set the default section heading for future args.
This will be used for any arg that hasn’t had Arg::help_heading
called.
This is useful if the default OPTIONS
or ARGS
headings are
not specific enough for one’s use case.
For subcommands, see Command::subcommand_help_heading
sourcepub fn next_display_order(self, disp_ord: impl Into<Option<usize>>) -> Self
pub fn next_display_order(self, disp_ord: impl Into<Option<usize>>) -> Self
Change the starting value for assigning future display orders for ags.
This will be used for any arg that hasn’t had Arg::display_order
called.
sourcepub fn arg_required_else_help(self, yes: bool) -> Self
pub fn arg_required_else_help(self, yes: bool) -> Self
Exit gracefully if no arguments are present (e.g. $ myprog
).
NOTE: subcommands
count as arguments
Examples
Command::new("myprog")
.arg_required_else_help(true);
sourcepub fn allow_hyphen_values(self, yes: bool) -> Self
pub fn allow_hyphen_values(self, yes: bool) -> Self
Specifies that leading hyphens are allowed in all argument values (e.g. -10
).
Otherwise they will be parsed as another flag or option. See also
Command::allow_negative_numbers
.
NOTE: Use this setting with caution as it silences certain circumstances which would
otherwise be an error (such as accidentally forgetting to specify a value for leading
option). It is preferred to set this on a per argument basis, via Arg::allow_hyphen_values
.
Examples
// Imagine you needed to represent negative numbers as well, such as -10
let m = Command::new("nums")
.allow_hyphen_values(true)
.arg(Arg::new("neg"))
.get_matches_from(vec![
"nums", "-20"
]);
assert_eq!(m.value_of("neg"), Some("-20"));
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 Command::allow_hyphen_values
except that it only allows numbers,
all other undefined leading hyphens will fail to parse.
Examples
let res = Command::new("myprog")
.allow_negative_numbers(true)
.arg(Arg::new("num"))
.try_get_matches_from(vec![
"myprog", "-20"
]);
assert!(res.is_ok());
let m = res.unwrap();
assert_eq!(m.value_of("num").unwrap(), "-20");
sourcepub fn trailing_var_arg(self, yes: bool) -> Self
pub fn trailing_var_arg(self, yes: bool) -> Self
Specifies that the final positional argument is a “VarArg” and that clap
should not
attempt to parse any further args.
The values of the trailing positional argument will contain all args from itself on.
NOTE: The final positional argument must have Arg::multiple_values(true)
or the usage
string equivalent.
Examples
let m = Command::new("myprog")
.trailing_var_arg(true)
.arg(arg!(<cmd> ... "commands to run"))
.get_matches_from(vec!["myprog", "arg1", "-r", "val1"]);
let trail: Vec<&str> = m.values_of("cmd").unwrap().collect();
assert_eq!(trail, ["arg1", "-r", "val1"]);
sourcepub fn allow_missing_positional(self, yes: bool) -> Self
pub fn allow_missing_positional(self, yes: bool) -> Self
Allows one to implement two styles of CLIs where positionals can be used out of order.
The first example is a CLI where the second to last positional argument is optional, but
the final positional argument is required. Such as $ prog [optional] <required>
where one
of the two following usages is allowed:
$ prog [optional] <required>
$ prog <required>
This would otherwise not be allowed. This is useful when [optional]
has a default value.
Note: when using this style of “missing positionals” the final positional must be
required if --
will not be used to skip to the final positional argument.
Note: This style also only allows a single positional argument to be “skipped” without
the use of --
. To skip more than one, see the second example.
The second example is when one wants to skip multiple optional positional arguments, and use
of the --
operator is OK (but not required if all arguments will be specified anyways).
For example, imagine a CLI which has three positional arguments [foo] [bar] [baz]...
where
baz
accepts multiple values (similar to man ARGS...
style training arguments).
With this setting the following invocations are posisble:
$ prog foo bar baz1 baz2 baz3
$ prog foo -- baz1 baz2 baz3
$ prog -- baz1 baz2 baz3
Examples
Style number one from above:
// Assume there is an external subcommand named "subcmd"
let m = Command::new("myprog")
.allow_missing_positional(true)
.arg(Arg::new("arg1"))
.arg(Arg::new("arg2")
.required(true))
.get_matches_from(vec![
"prog", "other"
]);
assert_eq!(m.value_of("arg1"), None);
assert_eq!(m.value_of("arg2"), Some("other"));
Now the same example, but using a default value for the first optional positional argument
// Assume there is an external subcommand named "subcmd"
let m = Command::new("myprog")
.allow_missing_positional(true)
.arg(Arg::new("arg1")
.default_value("something"))
.arg(Arg::new("arg2")
.required(true))
.get_matches_from(vec![
"prog", "other"
]);
assert_eq!(m.value_of("arg1"), Some("something"));
assert_eq!(m.value_of("arg2"), Some("other"));
Style number two from above:
// Assume there is an external subcommand named "subcmd"
let m = Command::new("myprog")
.allow_missing_positional(true)
.arg(Arg::new("foo"))
.arg(Arg::new("bar"))
.arg(Arg::new("baz").takes_value(true).multiple_values(true))
.get_matches_from(vec![
"prog", "foo", "bar", "baz1", "baz2", "baz3"
]);
assert_eq!(m.value_of("foo"), Some("foo"));
assert_eq!(m.value_of("bar"), Some("bar"));
assert_eq!(m.values_of("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
Now nofice if we don’t specify foo
or baz
but use the --
operator.
// Assume there is an external subcommand named "subcmd"
let m = Command::new("myprog")
.allow_missing_positional(true)
.arg(Arg::new("foo"))
.arg(Arg::new("bar"))
.arg(Arg::new("baz").takes_value(true).multiple_values(true))
.get_matches_from(vec![
"prog", "--", "baz1", "baz2", "baz3"
]);
assert_eq!(m.value_of("foo"), None);
assert_eq!(m.value_of("bar"), None);
assert_eq!(m.values_of("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
sourceimpl<'help> App<'help>
impl<'help> App<'help>
sourcepub fn short_flag(self, short: char) -> Self
pub fn short_flag(self, short: char) -> Self
Sets the short version of the subcommand flag without the preceding -
.
Allows the subcommand to be used as if it were an Arg::short
.
Examples
let matches = Command::new("pacman")
.subcommand(
Command::new("sync").short_flag('S').arg(
Arg::new("search")
.short('s')
.long("search")
.help("search remote repositories for matching strings"),
),
)
.get_matches_from(vec!["pacman", "-Ss"]);
assert_eq!(matches.subcommand_name().unwrap(), "sync");
let sync_matches = matches.subcommand_matches("sync").unwrap();
assert!(sync_matches.is_present("search"));
sourcepub fn long_flag(self, long: &'help str) -> Self
pub fn long_flag(self, long: &'help str) -> Self
Sets the long version of the subcommand flag without the preceding --
.
Allows the subcommand to be used as if it were an Arg::long
.
NOTE: Any leading -
characters will be stripped.
Examples
To set long_flag
use a word containing valid UTF-8 codepoints. If you supply a double leading
--
such as --sync
they will be stripped. Hyphens in the middle of the word; however,
will not be stripped (i.e. sync-file
is allowed).
let matches = Command::new("pacman")
.subcommand(
Command::new("sync").long_flag("sync").arg(
Arg::new("search")
.short('s')
.long("search")
.help("search remote repositories for matching strings"),
),
)
.get_matches_from(vec!["pacman", "--sync", "--search"]);
assert_eq!(matches.subcommand_name().unwrap(), "sync");
let sync_matches = matches.subcommand_matches("sync").unwrap();
assert!(sync_matches.is_present("search"));
sourcepub fn alias<S: Into<&'help str>>(self, name: S) -> Self
pub fn alias<S: Into<&'help str>>(self, name: S) -> Self
Sets a hidden alias to this subcommand.
This allows the subcommand to be accessed via either the original name, or this given alias. This is more efficient and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all aliased variants.
NOTE: Aliases defined with this method are hidden from the help
message. If you’re looking for aliases that will be displayed in the help
message, see Command::visible_alias
.
NOTE: When using aliases and checking for the existence of a
particular subcommand within an ArgMatches
struct, one only needs to
search for the original name and not all aliases.
Examples
let m = Command::new("myprog")
.subcommand(Command::new("test")
.alias("do-stuff"))
.get_matches_from(vec!["myprog", "do-stuff"]);
assert_eq!(m.subcommand_name(), Some("test"));
sourcepub fn short_flag_alias(self, name: char) -> Self
pub fn short_flag_alias(self, name: char) -> Self
Add an alias, which functions as “hidden” short flag subcommand
This will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.
Examples
let m = Command::new("myprog")
.subcommand(Command::new("test").short_flag('t')
.short_flag_alias('d'))
.get_matches_from(vec!["myprog", "-d"]);
assert_eq!(m.subcommand_name(), Some("test"));
sourcepub fn long_flag_alias(self, name: &'help str) -> Self
pub fn long_flag_alias(self, name: &'help str) -> Self
Add an alias, which functions as a “hidden” long flag subcommand.
This will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.
Examples
let m = Command::new("myprog")
.subcommand(Command::new("test").long_flag("test")
.long_flag_alias("testing"))
.get_matches_from(vec!["myprog", "--testing"]);
assert_eq!(m.subcommand_name(), Some("test"));
sourcepub fn aliases(self, names: &[&'help str]) -> Self
pub fn aliases(self, names: &[&'help str]) -> Self
Sets multiple hidden aliases to this subcommand.
This allows the subcommand to be accessed via either the original name or any of the given aliases. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command and not all aliased variants.
NOTE: Aliases defined with this method are hidden from the help
message. If looking for aliases that will be displayed in the help
message, see Command::visible_aliases
.
NOTE: When using aliases and checking for the existence of a
particular subcommand within an ArgMatches
struct, one only needs to
search for the original name and not all aliases.
Examples
let m = Command::new("myprog")
.subcommand(Command::new("test")
.aliases(&["do-stuff", "do-tests", "tests"]))
.arg(Arg::new("input")
.help("the file to add")
.required(false))
.get_matches_from(vec!["myprog", "do-tests"]);
assert_eq!(m.subcommand_name(), Some("test"));
sourcepub fn short_flag_aliases(self, names: &[char]) -> Self
pub fn short_flag_aliases(self, names: &[char]) -> Self
Add aliases, which function as “hidden” short flag subcommands.
These will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.
Examples
let m = Command::new("myprog")
.subcommand(Command::new("test").short_flag('t')
.short_flag_aliases(&['a', 'b', 'c']))
.arg(Arg::new("input")
.help("the file to add")
.required(false))
.get_matches_from(vec!["myprog", "-a"]);
assert_eq!(m.subcommand_name(), Some("test"));
sourcepub fn long_flag_aliases(self, names: &[&'help str]) -> Self
pub fn long_flag_aliases(self, names: &[&'help str]) -> Self
Add aliases, which function as “hidden” long flag subcommands.
These will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.
Examples
let m = Command::new("myprog")
.subcommand(Command::new("test").long_flag("test")
.long_flag_aliases(&["testing", "testall", "test_all"]))
.arg(Arg::new("input")
.help("the file to add")
.required(false))
.get_matches_from(vec!["myprog", "--testing"]);
assert_eq!(m.subcommand_name(), Some("test"));
sourcepub fn visible_alias<S: Into<&'help str>>(self, name: S) -> Self
pub fn visible_alias<S: Into<&'help str>>(self, name: S) -> Self
Sets a visible alias to this subcommand.
This allows the subcommand to be accessed via either the original name or the given alias. This is more efficient and easier than creating hidden subcommands as one only needs to check for the existence of this command and not all aliased variants.
NOTE: The alias defined with this method is visible from the help
message and displayed as if it were just another regular subcommand. If
looking for an alias that will not be displayed in the help message, see
Command::alias
.
NOTE: When using aliases and checking for the existence of a
particular subcommand within an ArgMatches
struct, one only needs to
search for the original name and not all aliases.
Examples
let m = Command::new("myprog")
.subcommand(Command::new("test")
.visible_alias("do-stuff"))
.get_matches_from(vec!["myprog", "do-stuff"]);
assert_eq!(m.subcommand_name(), Some("test"));
sourcepub fn visible_short_flag_alias(self, name: char) -> Self
pub fn visible_short_flag_alias(self, name: char) -> Self
Add an alias, which functions as “visible” short flag subcommand
This will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.
See also Command::short_flag_alias
.
Examples
let m = Command::new("myprog")
.subcommand(Command::new("test").short_flag('t')
.visible_short_flag_alias('d'))
.get_matches_from(vec!["myprog", "-d"]);
assert_eq!(m.subcommand_name(), Some("test"));
sourcepub fn visible_long_flag_alias(self, name: &'help str) -> Self
pub fn visible_long_flag_alias(self, name: &'help str) -> Self
Add an alias, which functions as a “visible” long flag subcommand.
This will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.
See also Command::long_flag_alias
.
Examples
let m = Command::new("myprog")
.subcommand(Command::new("test").long_flag("test")
.visible_long_flag_alias("testing"))
.get_matches_from(vec!["myprog", "--testing"]);
assert_eq!(m.subcommand_name(), Some("test"));
sourcepub fn visible_aliases(self, names: &[&'help str]) -> Self
pub fn visible_aliases(self, names: &[&'help str]) -> Self
Sets multiple visible aliases to this subcommand.
This allows the subcommand to be accessed via either the original name or any of the given aliases. This is more efficient and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command and not all aliased variants.
NOTE: The alias defined with this method is visible from the help
message and displayed as if it were just another regular subcommand. If
looking for an alias that will not be displayed in the help message, see
Command::alias
.
NOTE: When using aliases, and checking for the existence of a
particular subcommand within an ArgMatches
struct, one only needs to
search for the original name and not all aliases.
Examples
let m = Command::new("myprog")
.subcommand(Command::new("test")
.visible_aliases(&["do-stuff", "tests"]))
.get_matches_from(vec!["myprog", "do-stuff"]);
assert_eq!(m.subcommand_name(), Some("test"));
sourcepub fn visible_short_flag_aliases(self, names: &[char]) -> Self
pub fn visible_short_flag_aliases(self, names: &[char]) -> Self
Add aliases, which function as visible short flag subcommands.
See Command::short_flag_aliases
.
Examples
let m = Command::new("myprog")
.subcommand(Command::new("test").short_flag('b')
.visible_short_flag_aliases(&['t']))
.get_matches_from(vec!["myprog", "-t"]);
assert_eq!(m.subcommand_name(), Some("test"));
sourcepub fn visible_long_flag_aliases(self, names: &[&'help str]) -> Self
pub fn visible_long_flag_aliases(self, names: &[&'help str]) -> Self
Add aliases, which function as visible long flag subcommands.
See Command::long_flag_aliases
.
Examples
let m = Command::new("myprog")
.subcommand(Command::new("test").long_flag("test")
.visible_long_flag_aliases(&["testing", "testall", "test_all"]))
.get_matches_from(vec!["myprog", "--testing"]);
assert_eq!(m.subcommand_name(), Some("test"));
sourcepub fn display_order(self, ord: usize) -> Self
pub fn display_order(self, ord: usize) -> Self
Set the placement of this subcommand within the help.
Subcommands with a lower value will be displayed first in the help message. Subcommands with duplicate display orders will be displayed in alphabetical order.
This is helpful when one would like to emphasize frequently used subcommands, or prioritize those towards the top of the list.
NOTE: The default is 999 for all subcommands.
Examples
let m = Command::new("cust-ord")
.subcommand(Command::new("alpha") // typically subcommands are grouped
// alphabetically by name. Subcommands
// without a display_order have a value of
// 999 and are displayed alphabetically with
// all other 999 subcommands
.about("Some help and text"))
.subcommand(Command::new("beta")
.display_order(1) // In order to force this subcommand to appear *first*
// all we have to do is give it a value lower than 999.
// Any other subcommands with a value of 1 will be displayed
// alphabetically with this one...then 2 values, then 3, etc.
.about("I should be first!"))
.get_matches_from(vec![
"cust-ord", "--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
SUBCOMMANDS:
beta I should be first!
alpha Some help and text
sourcepub fn hide(self, yes: bool) -> Self
pub fn hide(self, yes: bool) -> Self
Specifies that this subcommand
should be hidden from help messages
Examples
Command::new("myprog")
.subcommand(
Command::new("test").hide(true)
)
sourcepub fn subcommand_required(self, yes: bool) -> Self
pub fn subcommand_required(self, yes: bool) -> Self
If no subcommand
is present at runtime, error and exit gracefully.
Examples
let err = Command::new("myprog")
.subcommand_required(true)
.subcommand(Command::new("test"))
.try_get_matches_from(vec![
"myprog",
]);
assert!(err.is_err());
assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand);
sourcepub fn allow_external_subcommands(self, yes: bool) -> Self
pub fn allow_external_subcommands(self, yes: bool) -> Self
Assume unexpected positional arguments are a subcommand
.
Arguments will be stored in the ""
argument in the ArgMatches
NOTE: Use this setting with caution, as a truly unexpected argument (i.e. one that is NOT an external subcommand) will not cause an error and instead be treated as a potential subcommand. One should check for such cases manually and inform the user appropriately.
NOTE: A built-in subcommand will be parsed as an external subcommand when escaped with
--
.
Examples
// Assume there is an external subcommand named "subcmd"
let m = Command::new("myprog")
.allow_external_subcommands(true)
.get_matches_from(vec![
"myprog", "subcmd", "--option", "value", "-fff", "--flag"
]);
// All trailing arguments will be stored under the subcommand's sub-matches using an empty
// string argument name
match m.subcommand() {
Some((external, ext_m)) => {
let ext_args: Vec<&str> = ext_m.values_of("").unwrap().collect();
assert_eq!(external, "subcmd");
assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
},
_ => {},
}
sourcepub fn allow_invalid_utf8_for_external_subcommands(self, yes: bool) -> Self
pub fn allow_invalid_utf8_for_external_subcommands(self, yes: bool) -> Self
Specifies that external subcommands that are invalid UTF-8 should not be treated as an error.
NOTE: Using external subcommand argument values with invalid UTF-8 requires using
ArgMatches::values_of_os
or ArgMatches::values_of_lossy
for those particular
arguments which may contain invalid UTF-8 values
NOTE: Setting this requires Command::allow_external_subcommands
Platform Specific
Non Windows systems only
Examples
// Assume there is an external subcommand named "subcmd"
let m = Command::new("myprog")
.allow_invalid_utf8_for_external_subcommands(true)
.allow_external_subcommands(true)
.get_matches_from(vec![
"myprog", "subcmd", "--option", "value", "-fff", "--flag"
]);
// All trailing arguments will be stored under the subcommand's sub-matches using an empty
// string argument name
match m.subcommand() {
Some((external, ext_m)) => {
let ext_args: Vec<&std::ffi::OsStr> = ext_m.values_of_os("").unwrap().collect();
assert_eq!(external, "subcmd");
assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
},
_ => {},
}
sourcepub fn args_conflicts_with_subcommands(self, yes: bool) -> Self
pub fn args_conflicts_with_subcommands(self, yes: bool) -> Self
Specifies that use of an argument prevents the use of subcommands
.
By default clap
allows arguments between subcommands such
as <cmd> [cmd_args] <subcmd> [subcmd_args] <subsubcmd> [subsubcmd_args]
.
This setting disables that functionality and says that arguments can only follow the final subcommand. For instance using this setting makes only the following invocations possible:
<cmd> <subcmd> <subsubcmd> [subsubcmd_args]
<cmd> <subcmd> [subcmd_args]
<cmd> [cmd_args]
Examples
Command::new("myprog")
.args_conflicts_with_subcommands(true);
sourcepub fn subcommand_precedence_over_arg(self, yes: bool) -> Self
pub fn subcommand_precedence_over_arg(self, yes: bool) -> Self
Prevent subcommands from being consumed as an arguments value.
By default, if an option taking multiple values is followed by a subcommand, the subcommand will be parsed as another value.
cmd --foo val1 val2 subcommand
--------- ----------
values another value
This setting instructs the parser to stop when encountering a subcommand instead of greedily consuming arguments.
cmd --foo val1 val2 subcommand
--------- ----------
values subcommand
Note: Make sure you apply it as global_setting
if you want this setting
to be propagated to subcommands and sub-subcommands!
Examples
let cmd = Command::new("cmd").subcommand(Command::new("sub")).arg(
Arg::new("arg")
.long("arg")
.multiple_values(true)
.takes_value(true),
);
let matches = cmd
.clone()
.try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
.unwrap();
assert_eq!(
matches.values_of("arg").unwrap().collect::<Vec<_>>(),
&["1", "2", "3", "sub"]
);
assert!(matches.subcommand_matches("sub").is_none());
let matches = cmd
.subcommand_precedence_over_arg(true)
.try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
.unwrap();
assert_eq!(
matches.values_of("arg").unwrap().collect::<Vec<_>>(),
&["1", "2", "3"]
);
assert!(matches.subcommand_matches("sub").is_some());
sourcepub fn subcommand_negates_reqs(self, yes: bool) -> Self
pub fn subcommand_negates_reqs(self, yes: bool) -> Self
Allows subcommands
to override all requirements of the parent command.
For example, if you had a subcommand or top level application with a required argument
that is only required as long as there is no subcommand present,
using this setting would allow you to set those arguments to Arg::required(true)
and yet receive no error so long as the user uses a valid subcommand instead.
NOTE: This defaults to false (using subcommand does not negate requirements)
Examples
This first example shows that it is an error to not use a required argument
let err = Command::new("myprog")
.subcommand_negates_reqs(true)
.arg(Arg::new("opt").required(true))
.subcommand(Command::new("test"))
.try_get_matches_from(vec![
"myprog"
]);
assert!(err.is_err());
assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
This next example shows that it is no longer error to not use a required argument if a valid subcommand is used.
let noerr = Command::new("myprog")
.subcommand_negates_reqs(true)
.arg(Arg::new("opt").required(true))
.subcommand(Command::new("test"))
.try_get_matches_from(vec![
"myprog", "test"
]);
assert!(noerr.is_ok());
sourcepub fn subcommand_value_name<S>(self, value_name: S) -> Self where
S: Into<&'help str>,
pub fn subcommand_value_name<S>(self, value_name: S) -> Self where
S: Into<&'help str>,
Sets the value name used for subcommands when printing usage and help.
By default, this is “SUBCOMMAND”.
See also Command::subcommand_help_heading
Examples
Command::new("myprog")
.subcommand(Command::new("sub1"))
.print_help()
will produce
myprog
USAGE:
myprog [SUBCOMMAND]
OPTIONS:
-h, --help Print help information
-V, --version Print version information
SUBCOMMANDS:
help Print this message or the help of the given subcommand(s)
sub1
but usage of subcommand_value_name
Command::new("myprog")
.subcommand(Command::new("sub1"))
.subcommand_value_name("THING")
.print_help()
will produce
myprog
USAGE:
myprog [THING]
OPTIONS:
-h, --help Print help information
-V, --version Print version information
SUBCOMMANDS:
help Print this message or the help of the given subcommand(s)
sub1
sourcepub fn subcommand_help_heading<T>(self, heading: T) -> Self where
T: Into<&'help str>,
pub fn subcommand_help_heading<T>(self, heading: T) -> Self where
T: Into<&'help str>,
Sets the help heading used for subcommands when printing usage and help.
By default, this is “SUBCOMMANDS”.
See also Command::subcommand_value_name
Examples
Command::new("myprog")
.subcommand(Command::new("sub1"))
.print_help()
will produce
myprog
USAGE:
myprog [SUBCOMMAND]
OPTIONS:
-h, --help Print help information
-V, --version Print version information
SUBCOMMANDS:
help Print this message or the help of the given subcommand(s)
sub1
but usage of subcommand_help_heading
Command::new("myprog")
.subcommand(Command::new("sub1"))
.subcommand_help_heading("THINGS")
.print_help()
will produce
myprog
USAGE:
myprog [SUBCOMMAND]
OPTIONS:
-h, --help Print help information
-V, --version Print version information
THINGS:
help Print this message or the help of the given subcommand(s)
sub1
sourceimpl<'help> App<'help>
impl<'help> App<'help>
sourcepub fn get_display_name(&self) -> Option<&str>
pub fn get_display_name(&self) -> Option<&str>
Get the name of the binary.
sourcepub fn get_bin_name(&self) -> Option<&str>
pub fn get_bin_name(&self) -> Option<&str>
Get the name of the binary.
sourcepub fn set_bin_name<S: Into<String>>(&mut self, name: S)
pub fn set_bin_name<S: Into<String>>(&mut self, name: S)
Set binary name. Uses &mut self
instead of self
.
sourcepub fn get_version(&self) -> Option<&'help str>
pub fn get_version(&self) -> Option<&'help str>
Get the version of the cmd.
sourcepub fn get_long_version(&self) -> Option<&'help str>
pub fn get_long_version(&self) -> Option<&'help str>
Get the long version of the cmd.
Get the authors of the cmd.
sourcepub fn get_short_flag(&self) -> Option<char>
pub fn get_short_flag(&self) -> Option<char>
Get the short flag of the subcommand.
sourcepub fn get_long_flag(&self) -> Option<&'help str>
pub fn get_long_flag(&self) -> Option<&'help str>
Get the long flag of the subcommand.
sourcepub fn get_about(&self) -> Option<&'help str>
pub fn get_about(&self) -> Option<&'help str>
Get the help message specified via Command::about
.
sourcepub fn get_long_about(&self) -> Option<&'help str>
pub fn get_long_about(&self) -> Option<&'help str>
Get the help message specified via Command::long_about
.
sourcepub fn get_help_heading(&self) -> Option<&'help str>
👎 Deprecated since 3.1.0: Replaced with App::get_next_help_heading
pub fn get_help_heading(&self) -> Option<&'help str>
Replaced with App::get_next_help_heading
Deprecated, replaced with Command::get_next_help_heading
sourcepub fn get_next_help_heading(&self) -> Option<&'help str>
pub fn get_next_help_heading(&self) -> Option<&'help str>
Get the custom section heading specified via Command::help_heading
.
sourcepub fn get_visible_aliases(&self) -> impl Iterator<Item = &'help str> + '_
pub fn get_visible_aliases(&self) -> impl Iterator<Item = &'help str> + '_
Iterate through the visible aliases for this subcommand.
sourcepub fn get_visible_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_
pub fn get_visible_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_
Iterate through the visible short aliases for this subcommand.
sourcepub fn get_visible_long_flag_aliases(
&self
) -> impl Iterator<Item = &'help str> + '_
pub fn get_visible_long_flag_aliases(
&self
) -> impl Iterator<Item = &'help str> + '_
Iterate through the visible long aliases for this subcommand.
sourcepub fn get_all_aliases(&self) -> impl Iterator<Item = &str> + '_
pub fn get_all_aliases(&self) -> impl Iterator<Item = &str> + '_
Iterate through the set of all the aliases for this subcommand, both visible and hidden.
sourcepub fn get_all_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_
pub fn get_all_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_
Iterate through the set of all the short aliases for this subcommand, both visible and hidden.
sourcepub fn get_all_long_flag_aliases(&self) -> impl Iterator<Item = &'help str> + '_
pub fn get_all_long_flag_aliases(&self) -> impl Iterator<Item = &'help str> + '_
Iterate through the set of all the long aliases for this subcommand, both visible and hidden.
sourcepub fn is_set(&self, s: AppSettings) -> bool
pub fn is_set(&self, s: AppSettings) -> bool
Check if the given AppSettings
variant is currently set on the Command
.
This checks both local and global settings.
sourcepub fn get_color(&self) -> ColorChoice
pub fn get_color(&self) -> ColorChoice
Should we color the output?
sourcepub fn get_subcommands(&self) -> impl Iterator<Item = &App<'help>>
pub fn get_subcommands(&self) -> impl Iterator<Item = &App<'help>>
Iterate through the set of subcommands, getting a reference to each.
sourcepub fn get_subcommands_mut(&mut self) -> impl Iterator<Item = &mut App<'help>>
pub fn get_subcommands_mut(&mut self) -> impl Iterator<Item = &mut App<'help>>
Iterate through the set of subcommands, getting a mutable reference to each.
sourcepub fn has_subcommands(&self) -> bool
pub fn has_subcommands(&self) -> bool
Returns true
if this Command
has subcommands.
sourcepub fn get_subcommand_help_heading(&self) -> Option<&str>
pub fn get_subcommand_help_heading(&self) -> Option<&str>
Returns the help heading for listing subcommands.
sourcepub fn get_subommand_help_heading(&self) -> Option<&str>
👎 Deprecated since 3.1.0: Replaced with App::get_subcommand_help_heading
pub fn get_subommand_help_heading(&self) -> Option<&str>
Replaced with App::get_subcommand_help_heading
Deprecated, replaced with App::get_subcommand_help_heading
sourcepub fn get_subcommand_value_name(&self) -> Option<&str>
pub fn get_subcommand_value_name(&self) -> Option<&str>
Returns the subcommand value name.
sourcepub fn get_before_help(&self) -> Option<&str>
pub fn get_before_help(&self) -> Option<&str>
Returns the help heading for listing subcommands.
sourcepub fn get_before_long_help(&self) -> Option<&str>
pub fn get_before_long_help(&self) -> Option<&str>
Returns the help heading for listing subcommands.
sourcepub fn get_after_help(&self) -> Option<&str>
pub fn get_after_help(&self) -> Option<&str>
Returns the help heading for listing subcommands.
sourcepub fn get_after_long_help(&self) -> Option<&str>
pub fn get_after_long_help(&self) -> Option<&str>
Returns the help heading for listing subcommands.
sourcepub fn find_subcommand<T>(&self, name: &T) -> Option<&App<'help>> where
T: PartialEq<str> + ?Sized,
pub fn find_subcommand<T>(&self, name: &T) -> Option<&App<'help>> where
T: PartialEq<str> + ?Sized,
Find subcommand such that its name or one of aliases equals name
.
This does not recurse through subcommands of subcommands.
sourcepub fn find_subcommand_mut<T>(&mut self, name: &T) -> Option<&mut App<'help>> where
T: PartialEq<str> + ?Sized,
pub fn find_subcommand_mut<T>(&mut self, name: &T) -> Option<&mut App<'help>> where
T: PartialEq<str> + ?Sized,
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.
sourcepub fn get_groups(&self) -> impl Iterator<Item = &ArgGroup<'help>>
pub fn get_groups(&self) -> impl Iterator<Item = &ArgGroup<'help>>
Iterate through the set of groups.
sourcepub fn get_arguments(&self) -> impl Iterator<Item = &Arg<'help>>
pub fn get_arguments(&self) -> impl Iterator<Item = &Arg<'help>>
Iterate through the set of arguments.
sourcepub fn get_positionals(&self) -> impl Iterator<Item = &Arg<'help>>
pub fn get_positionals(&self) -> impl Iterator<Item = &Arg<'help>>
Iterate through the positionals arguments.
sourcepub fn get_arg_conflicts_with(&self, arg: &Arg<'_>) -> Vec<&Arg<'help>>
pub fn get_arg_conflicts_with(&self, arg: &Arg<'_>) -> Vec<&Arg<'help>>
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
.
sourcepub fn is_no_binary_name_set(&self) -> bool
pub fn is_no_binary_name_set(&self) -> bool
Report whether Command::no_binary_name
is set
sourcepub fn is_dont_delimit_trailing_values_set(&self) -> bool
pub fn is_dont_delimit_trailing_values_set(&self) -> bool
Report whether Command::dont_delimit_trailing_values
is set
sourcepub fn is_disable_version_flag_set(&self) -> bool
pub fn is_disable_version_flag_set(&self) -> bool
Report whether Command::disable_version_flag
is set
sourcepub fn is_propagate_version_set(&self) -> bool
pub fn is_propagate_version_set(&self) -> bool
Report whether Command::propagate_version
is set
sourcepub fn is_next_line_help_set(&self) -> bool
pub fn is_next_line_help_set(&self) -> bool
Report whether Command::next_line_help
is set
sourcepub fn is_disable_help_flag_set(&self) -> bool
pub fn is_disable_help_flag_set(&self) -> bool
Report whether Command::disable_help_flag
is set
sourcepub fn is_disable_help_subcommand_set(&self) -> bool
pub fn is_disable_help_subcommand_set(&self) -> bool
Report whether Command::disable_help_subcommand
is set
sourcepub fn is_disable_colored_help_set(&self) -> bool
pub fn is_disable_colored_help_set(&self) -> bool
Report whether Command::disable_colored_help
is set
sourcepub fn is_dont_collapse_args_in_usage_set(&self) -> bool
pub fn is_dont_collapse_args_in_usage_set(&self) -> bool
Report whether Command::dont_collapse_args_in_usage
is set
sourcepub fn is_arg_required_else_help_set(&self) -> bool
pub fn is_arg_required_else_help_set(&self) -> bool
Report whether Command::arg_required_else_help
is set
sourcepub fn is_allow_negative_numbers_set(&self) -> bool
pub fn is_allow_negative_numbers_set(&self) -> bool
Report whether Command::allow_negative_numbers
is set
sourcepub fn is_trailing_var_arg_set(&self) -> bool
pub fn is_trailing_var_arg_set(&self) -> bool
Report whether Command::trailing_var_arg
is set
sourcepub fn is_allow_missing_positional_set(&self) -> bool
pub fn is_allow_missing_positional_set(&self) -> bool
Report whether Command::allow_missing_positional
is set
sourcepub fn is_hide_set(&self) -> bool
pub fn is_hide_set(&self) -> bool
Report whether Command::hide
is set
sourcepub fn is_subcommand_required_set(&self) -> bool
pub fn is_subcommand_required_set(&self) -> bool
Report whether Command::subcommand_required
is set
sourcepub fn is_allow_external_subcommands_set(&self) -> bool
pub fn is_allow_external_subcommands_set(&self) -> bool
Report whether Command::allow_external_subcommands
is set
sourcepub fn is_allow_invalid_utf8_for_external_subcommands_set(&self) -> bool
pub fn is_allow_invalid_utf8_for_external_subcommands_set(&self) -> bool
Report whether Command::allow_invalid_utf8_for_external_subcommands
is set
sourcepub fn is_args_conflicts_with_subcommands_set(&self) -> bool
pub fn is_args_conflicts_with_subcommands_set(&self) -> bool
Report whether Command::args_conflicts_with_subcommands
is set
sourcepub fn is_subcommand_precedence_over_arg_set(&self) -> bool
pub fn is_subcommand_precedence_over_arg_set(&self) -> bool
Report whether Command::subcommand_precedence_over_arg
is set
sourcepub fn is_subcommand_negates_reqs_set(&self) -> bool
pub fn is_subcommand_negates_reqs_set(&self) -> bool
Report whether Command::subcommand_negates_reqs
is set
Trait Implementations
impl<'help> Eq for App<'help>
impl<'help> StructuralEq for App<'help>
impl<'help> StructuralPartialEq for App<'help>
Auto Trait Implementations
impl<'help> RefUnwindSafe for App<'help>
impl<'help> Send for App<'help>
impl<'help> Sync for App<'help>
impl<'help> Unpin for App<'help>
impl<'help> UnwindSafe for App<'help>
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<Q, K> Equivalent<K> for Q where
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
impl<Q, K> Equivalent<K> for Q where
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
sourcefn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
Compare self to key
and return true
if they are equal.
sourceimpl<T> ToOwned for T where
T: Clone,
impl<T> ToOwned for T where
T: Clone,
type Owned = T
type Owned = T
The resulting type after obtaining ownership.
sourcefn clone_into(&self, target: &mut T)
fn clone_into(&self, target: &mut T)
toowned_clone_into
)Uses borrowed data to replace owned data, usually by cloning. Read more