Struct clap::App
[−]
[src]
pub struct App<'a, 'b> where 'a: 'b {
// 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 the
.get_matches()
family of methods being the terminal methods that starts the runtime-parsing
process. These methods then return information about the user supplied arguments (or lack there
of).
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::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, 'b> App<'a, 'b>
[src]
fn new<S: Into<String>>(n: S) -> Self
Creates a new instance of an application requiring a name. The name may be, but doesn't have to be same as the binary. The name will be displayed to the user when they request to print version or help and usage information.
Examples
let prog = App::new("My Program")
fn author<S: Into<&'b str>>(self, author: S) -> Self
Sets a string of author(s) that will be displayed to the user when they
request the help information with --help
or -h
.
Pro-tip: If you turn on unstable features you can use clap
s
convienience macro crate_authors!
to automatically set your
application's author 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")
fn bin_name<S: Into<String>>(self, name: S) -> Self
Overrides the system-determined binary name. This should only be used when absolutely neccessary, 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 command should not be used for SubCommand
s.
Examples
App::new("My Program") .bin_name("my_binary")
fn about<S: Into<&'b str>>(self, about: S) -> Self
Sets a string describing what the program does. This will be displayed when displaying help information.
Examples
App::new("myprog") .about("Does really amazing things to great people")
fn after_help<S: Into<&'b 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. This 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...but be careful with -R")
fn before_help<S: Into<&'b str>>(self, help: S) -> Self
Adds additional help information to be displayed in addition to auto-generated help. This information is displayed before the auto-generated help information. This is often used for header information.
Examples
App::new("myprog") .before_help("Some info I'd like to appear before the help info")
fn version<S: Into<&'b str>>(self, ver: S) -> Self
Sets a string of the version number to be displayed when displaying version or help information.
Pro-tip: Use clap
s convienience 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
Examples
App::new("myprog") .version("v0.1.24")
fn usage<S: Into<&'b str>>(self, usage: S) -> 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 ArgMatches::usage
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: 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<S: Into<&'b str>>(self, help: S) -> 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 --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<S: AsRef<str> + 'b>(self, s: S) -> Self
Sets the short version of the help
argument without the preceding -
.
By default clap
automatically assigns h
, but this can be overridden by defining your
own argument with a lowercase h
as the short
. clap
lazily generates these help
arguments after you've defined any arguments of your own.
NOTE: Any leading -
characters will be stripped, and only the first
non -
chacter will be used as the short
version
Examples
App::new("myprog") .help_short("H") // Using an uppercase `H` instead of the default lowercase `h`
fn version_short<S: AsRef<str>>(self, s: S) -> Self
Sets the short version of the version
argument without the preceding -
.
By default clap
automatically assigns V
, but this can be overridden by defining your
own argument with a uppercase V
as the short
. clap
lazily generates these version
arguments after you've defined any arguments of your own.
NOTE: Any leading -
characters will be stripped, and only the first
non -
chacter will be used as the short
version
Examples
App::new("myprog") .version_short("v") // Using a lowercase `v` instead of the default capital `V`
fn template<S: Into<&'b str>>(self, s: S) -> Self
Sets the help template to be used, overriding the default format.
Tags arg given inside curly brackets:
Valid tags are:
* {bin}
- Binary name.
* {version}
- Version number.
* {author}
- Author information.
* {usage}
- Automatically generated or given usage string.
* {all-args}
- Help for all arguments (options, flags, positionals arguments,
and subcommands) including titles.
* {unified}
- Unified help for options and flags.
* {flags}
- Help for flags.
* {options}
- Help for options.
* {positionals}
- Help for positionals arguments.
* {subcommands}
- Help for subcommands.
* {after-help}
- Help for flags.
Examples
App::new("myprog") .version("1.0") .template("{bin} ({version}) - {usage}")
NOTE:The template system is, on purpose, very simple. Therefore the tags have to writen in the lowercase and without spacing.
fn setting(self, setting: AppSettings) -> Self
Enables a single Application level settings.
See AppSettings
for a full list of possibilities and examples.
Examples
App::new("myprog") .setting(AppSettings::SubcommandRequired) .setting(AppSettings::WaitOnError)
fn settings(self, settings: &[AppSettings]) -> Self
Enables multiple Application level settings
See AppSettings
for a full list of possibilities and examples.
Examples
App::new("myprog") .settings(&[AppSettings::SubcommandRequired, AppSettings::WaitOnError])
fn arg<A: Borrow<Arg<'a, 'b>> + 'a>(self, a: A) -> Self
Adds an argument to the list of valid possibilties.
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: &[Arg<'a, 'b>]) -> Self
Adds multiple arguments to the list of valid possibilties
Examples
App::new("myprog") .args( &[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: &'a str) -> Self
A convienience method for adding a single argument from a usage type string. The string
used follows the same rules and syntax as Arg::from_usage()
NOTE: 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 --config=<FILE> 'Sets a configuration file to use'")
fn args_from_usage(self, usage: &'a 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.
NOTE: Like App::arg_from_usage()
the downside is you only set properties for the
Arg
s which Arg::from_usage()
supports.
Examples
App::new("myprog") .args_from_usage( "-c --config=[FILE] 'Sets a configuration file to use' [debug]... -d 'Sets the debugging level' <FILE> 'The input file to use'" )
fn group(self, group: ArgGroup<'a>) -> 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 benfit 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") .args_from_usage( "--set-ver [ver] 'set the version manually' --major 'auto increase major' --minor 'auto increase minor' --patch 'auto increase patch'") .group(ArgGroup::with_name("vers") .args(&["set-ver", "major", "minor","patch"]) .required(true))
fn groups(self, groups: &[ArgGroup<'a>]) -> Self
Adds multiple ArgGroup
s to the application at once.
Examples
App::new("app") .args_from_usage( "--set-ver [ver] 'set the version manually' --major 'auto increase major' --minor 'auto increase minor' --patch 'auto increase patch' -c [FILE] 'a config file' -i [IFACE] 'an interface'") .groups(&[ ArgGroup::with_name("vers") .args(&["set-ver", "major", "minor","patch"]) .required(true), ArgGroup::with_name("input") .args(&["c", "i"]) ])
fn subcommand(self, subcmd: App<'a, 'b>) -> 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
App::new("myprog") .subcommand(SubCommand::with_name("config") .about("Controls configuration features") .arg_from_usage("<config> 'Required configuration file to use'"))
fn subcommands<I>(self, subcmds: I) -> Self where I: IntoIterator<Item=App<'a, 'b>>
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 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 emphasise 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(SubCommand::with_name("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(SubCommand::with_name("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 [FLAGS] [OPTIONS] FLAGS: -h, --help Prints help information -V, --version Prints version information SUBCOMMANDS: beta I should be first! alpha Some help and text
fn print_help(&self) -> ClapResult<()>
Prints the full help message to io::stdout()
using a BufWriter
Examples
let app = App::new("myprog"); app.print_help();
fn write_help<W: Write>(&self, w: &mut W) -> ClapResult<()>
Writes the full help message to the user to a io::Write
object
Examples
use std::io; 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<'a>
Starts the parsing process, upon a failed parse an error will be displayed to the user and
the process with exit with the appropriate error code. By default this method gets matches
from env::args_os
Examples
let matches = App::new("myprog") // Args and options go here... .get_matches();
fn get_matches_safe(self) -> ClapResult<ArgMatches<'a>>
Starts the parsing process. This method will return a Result
type instead of exiting the
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 an error, where the kind
is a ErrorKind::HelpDisplayed
or ErrorKind::VersionDisplayed
respectively. You must call error.exit()
or
perform a std::process::exit
.
Examples
let matches = App::new("myprog") // Args and options go here... .get_matches_safe() .unwrap_or_else( |e| e.exit() );
fn get_matches_from<I, T>(self, itr: I) -> ArgMatches<'a> where I: IntoIterator<Item=T>, T: Into<OsString>
Starts the parsing process. Like App::get_matches
this method does not return a 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);
fn get_matches_from_safe<I, T>(self, itr: I) -> ClapResult<ArgMatches<'a>> where I: IntoIterator<Item=T>, T: Into<OsString>
Starts the parsing process. A combination of App::get_matches_from
, and
App::get_matches_safe
NOTE: This method WILL NOT exit when --help
or --version
(or short versions) are
used. It will return an error, where the kind
is a ErrorKind::HelpDisplayed
or ErrorKind::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 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_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<'a>> where I: IntoIterator<Item=T>, T: Into<OsString>
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 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.get_matches_from_safe_borrow(arg_vec) .unwrap_or_else( |e| { panic!("An error occurs: {}", e) });
Trait Implementations
impl<'a, 'b> Clone for App<'a, 'b>
[src]
fn clone(&self) -> Self
Returns a copy of the value. Read more
fn clone_from(&mut self, source: &Self)
1.0.0
Performs copy-assignment from source
. Read more