pub struct App<'help> { /* private fields */ }
Expand description
Represents a command line interface which is made up of all possible
command line arguments and subcommands. Interface arguments and settings are
configured using the “builder pattern.” Once all configuration is complete,
the App::get_matches
family of methods starts the runtime-parsing
process. These methods then return information about the user supplied
arguments (or lack thereof).
NOTE: There aren’t any mandatory “options” that one must set. The “options” may
also appear in any order (so long as one of the App::get_matches
methods is the last method
called).
Examples
let m = App::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").index(1)
)
.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
sourceimpl<'help> App<'help>
impl<'help> App<'help>
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<&str>
pub fn get_long_flag(&self) -> Option<&str>
Get the long flag of the subcommand.
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_about(&self) -> Option<&str>
pub fn get_about(&self) -> Option<&str>
Get the help message specified via App::about
.
sourcepub fn get_long_about(&self) -> Option<&str>
pub fn get_long_about(&self) -> Option<&str>
Get the help message specified via App::long_about
.
sourcepub fn get_help_heading(&self) -> Option<&'help str>
pub fn get_help_heading(&self) -> Option<&'help str>
Get the custom section heading specified via App::help_heading
.
sourcepub fn get_visible_aliases(&self) -> impl Iterator<Item = &str>
pub fn get_visible_aliases(&self) -> impl Iterator<Item = &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 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 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 App
.
sourcepub fn is_set(&self, s: AppSettings) -> bool
pub fn is_set(&self, s: AppSettings) -> bool
Returns true
if the given AppSettings
variant is currently set in
this App
(checks both local and global settings).
sourcepub fn has_subcommands(&self) -> bool
pub fn has_subcommands(&self) -> bool
Returns true
if this App
has subcommands.
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 App
requiring a name
.
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.
An App
represents a command line interface (CLI) which is made up of
all possible command line arguments and subcommands. “Subcommands” are
sub-CLIs with their own arguments, settings, and even subcommands
forming a sort of hierarchy.
Examples
App::new("My Program")
Sets a string of author(s) that will be displayed to the user when they request 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.
See the examples/
directory for more information.
Examples
App::new("myprog")
.author("Me, me@mymain.com")
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. 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.
Normally, the binary name is used in help and error messages. clap
automatically determines the binary name at runtime, however by manually
setting the binary name, one can effectively override what will be
displayed in the help or error messages.
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
App::new("My Program")
.bin_name("my_binary")
sourcepub fn about<S: Into<&'help str>>(self, about: S) -> Self
pub fn about<S: Into<&'help str>>(self, about: S) -> Self
Sets a string describing what the program does. This will be displayed
when the user requests the short format help message (-h
).
clap
can display two different help messages, a long format and a
short format depending on whether the user used -h
(short) or
--help
(long). This method sets the message during the short format
(-h
) message. However, if no long format message is configured, this
message will be displayed for both the long format, or short format
help message.
NOTE: Only App::about
(short format) is used in completion
script generation in order to be concise.
Examples
App::new("myprog")
.about("Does really amazing things for great people")
sourcepub fn long_about<S: Into<&'help str>>(self, about: S) -> Self
pub fn long_about<S: Into<&'help str>>(self, about: S) -> Self
Sets a long format string describing what the program does. This will be
displayed when the user requests the long format help message (--help
).
Advanced
clap
can display two different help messages, a long format and a
short format depending on whether the user used -h
(short) or
--help
(long). This method sets the message during the long format
(--help
) message. However, if no short format message is configured,
this message will be displayed for both the long format, or short
format help message.
NOTE: Only App::about
(short format) is used in completion
script generation in order to be concise.
Examples
App::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 name<S: Into<String>>(self, name: S) -> Self
pub fn name<S: Into<String>>(self, name: S) -> Self
(Re)Sets the program’s name. This will be displayed when displaying help or version messages.
Pro-tip: This function is particularly useful when configuring a
program via App::from(yaml)
in conjunction with the crate_name!
macro to derive the program’s name from its Cargo.toml
.
Examples
let yaml = load_yaml!("app.yaml");
let app = App::from(yaml)
.name(crate_name!());
// continued logic goes here, such as `app.get_matches()` etc.
sourcepub fn after_help<S: Into<&'help str>>(self, help: S) -> Self
pub fn after_help<S: Into<&'help str>>(self, help: S) -> Self
Adds additional help information to be displayed at the end of the auto-generated help. This is often used to describe how to use the arguments, caveats to be noted, or license and contact information.
NOTE: If only after_long_help
is provided, and not App::after_help
but the user requests
-h
clap will still display the contents of after_help
appropriately.
Examples
App::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
Adds additional help information to be displayed in addition to auto-generated help. This
information is displayed after the auto-generated help information and is meant to be
more verbose than after_help
. This is often used to describe how to use the arguments, or
caveats to be noted in man pages.
NOTE: If only after_help
is provided, and not App::after_long_help
but the user
requests --help
, clap will still display the contents of after_help
appropriately.
Examples
App::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
Adds additional help information to be displayed prior to the auto-generated help. This is often used for header, copyright, or license information.
NOTE: If only before_long_help
is provided, and not App::before_help
but the user
requests -h
clap will still display the contents of before_long_help
appropriately.
Examples
App::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
Adds additional help information to be displayed prior to the auto-generated help. This is often used for header, copyright, or license information.
NOTE: If only before_help
is provided, and not App::before_long_help
but the user
requests --help
, clap will still display the contents of before_help
appropriately.
Examples
App::new("myprog")
.before_long_help("Some verbose and long info I'd like to appear before the help info")
sourcepub fn short_flag(self, short: char) -> Self
pub fn short_flag(self, short: char) -> Self
Allows the subcommand to be used as if it were an Arg::short
.
Sets the short version of the subcommand flag without the preceding -
.
Examples
let matches = App::new("pacman")
.subcommand(
App::new("sync").short_flag('S').arg(
Arg::new("search")
.short('s')
.long("search")
.about("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
Allows the subcommand to be used as if it were an Arg::long
.
Sets the long version of the subcommand flag without the preceding --
.
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 = App::new("pacman")
.subcommand(
App::new("sync").long_flag("sync").arg(
Arg::new("search")
.short('s')
.long("search")
.about("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 version<S: Into<&'help str>>(self, ver: S) -> Self
pub fn version<S: Into<&'help str>>(self, ver: S) -> Self
Sets a string of the version number to be displayed when displaying the
short format version message (-V
) or the help message.
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. See the examples/
directory for more
information.
clap
can display two different version messages, a [long format] and a
[short format] depending on whether the user used -V
(short) or
--version
(long). This method sets the message during the short format
(-V
). However, if no long format message is configured, this
message will be displayed for both the long format, or short format
version message.
Examples
App::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 a string of the version number to be displayed when the user
requests the long format version message (--version
) or the help
message.
This is often used to display things such as commit ID, or compile time configured options.
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. See the examples/
directory for more
information.
clap
can display two different version messages, a [long format] and a
[short format] depending on whether the user used -V
(short) or
--version
(long). This method sets the message during the long format
(--version
). However, if no short format message is configured, this
message will be displayed for both the long format, or short format
version message.
Examples
App::new("myprog")
.long_version(
"v0.1.24
commit: abcdef89726d
revision: 123
release: 2
binary: myprog")
sourcepub fn license<S: Into<&'help str>>(self, license: S) -> Self
pub fn license<S: Into<&'help str>>(self, license: S) -> Self
Sets a string of the license to be displayed when displaying help information.
Pro-tip: Use clap
s convenience macro crate_license!
to automatically set your
application’s license to the same thing as your crate at compile time. See the
examples/
directory for more information
Examples
App::new("myprog")
.license("MIT OR Apache-2.0")
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.
This will be displayed to the user when errors are found in argument parsing.
CAUTION: Using this setting disables clap
s “context-aware” usage
strings. After this setting is set, this will be the only usage string
displayed to the user!
NOTE: This will not replace the entire help message, only the portion showing the usage.
Examples
App::new("myprog")
.override_usage("myapp [-clDas] <some_file>")
sourcepub fn usage<S: Into<&'help str>>(self, usage: S) -> Self
👎 Deprecated since 3.0.0: Replaced with App::override_usage
pub fn usage<S: Into<&'help str>>(self, usage: S) -> Self
Replaced with App::override_usage
Deprecated, see App::override_usage
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. This should only be used
when the auto-generated message does not suffice.
This will be displayed to the user when they use --help
or -h
.
NOTE: This replaces the entire help message, so nothing will be auto-generated.
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 App::override_help
for
them as well.
Examples
App::new("myapp")
.override_help("myapp v1.0\n\
Does awesome things\n\
(C) me@mail.com\n\n\
USAGE: myapp <opts> <comamnd>\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\
Commmands:\n\
help Print this message\n\
work Do some work")
sourcepub fn help<S: Into<&'help str>>(self, help: S) -> Self
👎 Deprecated since 3.0.0: Replaced with App::override_help
pub fn help<S: Into<&'help str>>(self, help: S) -> Self
Replaced with App::override_help
Deprecated, see App::override_help
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:
{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 (fromApp::about
orApp::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
orApp::after_long_help
.{before-help}
- Help fromApp::before_help
orApp::before_long_help
.
Examples
App::new("myprog")
.version("1.0")
.help_template("{bin} ({version}) - {usage}")
sourcepub fn template<S: Into<&'help str>>(self, s: S) -> Self
👎 Deprecated since 3.0.0: Replaced with App::help_template
pub fn template<S: Into<&'help str>>(self, s: S) -> Self
Replaced with App::help_template
Deprecated, see App::help_template
sourcepub fn setting<F>(self, setting: F) -> Self where
F: Into<AppFlags>,
pub fn setting<F>(self, setting: F) -> Self where
F: Into<AppFlags>,
Enables a single settings for the current (this App
instance) command or subcommand.
See AppSettings
for a full list of possibilities and examples.
Examples
App::new("myprog")
.setting(AppSettings::SubcommandRequired)
.setting(AppSettings::WaitOnError)
App::new("myprog")
.setting(AppSettings::SubcommandRequired | AppSettings::WaitOnError)
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>,
Disables a single setting for the current (this App
instance) command or subcommand.
See AppSettings
for a full list of possibilities and examples.
Examples
App::new("myprog")
.unset_setting(AppSettings::SubcommandRequired)
.unset_setting(AppSettings::WaitOnError)
App::new("myprog")
.unset_setting(AppSettings::SubcommandRequired | AppSettings::WaitOnError)
sourcepub fn global_setting(self, setting: AppSettings) -> Self
pub fn global_setting(self, setting: AppSettings) -> Self
Enables a single setting that is propagated down through all child subcommands.
See AppSettings
for a full list of possibilities and examples.
NOTE: The setting is only propagated down and not up through parent commands.
Examples
App::new("myprog")
.global_setting(AppSettings::SubcommandRequired)
sourcepub fn unset_global_setting(self, setting: AppSettings) -> Self
pub fn unset_global_setting(self, setting: AppSettings) -> Self
Disables a global setting, and stops propagating down to child subcommands.
See AppSettings
for a full list of possibilities and examples.
NOTE: The setting being unset will be unset from both local and global settings.
Examples
App::new("myprog")
.unset_global_setting(AppSettings::AllowNegativeNumbers)
sourcepub fn color(self, color: ColorChoice) -> Self
pub fn color(self, color: ColorChoice) -> Self
Sets the behaviour of colored output during runtime.
NOTE: This choice is propagated to all child subcommands.
NOTE: Default behaviour is ColorChoice::Auto
.
Examples
App::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. Defaults to
100
. Using 0
will ignore terminal widths and use source formatting.
clap
automatically tries to determine the terminal width on Unix,
Linux, OSX and Windows if the wrap_help
cargo “feature” has been enabled
at compile time. If the terminal width cannot be determined, clap
fall back to 100
.
NOTE: This setting applies globally and not on a per-command basis.
NOTE: This setting must be set before any subcommands are added!
Platform Specific
Only Unix, Linux, OSX and Windows support automatic determination of terminal width. Even on those platforms, this setting is useful if for any reason the terminal width cannot be determined.
Examples
App::new("myprog")
.term_width(80)
sourcepub fn set_term_width(self, width: usize) -> Self
👎 Deprecated since 3.0.0: Replaced with App::term_width
pub fn set_term_width(self, width: usize) -> Self
Replaced with App::term_width
Deprecated, see App::term_width
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. Using 0
will ignore terminal widths and use source formatting.
clap
automatically tries to determine the terminal width on Unix,
Linux, OSX and Windows if the wrap_help
cargo “feature” has been
enabled at compile time, but one might want to limit the size to some
maximum (e.g. when the terminal is running fullscreen).
NOTE: This setting applies globally and not on a per-command basis.
NOTE: This setting must be set before any subcommands are added!
Platform Specific
Only Unix, Linux, OSX and Windows support automatic determination of terminal width.
Examples
App::new("myprog")
.max_term_width(100)
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
App::new("myprog")
// Adding a single "flag" argument with a short and help text, using Arg::new()
.arg(
Arg::new("debug")
.short('d')
.about("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::from("-c --config=[CONFIG] 'Optionally sets a config file to use'")
)
sourcepub fn help_heading<O>(self, heading: O) -> Self where
O: Into<Option<&'help str>>,
pub fn 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.
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 arg_from_usage(self, usage: &'help str) -> Self
👎 Deprecated since 3.0.0: Replaced with App::arg
pub fn arg_from_usage(self, usage: &'help str) -> Self
Replaced with App::arg
Deprecated, see App::arg
sourcepub fn alias<S: Into<&'help str>>(self, name: S) -> Self
pub fn alias<S: Into<&'help str>>(self, name: S) -> Self
If this App
instance is a subcommand, this method adds an alias, which
allows this 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 App::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 = App::new("myprog")
.subcommand(App::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
Allows adding an alias, which function as “hidden” short flag subcommands that 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 = App::new("myprog")
.subcommand(App::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
Allows adding an alias, which function as “hidden” long flag subcommands that 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 = App::new("myprog")
.subcommand(App::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
If this App
instance is a subcommand, this method adds a multiple
aliases, which allows this 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 App::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 = App::new("myprog")
.subcommand(App::new("test")
.aliases(&["do-stuff", "do-tests", "tests"]))
.arg(Arg::new("input")
.about("the file to add")
.index(1)
.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
Allows adding aliases, which function as “hidden” short flag subcommands that 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 = App::new("myprog")
.subcommand(App::new("test").short_flag('t')
.short_flag_aliases(&['a', 'b', 'c']))
.arg(Arg::new("input")
.about("the file to add")
.index(1)
.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
Allows adding aliases, which function as “hidden” long flag subcommands that 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 = App::new("myprog")
.subcommand(App::new("test").long_flag("test")
.long_flag_aliases(&["testing", "testall", "test_all"]))
.arg(Arg::new("input")
.about("the file to add")
.index(1)
.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
If this App
instance is a subcommand, this method adds a visible
alias, which allows this 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
App::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 = App::new("myprog")
.subcommand(App::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
Allows adding an alias that functions exactly like those defined with
App::short_flag_alias
, except that they are visible inside the help message.
Examples
let m = App::new("myprog")
.subcommand(App::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
Allows adding an alias that functions exactly like those defined with
App::long_flag_alias
, except that they are visible inside the help message.
Examples
let m = App::new("myprog")
.subcommand(App::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
If this App
instance is a subcommand, this method adds multiple visible
aliases, which allows this 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
App::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 = App::new("myprog")
.subcommand(App::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
Allows adding multiple short flag aliases that functions exactly like those defined
with App::short_flag_aliases
, except that they are visible inside the help message.
Examples
let m = App::new("myprog")
.subcommand(App::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
Allows adding multiple long flag aliases that functions exactly like those defined
with App::long_flag_aliases
, except that they are visible inside the help message.
Examples
let m = App::new("myprog")
.subcommand(App::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 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.
For instance, you can make an entire ArgGroup
required, meaning that one (and only
one) argument from that group must be present at runtime.
You can also do things such as 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.
Another added benefit of ArgGroup
s is that you can extract a value from a group instead
of determining exactly which argument was used.
Finally, using ArgGroup
s to ensure exclusion between arguments is another very common
use.
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.
App::new("app")
.arg("--set-ver [ver] 'set the version manually'")
.arg("--major 'auto increase major'")
.arg("--minor 'auto increase minor'")
.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 App
at once.
Examples
App::new("app")
.arg("--set-ver [ver] 'set the version manually'")
.arg("--major 'auto increase major'")
.arg("--minor 'auto increase minor'")
.arg("--patch 'auto increase patch'")
.arg("-c [FILE] 'a config file'")
.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-App
s, because they can contain their own arguments, subcommands, version, usage,
etc. They also function just like App
s, in that they get their own auto generated help,
version, and usage.
Examples
App::new("myprog")
.subcommand(App::new("config")
.about("Controls configuration features")
.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 by iterating over an
IntoIterator
of App
s.
Examples
.subcommands( vec![
App::new("config").about("Controls configuration functionality")
.arg(Arg::new("config_file").index(1)),
App::new("debug").about("Controls debug functionality")])
sourcepub fn display_order(self, ord: usize) -> Self
pub fn display_order(self, ord: usize) -> Self
Allows custom ordering of subcommands within the help message. Subcommands with a lower value will be displayed first in the help message. This is helpful when one would like to emphasize frequently used subcommands, or prioritize those towards the top of the list. Duplicate values are allowed. Subcommands with duplicate display orders will be displayed in alphabetical order.
NOTE: The default is 999 for all subcommands.
Examples
let m = App::new("cust-ord")
.subcommand(App::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(App::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 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 an App
.
Examples
let mut app = App::new("foo")
.arg(Arg::new("bar")
.short('b'))
.mut_arg("bar", |a| a.short('B'));
let res = app.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 = app.try_get_matches_from_mut(vec!["foo", "-B"]);
assert!(res.is_ok());
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 app = App::new("myprog");
let err = app.error(ErrorKind::InvalidValue, "Some failure case");
sourcepub fn print_help(&mut self) -> Result<()>
pub fn print_help(&mut self) -> Result<()>
Prints the full help message to io::stdout()
using a BufWriter
using the same
method as if someone ran -h
to request the help message.
NOTE: clap has the ability to distinguish between “short” and “long” help messages
depending on if the user ran -h
(short) or --help
(long).
Examples
let mut app = App::new("myprog");
app.print_help();
sourcepub fn print_long_help(&mut self) -> Result<()>
pub fn print_long_help(&mut self) -> Result<()>
Prints the full help message to io::stdout()
using a BufWriter
using the same
method as if someone ran --help
to request the help message.
NOTE: clap has the ability to distinguish between “short” and “long” help messages
depending on if the user ran -h
(short) or --help
(long).
Examples
let mut app = App::new("myprog");
app.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 full help message to the user to a io::Write
object in the same method as if
the user ran -h
.
NOTE: clap has the ability to distinguish between “short” and “long” help messages
depending on if the user ran -h
(short) or --help
(long).
Examples
use std::io;
let mut app = App::new("myprog");
let mut out = io::stdout();
app.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 full help message to the user to a io::Write
object in the same method as if
the user ran --help
.
NOTE: clap has the ability to distinguish between “short” and “long” help messages
depending on if the user ran -h
(short) or --help
(long).
Examples
use std::io;
let mut app = App::new("myprog");
let mut out = io::stdout();
app.write_long_help(&mut out).expect("failed to write to stdout");
sourcepub fn render_version(&self) -> String
pub fn render_version(&self) -> String
Returns the version message rendered as if the user ran -V
.
NOTE: clap has the ability to distinguish between “short” and “long” version messages
depending on if the user ran -V
(short) or --version
(long).
Coloring
This function does not try to color the message nor it inserts any ANSI escape codes.
Examples
use std::io;
let app = App::new("myprog");
println!("{}", app.render_version());
sourcepub fn render_long_version(&self) -> String
pub fn render_long_version(&self) -> String
Returns the version message rendered as if the user ran --version
.
NOTE: clap has the ability to distinguish between “short” and “long” version messages
depending on if the user ran -V
(short) or --version
(long).
Coloring
This function does not try to color the message nor it inserts any ANSI escape codes.
Examples
use std::io;
let app = App::new("myprog");
println!("{}", app.render_long_version());
sourcepub fn render_usage(&mut self) -> String
pub fn render_usage(&mut self) -> String
Returns the usage statement
Examples
use std::io;
let mut app = App::new("myprog");
println!("{}", app.render_usage());
sourcepub fn get_matches(self) -> ArgMatches
pub fn get_matches(self) -> ArgMatches
Starts the parsing process, upon a failed parse an error will be displayed to the user and
the process will exit with the appropriate error code. By default this method gets all user
provided arguments from env::args_os
in order to allow for invalid UTF-8 code points,
which are legal on many platforms.
Examples
let matches = App::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
Starts the parsing process, just like App::get_matches
but doesn’t consume the App
.
Examples
let mut app = App::new("myprog")
// Args and options go here...
;
let matches = app.get_matches_mut();
sourcepub fn try_get_matches(self) -> ClapResult<ArgMatches>
pub fn try_get_matches(self) -> ClapResult<ArgMatches>
Starts the parsing process. This method will return a clap::Result
type instead of exiting
the process on failed parse. By default this method gets matches from env::args_os
.
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
.
Examples
let matches = App::new("myprog")
// Args and options go here...
.try_get_matches()
.unwrap_or_else(|e| e.exit());
sourcepub fn get_matches_safe(self) -> ClapResult<ArgMatches>
👎 Deprecated since 3.0.0: Replaced with App::try_get_matches
pub fn get_matches_safe(self) -> ClapResult<ArgMatches>
Replaced with App::try_get_matches
Deprecated, see App::try_get_matches
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,
Starts the parsing process. Like App::get_matches
this method does not return a clap::Result
and will automatically exit with an error message. This method, however, lets you specify
what iterator to use when performing matches, such as a Vec
of your making.
NOTE: The first argument will be parsed as the binary name unless
AppSettings::NoBinaryName
is used.
Examples
let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
let matches = App::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,
Starts the parsing process. A combination of App::get_matches_from
, and
App::try_get_matches
.
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
AppSettings::NoBinaryName
is used.
Examples
let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
let matches = App::new("myprog")
// Args and options go here...
.try_get_matches_from(arg_vec)
.unwrap_or_else(|e| e.exit());
sourcepub fn get_matches_from_safe<I, T>(self, itr: I) -> ClapResult<ArgMatches> where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
👎 Deprecated since 3.0.0: Replaced with App::try_get_matches_from
pub fn get_matches_from_safe<I, T>(self, itr: I) -> ClapResult<ArgMatches> where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
Replaced with App::try_get_matches_from
Deprecated, see App::try_get_matches_from
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,
Starts the parsing process without consuming the App
struct self
. This is normally not
the desired functionality, instead prefer App::try_get_matches_from
which does
consume self
.
NOTE: The first argument will be parsed as the binary name unless
AppSettings::NoBinaryName
is used.
Examples
let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
let mut app = App::new("myprog");
// Args and options go here...
let matches = app.try_get_matches_from_mut(arg_vec)
.unwrap_or_else(|e| e.exit());
sourcepub fn get_matches_from_safe_borrow<I, T>(
&mut self,
itr: I
) -> ClapResult<ArgMatches> where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
👎 Deprecated since 3.0.0: Replaced with App::try_get_matches_from_mut
pub fn get_matches_from_safe_borrow<I, T>(
&mut self,
itr: I
) -> ClapResult<ArgMatches> where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
Replaced with App::try_get_matches_from_mut
Deprecated, see App::try_get_matches_from_mut
sourcepub fn subcommand_placeholder<S, T>(self, placeholder: S, header: T) -> Self where
S: Into<&'help str>,
T: Into<&'help str>,
pub fn subcommand_placeholder<S, T>(self, placeholder: S, header: T) -> Self where
S: Into<&'help str>,
T: Into<&'help str>,
Sets the placeholder text used for subcommands when printing usage and help. By default, this is “SUBCOMMAND” with a header of “SUBCOMMANDS”.
Examples
App::new("myprog")
.subcommand(App::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_placeholder
App::new("myprog")
.subcommand(App::new("sub1"))
.subcommand_placeholder("THING", "THINGS")
.print_help()
will produce
myprog
USAGE:
myprog [THING]
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
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 · sourcepub fn borrow_mut(&mut self) -> &mut T
pub 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,
sourcepub fn equivalent(&self, key: &K) -> bool
pub 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.
sourcepub fn to_owned(&self) -> T
pub fn to_owned(&self) -> T
Creates owned data from borrowed data, usually by cloning. Read more
sourcepub fn clone_into(&self, target: &mut T)
pub fn clone_into(&self, target: &mut T)
toowned_clone_into
)Uses borrowed data to replace owned data, usually by cloning. Read more