Struct clap::App
[−]
[src]
pub struct App<'a, 'v, 'ab, 'u, 'h, 'ar> { // some fields omitted }
Used to create a representation of a command line program and all possible command line arguments.
Application settings are set using the "builder pattern" with .get_matches()
being the
terminal method that starts the runtime-parsing process and returns information about
the user supplied arguments (or lack there of).
There aren't any mandatory "options" that one must set. The "options" may also appear in any
order (so long as .get_matches()
is the last method called).
Examples
let matches = App::new("myprog") .author("Me, me@mail.com") .version("1.0.2") .about("Explains in brief what the program does") .arg( Arg::with_name("in_file").index(1) ) .after_help("Longer explaination to appear after the options when \ displaying the help information from --help or -h") .get_matches(); // Your program logic starts here...
Methods
impl<'a, 'v, 'ab, 'u, 'h, 'ar> App<'a, 'v, 'ab, 'u, 'h, 'ar>
fn new(n: &'ar str) -> Self
Creates a new instance of an application requiring a name (such as the binary). The name will be displayed to the user when they request to print version or help and usage information. The name should not contain spaces (hyphens '-' are ok).
Examples
let prog = App::new("myprog")
fn author(self, a: &'a str) -> Self
Sets a string of author(s) and will be displayed to the user when they request the help
information with --help
or -h
.
Examples
App::new("myprog") .author("Me, me@mymain.com")
fn bin_name(self, a: &str) -> Self
Overrides the system-determined binary name. This should only be used when absolutely neccessary, such as the binary name for your application is misleading, or perhaps not how the user should invoke your program.
NOTE: This command should not be used for SubCommands.
Examples
App::new("myprog") .bin_name("my_binary")
fn about(self, a: &'ab str) -> Self
Sets a string briefly describing what the program does and will be displayed when displaying help information.
Examples
App::new("myprog") .about("Does really amazing things to great people")
fn after_help(self, h: &'h str) -> Self
Adds additional help information to be displayed in addition to and directly after auto-generated help. This information is displayed after the auto-generated help information. This additional help is often used to describe how to use the arguments, or caveats to be noted.
Examples
App::new("myprog") .after_help("Does really amazing things to great people")
fn subcommands_negate_reqs(self, n: bool) -> Self
Allows subcommands to override all requirements of the parent (this command). For example if you had a subcommand or even top level application which had a required arguments that are only required as long as there is no subcommand present.
Deprecated: Use App::setting()
with AppSettings::SubcommandsNegateReqs
instead.
This method will be removed at 2.x
NOTE: This defaults to false (using subcommand does not negate requirements)
Examples
App::new("myprog") .subcommands_negate_reqs(true)
fn subcommand_required(self, n: bool) -> Self
Allows specifying that if no subcommand is present at runtime, error and exit gracefully
Deprecated: Use App::setting()
with AppSettings::SubcommandRequired
instead. This
method will be removed at 2.x
NOTE: This defaults to false (subcommands do not need to be present)
Examples
App::new("myprog") .subcommand_required(true)
fn version(self, v: &'v str) -> Self
Sets a string of the version number to be displayed when displaying version or help information.
Examples
App::new("myprog") .version("v0.1.24")
fn usage(self, u: &'u str) -> Self
Sets a custom usage string to override the auto-generated usage string.
This will be displayed to the user when errors are found in argument parsing, or when you
call ArgMatcher::usage()
NOTE: You do not need to specify the "USAGE: \n\t" portion, as that will
still be applied by clap
, you only need to specify the portion starting
with the binary name.
NOTE: This will not replace the entire help message, only the portion showing the usage.
Examples
App::new("myprog") .usage("myapp [-clDas] <some_file>")
fn help(self, h: &'u str) -> Self
Sets a custom help message and overrides the auto-generated one. This should only be used when the auto-generated message does not suffice.
This will be displayed to the user when they use the default --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 .help()
for them as well.
Examples
App::new("myapp") .help("myapp v1.0\n\ Does awesome things\n\ (C) me@mail.com\n\n\ USAGE: myapp <opts> <comamnd>\n\n\ Options:\n\ -h, --helpe Dispay this message\n\ -V, --version Display version info\n\ -s <stuff> Do something with stuff\n\ -v Be verbose\n\n\ Commmands:\n\ help Prints this message\n\ work Do some work")
fn help_short(self, s: &str) -> Self
Sets the short version of the help
argument without the preceding -
.
By default clap
automatically assigns h
, but this can be overridden
NOTE: Any leading -
characters will be stripped, and only the first
non -
chacter will be used as the short
version
Examples
App::new("myprog") // Using an uppercase `H` instead of the default lowercase `h` .help_short("H")
fn version_short(self, s: &str) -> Self
Sets the short version of the version
argument without the preceding -
.
By default clap
automatically assigns V
, but this can be overridden
NOTE: Any leading -
characters will be stripped, and only the first
non -
chacter will be used as the short
version
Examples
App::new("myprog") // Using a lowercase `v` instead of the default capital `V` .version_short("v")
fn arg_required_else_help(self, tf: bool) -> Self
Specifies that the help text sould be displayed (and then exit gracefully), if no
arguments are present at runtime (i.e. an empty run such as, $ myprog
.
Deprecated: Use App::setting()
with AppSettings::ArgRequiredElseHelp
instead. This
method will be removed at 2.x
NOTE: Subcommands count as arguments
Examples
App::new("myprog") .arg_required_else_help(true)
fn hidden(self, h: bool) -> Self
Hides a subcommand from help message output.
NOTE: This does not hide the subcommand from usage strings on error
Examples
.hidden(true)
fn global_version(self, gv: bool) -> Self
Uses version of the current command for all subcommands. (Defaults to false; subcommands have independant version strings)
Deprecated: Use App::setting()
with AppSettings::GlobalVersion
instead. This
method will be removed at 2.x
NOTE: The version for the current command and this setting must be set prior to adding any subcommands
Examples
App::new("myprog") .version("v1.1") .global_version(true) .subcommand(SubCommand::with_name("test")) .get_matches(); // running `myprog test --version` will display // "myprog-test v1.1"
fn versionless_subcommands(self, vers: bool) -> Self
Disables -V
and --version
for all subcommands (Defaults to false; subcommands have
version flags)
Deprecated: Use App::setting()
with AppSettings::VersionlessSubcommands
instead.
This method will be removed at 2.x
NOTE: This setting must be set prior adding any subcommands
NOTE: Do not set this value to false, it will have undesired results!
Examples
App::new("myprog") .version("v1.1") .versionless_subcommands(true) .subcommand(SubCommand::with_name("test")) .get_matches(); // running `myprog test --version` will display unknown argument error
fn unified_help_message(self, uni_help: bool) -> Self
By default the auto-generated help message groups flags, options, and positional arguments separately. This setting disable that and groups flags and options together presenting a more unified help message (a la getopts or docopt style).
Deprecated: Use App::setting()
with AppSettings::UnifiedHelpMessage
instead. This
method will be removed at 2.x
NOTE: This setting is cosmetic only and does not affect any functionality.
Examples
App::new("myprog") .unified_help_message(true) .get_matches(); // running `myprog --help` will display a unified "docopt" or "getopts" style help message
fn wait_on_error(self, w: bool) -> Self
Will display a message "Press [ENTER]/[RETURN] to continue..." and wait user before exiting
This is most useful when writing an application which is run from a GUI shortcut, or on
Windows where a user tries to open the binary by double-clicking instead of using the
command line (i.e. set .arg_required_else_help(true)
and .wait_on_error(true)
to
display the help in such a case).
Deprecated: Use App::setting()
with AppSettings::WaitOnError
instead. This
method will be removed at 2.x
NOTE: This setting is not recursive with subcommands, meaning if you wish this behavior for all subcommands, you must set this on each command (needing this is extremely rare)
Examples
App::new("myprog") .arg_required_else_help(true)
fn subcommand_required_else_help(self, tf: bool) -> Self
Specifies that the help text sould be displayed (and then exit gracefully), if no
subcommands are present at runtime (i.e. an empty run such as, $ myprog
.
Deprecated: Use App::setting()
with AppSettings::SubcommandRequiredElseHelp
instead. This method will be removed at 2.x
NOTE: This should not be used with .subcommand_required()
as they do the same
thing, except one prints the help text, and one prints an error.
NOTE: If the user specifies arguments at runtime, but no subcommand the help text will
still be displayed and exit. If this is not the desired result, consider using
.arg_required_else_help()
Examples
App::new("myprog") .subcommand_required_else_help(true)
fn setting(self, setting: AppSettings) -> Self
Enables Application level settings, passed as argument
Examples
App::new("myprog") .setting(AppSettings::SubcommandRequired) .setting(AppSettings::WaitOnError)
fn settings(self, settings: &[AppSettings]) -> Self
Enables multiple Application level settings, passed as argument
Examples
App::new("myprog") .settings( &[AppSettings::SubcommandRequired, AppSettings::WaitOnError])
fn arg(self, a: Arg<'ar, 'ar, 'ar, 'ar, 'ar, 'ar>) -> Self
Adds an argument to the list of valid possibilties manually. This method allows you full control over the arguments settings and options (as well as dynamic generation). It also allows you specify several more advanced configuration options such as relational rules (exclusions and requirements).
The only disadvantage to this method is that it's more verbose, and arguments must be added
one at a time. Using Arg::from_usage
helps with the verbosity, and still allows full
control over the advanced configuration options.
Examples
App::new("myprog") // Adding a single "flag" argument with a short and help text, using Arg::with_name() .arg( Arg::with_name("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_usage() .arg( Arg::from_usage("-c --config=[CONFIG] 'Optionally sets a config file to use'") )
fn args(self, args: Vec<Arg<'ar, 'ar, 'ar, 'ar, 'ar, 'ar>>) -> Self
Adds multiple arguments to the list of valid possibilties by iterating over a Vec of Args
Examples
App::new("myprog") .args( vec![Arg::from_usage("[debug] -d 'turns on debugging info"), Arg::with_name("input").index(1).help("the input file to use")] )
fn arg_from_usage(self, usage: &'ar str) -> Self
A convienience method for adding a single basic argument (one without advanced
relational rules) from a usage type string. The string used follows the same rules and
syntax as Arg::from_usage()
The downside to using this method is that you can not set any additional properties of the
Arg
other than what Arg::from_usage()
supports.
Examples
App::new("myprog") .arg_from_usage("-c --conf=<config> 'Sets a configuration file to use'")
fn args_from_usage(self, usage: &'ar str) -> Self
Adds multiple arguments at once from a usage string, one per line. See Arg::from_usage()
for details on the syntax and rules supported.
Like App::arg_from_usage()
the downside is you only set properties for the Arg
s which
Arg::from_usage()
supports. But here the benefit is pretty strong, as the readability is
greatly enhanced, especially if you don't need any of the more advanced configuration
options.
Examples
App::new("myprog") .args_from_usage( "-c --conf=[config] 'Sets a configuration file to use' [debug]... -d 'Sets the debugging level' <input> 'The input file to use'" )
fn arg_group(self, group: ArgGroup<'ar, 'ar>) -> Self
Adds an ArgGroup to the application. ArgGroups are a family of related arguments. By placing them in a logical group, you make easier requirement and exclusion rules. For instance, you can make an ArgGroup required, this means that one (and only one) argument from that group must be present. Using more than one argument from an ArgGroup causes a failure (graceful exit).
You can also do things such as name an ArgGroup as a confliction, meaning any of the arguments that belong to that group will cause a failure if present.
Perhaps the most common use of ArgGroups is to require one and only one argument to be
present out of a given set. For example, lets say that you were building an application
where one could set a given version number by supplying a string using an option argument,
such as --set-ver v1.2.3
, you also wanted to support automatically using a previous
version numer and simply incrementing one of the three numbers, so you create three flags
--major
, --minor
, and --patch
. All of these arguments shouldn't be used at one time
but perhaps you want to specify that at least one of them is used. You can create a
group
Examples
.args_from_usage("--set-ver [ver] 'set the version manually' --major 'auto increase major' --minor 'auto increase minor' --patch 'auto increase patch") .arg_group(ArgGroup::with_name("vers") .add_all(&["ver", "major", "minor","patch"]) .required(true))
fn arg_groups(self, groups: Vec<ArgGroup<'ar, 'ar>>) -> Self
Adds a ArgGroups to the application. ArgGroups are a family of related arguments. By placing them in a logical group, you make easier requirement and exclusion rules. For instance, you can make an ArgGroup required, this means that one (and only one) argument from that group must be present. Using more than one argument from an ArgGroup causes a failure (graceful exit).
You can also do things such as name an ArgGroup as a confliction, meaning any of the arguments that belong to that group will cause a failure if present.
Perhaps the most common use of ArgGroups is to require one and only one argument to be
present out of a given set. For example, lets say that you were building an application
where one could set a given version number by supplying a string using an option argument,
such as --set-ver v1.2.3
, you also wanted to support automatically using a previous
version numer and simply incrementing one of the three numbers, so you create three flags
--major
, --minor
, and --patch
. All of these arguments shouldn't be used at one time
but perhaps you want to specify that at least one of them is used. You can create a
group
Examples
.args_from_usage("--set-ver [ver] 'set the version manually' --major 'auto increase major' --minor 'auto increase minor' --patch 'auto increase patch") .arg_group(ArgGroup::with_name("vers") .add_all(&["ver", "major", "minor","patch"]) .required(true))
fn subcommand(self, subcmd: App<'a, 'v, 'ab, 'u, 'h, 'ar>) -> Self
Adds a subcommand to the list of valid possibilties. Subcommands are effectively sub apps, because they can contain their own arguments, subcommands, version, usage, etc. They also function just like apps, in that they get their own auto generated help, version, and usage.
Examples
.subcommand(SubCommand::with_name("config") .about("Controls configuration features") .arg_from_usage("<config> 'Required configuration file to use'")) // Additional subcommand configuration goes here, such as other arguments...
fn subcommands(self, subcmds: Vec<App<'a, 'v, 'ab, 'u, 'h, 'ar>>) -> Self
Adds multiple subcommands to the list of valid possibilties by iterating over a Vec of
SubCommand
s
Examples
.subcommands( vec![ SubCommand::with_name("config").about("Controls configuration functionality") .arg(Arg::with_name("config_file").index(1)), SubCommand::with_name("debug").about("Controls debug functionality")])
fn print_help(&self) -> ClapResult<()>
Prints the full help message to io::stdout()
using a BufWriter
Examples
let mut app = App::new("myprog"); let mut out = io::stdout(); app.write_help(&mut out).ok().expect("failed to write to stdout");
fn write_help<W: Write>(&self, w: &mut W) -> ClapResult<()>
Writes the full help message to the user to a io::Write
object
let mut app = App::new("myprog"); let mut out = io::stdout(); app.write_help(&mut out).ok().expect("failed to write to stdout");
fn get_matches(self) -> ArgMatches<'ar, 'ar>
Starts the parsing process. Called on top level parent app ONLY then recursively calls the real parsing function for all subcommands
Panics
If any arguments contain invalid unicode characters. If this is not desired it is
recommended to use the *_safe()
or *_lossy()
versions of this method.
Examples
let matches = App::new("myprog") // Args and options go here... .get_matches();
fn get_matches_lossy(self) -> ArgMatches<'ar, 'ar>
Starts the parsing process. Called on top level parent app ONLY then recursively calls
the real parsing function for all subcommands. Invalid unicode characters are replaced with
U+FFFD REPLACEMENT CHARACTER
Examples
let matches = App::new("myprog") // Args and options go here... .get_matches();
fn get_matches_safe(self) -> ClapResult<ArgMatches<'ar, 'ar>>
Starts the parsing process. Called on top level parent app ONLY then recursively calls the real parsing function for all subcommands
NOTE: This method WILL NOT exit when --help
or --version
(or short versions) are
used. It will return an error, where the error_type
is a ClapErrorType::HelpDisplayed
or ClapErrorType::VersionDisplayed
respectively. You must call error.exit()
or
perform a std::process::exit
yourself.
NOTE: This method should only be used when is absolutely necessary to handle errors manually.
Examples
let matches = App::new("myprog") // Args and options go here... .get_matches_safe() .unwrap_or_else( |e| { panic!("An error occurs: {}", e) });
fn get_matches_safe_lossy(self) -> ClapResult<ArgMatches<'ar, 'ar>>
Starts the parsing process. Called on top level parent app ONLY then recursively calls
the real parsing function for all subcommands. Invalid unicode characters are replaced with
U+FFFD REPLACEMENT CHARACTER
NOTE: This method WILL NOT exit when --help
or --version
(or short versions) are
used. It will return an error, where the error_type
is a ClapErrorType::HelpDisplayed
or ClapErrorType::VersionDisplayed
respectively. You must call error.exit()
or
perform a std::process::exit
yourself.
NOTE: This method should only be used when is absolutely necessary to handle errors manually.
Examples
let matches = App::new("myprog") // Args and options go here... .get_matches_safe() .unwrap_or_else( |e| { panic!("An error occurs: {}", e) });
fn get_matches_from<I, T>(self, itr: I) -> ArgMatches<'ar, 'ar> where I: IntoIterator<Item=T>, T: AsRef<OsStr>
Starts the parsing process. Called on top level parent app ONLY then recursively calls the real parsing function for all subcommands
NOTE: The first argument will be parsed as the binary name.
NOTE: This method should only be used when absolutely necessary, such as needing to
parse arguments from something other than std::env::args()
. If you are unsure, use
App::get_matches()
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);
fn get_matches_from_lossy<I, T>(self, itr: I) -> ArgMatches<'ar, 'ar> where I: IntoIterator<Item=T>, T: AsRef<OsStr>
Starts the parsing process. Called on top level parent app ONLY then recursively calls
the real parsing function for all subcommands. Invalid unicode characters are replaced with
U+FFFD REPLACEMENT CHARACTER
NOTE: The first argument will be parsed as the binary name.
NOTE: This method should only be used when absolutely necessary, such as needing to
parse arguments from something other than std::env::args()
. If you are unsure, use
App::get_matches()
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);
fn get_matches_from_safe<I, T>(self, itr: I) -> ClapResult<ArgMatches<'ar, 'ar>> where I: IntoIterator<Item=T>, T: AsRef<OsStr>
Starts the parsing process. Called on top level parent app ONLY then recursively calls the real parsing function for all subcommands
NOTE: This method WILL NOT exit when --help
or --version
(or short versions) are
used. It will return an error, where the error_type
is a ClapErrorType::HelpDisplayed
or ClapErrorType::VersionDisplayed
respectively. You must call error.exit()
or
perform a std::process::exit
yourself.
NOTE: The first argument will be parsed as the binary name.
NOTE: This method should only be used when absolutely necessary, such as needing to
parse arguments from something other than std::env::args()
. If you are unsure, use
App::get_matches_safe()
NOTE: This method should only be used when is absolutely necessary to handle errors manually.
NOTE: Invalid unicode characters will result in an Err
with type
ClapErrorType::InvalidUnicode
Examples
let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; let matches = App::new("myprog") // Args and options go here... .get_matches_from_safe(arg_vec) .unwrap_or_else( |e| { panic!("An error occurs: {}", e) });
fn get_matches_from_safe_lossy<I, T>(self, itr: I) -> ClapResult<ArgMatches<'ar, 'ar>> where I: IntoIterator<Item=T>, T: AsRef<OsStr>
Starts the parsing process. Called on top level parent app ONLY then recursively calls
the real parsing function for all subcommands. Invalid unicode characters are replaced with
U+FFFD REPLACEMENT CHARACTER
NOTE: This method WILL NOT exit when --help
or --version
(or short versions) are
used. It will return an error, where the error_type
is a ClapErrorType::HelpDisplayed
or ClapErrorType::VersionDisplayed
respectively. You must call error.exit()
or
perform a std::process::exit
yourself.
NOTE: The first argument will be parsed as the binary name.
NOTE: This method should only be used when absolutely necessary, such as needing to
parse arguments from something other than std::env::args()
. If you are unsure, use
App::get_matches_safe()
NOTE: This method should only be used when is absolutely necessary to handle errors manually.
Examples
let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; let matches = App::new("myprog") // Args and options go here... .get_matches_from_safe(arg_vec) .unwrap_or_else( |e| { panic!("An error occurs: {}", e) });
fn get_matches_from_safe_borrow<I, T>(&mut self, itr: I) -> ClapResult<ArgMatches<'ar, 'ar>> where I: IntoIterator<Item=T>, T: AsRef<OsStr>
Starts the parsing process without consuming the App
struct self
. This is normally not
the desired functionality, instead prefer App::get_matches_from_safe
which does
consume self
.
NOTE: The first argument will be parsed as the binary name.
NOTE: This method should only be used when absolutely necessary, such as needing to
parse arguments from something other than std::env::args()
. If you are unsure, use
App::get_matches_safe()
NOTE: This method should only be used when is absolutely necessary to handle errors manually.
NOTE: Invalid unicode characters will result in an Err
with type
ClapErrorType::InvalidUnicode
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.get_matches_from_safe_borrow(arg_vec) .unwrap_or_else( |e| { panic!("An error occurs: {}", e) });
fn get_matches_from_safe_borrow_lossy<I, T>(&mut self, itr: I) -> ClapResult<ArgMatches<'ar, 'ar>> where I: IntoIterator<Item=T>, T: AsRef<OsStr>
Starts the parsing process without consuming the App
struct self
. This is normally not
the desired functionality, instead prefer App::get_matches_from_safe
which does
consume self
. Invalid unicode characters are replaced with U+FFFD REPLACEMENT CHARACTER
NOTE: The first argument will be parsed as the binary name.
NOTE: This method should only be used when absolutely necessary, such as needing to
parse arguments from something other than std::env::args()
. If you are unsure, use
App::get_matches_safe()
NOTE: This method should only be used when is absolutely necessary to handle errors manually.
NOTE: Invalid unicode characters will result in an Err
with type
ClapErrorType::InvalidUnicode
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.get_matches_from_safe_borrow(arg_vec) .unwrap_or_else( |e| { panic!("An error occurs: {}", e) });