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).

Example

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).

Example

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.

Example

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.

Example

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.

Example

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.

Example

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.

NOTE: This defaults to false (using subcommand does not negate requirements)

Example

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

NOTE: This defaults to false (subcommands do not need to be present)

Example

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.

Example

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 ArgMatches::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.

Example

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.

Example

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

Example

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

Example

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.

NOTE: Subcommands count as arguments

Example

App::new("myprog")
    .arg_required_else_help(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)

NOTE: The version for the current command and this setting must be set prior to adding any subcommands

Example

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)

NOTE: This setting must be set prior adding any subcommands

NOTE: Do not set this value to false, it will have undesired results!

Example

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).

NOTE: This setting is cosmetic only and does not affect any functionality.

Example

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).

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)

Example

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.

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()

Example

App::new("myprog")
    .subcommand_required_else_help(true)

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.

Example

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

Example

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.

Example

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 Args 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.

Example

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

Example

.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(vec!["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

Example

.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(vec!["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.

Example

.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 SubCommands

Example

.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 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

Example

let matches = App::new("myprog")
    // Args and options go here...
    .get_matches();

fn get_matches_from<I, T>(self, itr: I) -> ArgMatches<'ar, 'ar> where I: IntoIterator<Item=T>, T: AsRef<str>

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()

Example

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);