logo
pub enum AppSettings {
Show 32 variants AllowInvalidUtf8ForExternalSubcommands, AllowLeadingHyphen, AllArgsOverrideSelf, AllowNegativeNumbers, AllowMissingPositional, AllowExternalSubcommands, ArgsNegateSubcommands, ArgRequiredElseHelp, SubcommandPrecedenceOverArg, DontCollapseArgsInUsage, DontDelimitTrailingValues, DisableHelpFlag, DisableHelpSubcommand, DisableVersionFlag, DeriveDisplayOrder, PropagateVersion, Hidden, HidePossibleValuesInHelp, HelpRequired, IgnoreErrors, InferSubcommands, InferLongArgs, NoBinaryName, NextLineHelp, SubcommandsNegateReqs, SubcommandRequiredElseHelp, UseLongFormatForHelpSubcommand, SubcommandRequired, TrailingVarArg, WaitOnError, NoAutoHelp, NoAutoVersion, // some variants omitted
}
Expand description

Application level settings, which affect how App operates

NOTE: When these settings are used, they apply only to current command, and are not propagated down or up through child or parent subcommands

Variants

AllowInvalidUtf8ForExternalSubcommands

Specifies that external subcommands that are invalid UTF-8 should not be treated as an error.

NOTE: Using external subcommand argument values with invalid UTF-8 requires using ArgMatches::values_of_os or ArgMatches::values_of_lossy for those particular arguments which may contain invalid UTF-8 values

NOTE: Setting this requires AppSettings::AllowExternalSubcommands

Platform Specific

Non Windows systems only

Examples

// Assume there is an external subcommand named "subcmd"
let m = App::new("myprog")
   .setting(AppSettings::AllowInvalidUtf8ForExternalSubcommands)
   .setting(AppSettings::AllowExternalSubcommands)
   .get_matches_from(vec![
       "myprog", "subcmd", "--option", "value", "-fff", "--flag"
   ]);

// All trailing arguments will be stored under the subcommand's sub-matches using an empty
// string argument name
match m.subcommand() {
   Some((external, ext_m)) => {
        let ext_args: Vec<&std::ffi::OsStr> = ext_m.values_of_os("").unwrap().collect();
        assert_eq!(external, "subcmd");
        assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
   },
   _ => {},
}

AllowLeadingHyphen

Specifies that leading hyphens are allowed in all argument values, such as negative numbers like -10. (which would otherwise be parsed as another flag or option)

NOTE: Use this setting with caution as it silences certain circumstances which would otherwise be an error (such as accidentally forgetting to specify a value for leading option). It is preferred to set this on a per argument basis, via Arg::allow_hyphen_values

Examples

// Imagine you needed to represent negative numbers as well, such as -10
let m = App::new("nums")
    .setting(AppSettings::AllowLeadingHyphen)
    .arg(Arg::new("neg"))
    .get_matches_from(vec![
        "nums", "-20"
    ]);

assert_eq!(m.value_of("neg"), Some("-20"));

AllArgsOverrideSelf

Specifies that all arguments override themselves. This is the equivalent to saying the foo arg using Arg::overrides_with("foo") for all defined arguments.

AllowNegativeNumbers

Allows negative numbers to pass as values. This is similar to AppSettings::AllowLeadingHyphen except that it only allows numbers, all other undefined leading hyphens will fail to parse.

Examples

let res = App::new("myprog")
    .setting(AppSettings::AllowNegativeNumbers)
    .arg(Arg::new("num"))
    .try_get_matches_from(vec![
        "myprog", "-20"
    ]);
assert!(res.is_ok());
let m = res.unwrap();
assert_eq!(m.value_of("num").unwrap(), "-20");

AllowMissingPositional

Allows one to implement two styles of CLIs where positionals can be used out of order.

The first example is a CLI where the second to last positional argument is optional, but the final positional argument is required. Such as $ prog [optional] <required> where one of the two following usages is allowed:

  • $ prog [optional] <required>
  • $ prog <required>

This would otherwise not be allowed. This is useful when [optional] has a default value.

Note: when using this style of “missing positionals” the final positional must be required if -- will not be used to skip to the final positional argument.

Note: This style also only allows a single positional argument to be “skipped” without the use of --. To skip more than one, see the second example.

The second example is when one wants to skip multiple optional positional arguments, and use of the -- operator is OK (but not required if all arguments will be specified anyways).

For example, imagine a CLI which has three positional arguments [foo] [bar] [baz]... where baz accepts multiple values (similar to man ARGS... style training arguments).

With this setting the following invocations are posisble:

  • $ prog foo bar baz1 baz2 baz3
  • $ prog foo -- baz1 baz2 baz3
  • $ prog -- baz1 baz2 baz3

Examples

Style number one from above:

// Assume there is an external subcommand named "subcmd"
let m = App::new("myprog")
    .setting(AppSettings::AllowMissingPositional)
    .arg(Arg::new("arg1"))
    .arg(Arg::new("arg2")
        .required(true))
    .get_matches_from(vec![
        "prog", "other"
    ]);

assert_eq!(m.value_of("arg1"), None);
assert_eq!(m.value_of("arg2"), Some("other"));

Now the same example, but using a default value for the first optional positional argument

// Assume there is an external subcommand named "subcmd"
let m = App::new("myprog")
    .setting(AppSettings::AllowMissingPositional)
    .arg(Arg::new("arg1")
        .default_value("something"))
    .arg(Arg::new("arg2")
        .required(true))
    .get_matches_from(vec![
        "prog", "other"
    ]);

assert_eq!(m.value_of("arg1"), Some("something"));
assert_eq!(m.value_of("arg2"), Some("other"));

Style number two from above:

// Assume there is an external subcommand named "subcmd"
let m = App::new("myprog")
    .setting(AppSettings::AllowMissingPositional)
    .arg(Arg::new("foo"))
    .arg(Arg::new("bar"))
    .arg(Arg::new("baz").takes_value(true).multiple_values(true))
    .get_matches_from(vec![
        "prog", "foo", "bar", "baz1", "baz2", "baz3"
    ]);

assert_eq!(m.value_of("foo"), Some("foo"));
assert_eq!(m.value_of("bar"), Some("bar"));
assert_eq!(m.values_of("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);

Now nofice if we don’t specify foo or baz but use the -- operator.

// Assume there is an external subcommand named "subcmd"
let m = App::new("myprog")
    .setting(AppSettings::AllowMissingPositional)
    .arg(Arg::new("foo"))
    .arg(Arg::new("bar"))
    .arg(Arg::new("baz").takes_value(true).multiple_values(true))
    .get_matches_from(vec![
        "prog", "--", "baz1", "baz2", "baz3"
    ]);

assert_eq!(m.value_of("foo"), None);
assert_eq!(m.value_of("bar"), None);
assert_eq!(m.values_of("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);

AllowExternalSubcommands

Specifies that an unexpected positional argument, which would otherwise cause a ErrorKind::UnknownArgument error, should instead be treated as a subcommand within the ArgMatches struct.

NOTE: Use this setting with caution, as a truly unexpected argument (i.e. one that is NOT an external subcommand) will not cause an error and instead be treated as a potential subcommand. One should check for such cases manually and inform the user appropriately.

Examples

// Assume there is an external subcommand named "subcmd"
let m = App::new("myprog")
    .setting(AppSettings::AllowExternalSubcommands)
    .get_matches_from(vec![
        "myprog", "subcmd", "--option", "value", "-fff", "--flag"
    ]);

// All trailing arguments will be stored under the subcommand's sub-matches using an empty
// string argument name
match m.subcommand() {
    Some((external, ext_m)) => {
         let ext_args: Vec<&str> = ext_m.values_of("").unwrap().collect();
         assert_eq!(external, "subcmd");
         assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
    },
    _ => {},
}

ArgsNegateSubcommands

Specifies that use of a valid argument negates subcommands being used after. By default clap allows arguments between subcommands such as <cmd> [cmd_args] <subcmd> [subcmd_args] <subsubcmd> [subsubcmd_args].

This setting disables that functionality and says that arguments can only follow the final subcommand. For instance using this setting makes only the following invocations possible:

  • <cmd> <subcmd> <subsubcmd> [subsubcmd_args]
  • <cmd> <subcmd> [subcmd_args]
  • <cmd> [cmd_args]

Examples

App::new("myprog")
    .setting(AppSettings::ArgsNegateSubcommands);

ArgRequiredElseHelp

Specifies that the help text should 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

NOTE: Setting Arg::default_value effectively disables this option as it will ensure that some argument is always present.

Examples

App::new("myprog")
    .setting(AppSettings::ArgRequiredElseHelp);

SubcommandPrecedenceOverArg

Instructs the parser to stop when encountering a subcommand instead of greedily consuming args.

By default, if an option taking multiple values is followed by a subcommand, the subcommand will be parsed as another value.

app --foo val1 val2 subcommand
          --------- ----------
            values   another value

This setting instructs the parser to stop when encountering a subcommand instead of greedily consuming arguments.

app --foo val1 val2 subcommand
          --------- ----------
            values   subcommand

Note: Make sure you apply it as global_setting if you want this setting to be propagated to subcommands and sub-subcommands!

Examples

let app = App::new("app").subcommand(App::new("sub")).arg(
    Arg::new("arg")
        .long("arg")
        .multiple_values(true)
        .takes_value(true),
);

let matches = app
    .clone()
    .try_get_matches_from(&["app", "--arg", "1", "2", "3", "sub"])
    .unwrap();

assert_eq!(
    matches.values_of("arg").unwrap().collect::<Vec<_>>(),
    &["1", "2", "3", "sub"]
);
assert!(matches.subcommand_matches("sub").is_none());

let matches = app
    .setting(AppSettings::SubcommandPrecedenceOverArg)
    .try_get_matches_from(&["app", "--arg", "1", "2", "3", "sub"])
    .unwrap();

assert_eq!(
    matches.values_of("arg").unwrap().collect::<Vec<_>>(),
    &["1", "2", "3"]
);
assert!(matches.subcommand_matches("sub").is_some());

DontCollapseArgsInUsage

Disables the automatic collapsing of positional args into [ARGS] inside the usage string

Examples

App::new("myprog")
    .setting(AppSettings::DontCollapseArgsInUsage)
    .get_matches();

DontDelimitTrailingValues

Disables the automatic delimiting of values when -- or AppSettings::TrailingVarArg was used.

NOTE: The same thing can be done manually by setting the final positional argument to Arg::use_delimiter(false). Using this setting is safer, because it’s easier to locate when making changes.

Examples

App::new("myprog")
    .setting(AppSettings::DontDelimitTrailingValues)
    .get_matches();

DisableHelpFlag

Disables -h and --help flag.

Examples

let res = App::new("myprog")
    .setting(AppSettings::DisableHelpFlag)
    .try_get_matches_from(vec![
        "myprog", "-h"
    ]);
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);

DisableHelpSubcommand

Disables the help subcommand.

Examples

let res = App::new("myprog")
    .setting(AppSettings::DisableHelpSubcommand)
    // Normally, creating a subcommand causes a `help` subcommand to automatically
    // be generated as well
    .subcommand(App::new("test"))
    .try_get_matches_from(vec![
        "myprog", "help"
    ]);
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);

DisableVersionFlag

Disables -V and --version flag.

Examples

let res = App::new("myprog")
    .setting(AppSettings::DisableVersionFlag)
    .try_get_matches_from(vec![
        "myprog", "-V"
    ]);
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);

DeriveDisplayOrder

Displays the arguments and subcommands in the help message in the order that they were declared in, and not alphabetically which is the default.

Examples

App::new("myprog")
    .setting(AppSettings::DeriveDisplayOrder)
    .get_matches();

PropagateVersion

Specifies to use the version of the current command for all subcommands.

Defaults to false; subcommands have independent version strings from their parents.

Note: Make sure you apply it as global_setting if you want this setting to be propagated to subcommands and sub-subcommands!

Examples

App::new("myprog")
    .version("v1.1")
    .setting(AppSettings::PropagateVersion)
    .subcommand(App::new("test"))
    .get_matches();
// running `$ myprog test --version` will display
// "myprog-test v1.1"

Hidden

Specifies that this subcommand should be hidden from help messages

Examples

App::new("myprog")
    .subcommand(App::new("test")
    .setting(AppSettings::Hidden))

HidePossibleValuesInHelp

Tells clap not to print possible values when displaying help information. This can be useful if there are many values, or they are explained elsewhere.

HelpRequired

Tells clap to panic if help strings are omitted

Examples

App::new("myprog")
    .setting(AppSettings::HelpRequired)
    .arg(
        Arg::new("foo").about("It does foo stuff")
        // As required via AppSettings::HelpRequired, a help message was supplied
     )

Panics

App::new("myapp")
    .setting(AppSettings::HelpRequired)
    .arg(
        Arg::new("foo")
        // Someone forgot to put .about("...") here
        // Since the setting AppSettings::HelpRequired is activated, this will lead to
        // a panic (if you are in debug mode)
    )

IgnoreErrors

Try not to fail on parse errors like missing option values.

Note: Make sure you apply it as global_setting if you want this setting to be propagated to subcommands and sub-subcommands!

Issue: #1880 Partial / Pre Parsing a CLI

This is the basis for:

Support is not complete: Errors are still possible but they can be avoided in many cases.

let app = App::new("app")
  .setting(AppSettings::IgnoreErrors)
  .arg("-c, --config=[FILE] 'Sets a custom config file'")
  .arg("-x, --stuff=[FILE] 'Sets a custom stuff file'")
  .arg("-f 'Flag'");

let r = app.try_get_matches_from(vec!["app", "-c", "file", "-f", "-x"]);

assert!(r.is_ok(), "unexpected error: {:?}", r);
let m = r.unwrap();
assert_eq!(m.value_of("config"), Some("file"));
assert!(m.is_present("f"));
assert_eq!(m.value_of("stuff"), None);

InferSubcommands

Tries to match unknown args to partial subcommands or their aliases. For example, to match a subcommand named test, one could use t, te, tes, and test.

NOTE: The match must not be ambiguous at all in order to succeed. i.e. to match te to test there could not also be a subcommand or alias temp because both start with te

CAUTION: This setting can interfere with positional/free arguments, take care when designing CLIs which allow inferred subcommands and have potential positional/free arguments whose values could start with the same characters as subcommands. If this is the case, it’s recommended to use settings such as AppSettings::ArgsNegateSubcommands in conjunction with this setting.

Examples

let m = App::new("prog")
    .setting(AppSettings::InferSubcommands)
    .subcommand(App::new("test"))
    .get_matches_from(vec![
        "prog", "te"
    ]);
assert_eq!(m.subcommand_name(), Some("test"));

InferLongArgs

Tries to match unknown args to partial long arguments or their aliases. For example, to match an argument named --test, one could use --t, --te, --tes, and --test.

NOTE: The match must not be ambiguous at all in order to succeed. i.e. to match --te to --test there could not also be another argument or alias --temp because both start with --te

NoBinaryName

Specifies that the parser should not assume the first argument passed is the binary name. This is normally the case when using a “daemon” style mode, or an interactive CLI where one would not normally type the binary or program name for each command.

Examples

let m = App::new("myprog")
    .setting(AppSettings::NoBinaryName)
    .arg(Arg::from("<cmd>... 'commands to run'"))
    .get_matches_from(vec!["command", "set"]);

let cmds: Vec<&str> = m.values_of("cmd").unwrap().collect();
assert_eq!(cmds, ["command", "set"]);

NextLineHelp

Places the help string for all arguments on the line after the argument.

Examples

App::new("myprog")
    .setting(AppSettings::NextLineHelp)
    .get_matches();

SubcommandsNegateReqs

Allows subcommands to override all requirements of the parent command. For example, if you had a subcommand or top level application with a required argument that is only required as long as there is no subcommand present, using this setting would allow you to set those arguments to Arg::required(true) and yet receive no error so long as the user uses a valid subcommand instead.

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

Examples

This first example shows that it is an error to not use a required argument

let err = App::new("myprog")
    .setting(AppSettings::SubcommandsNegateReqs)
    .arg(Arg::new("opt").required(true))
    .subcommand(App::new("test"))
    .try_get_matches_from(vec![
        "myprog"
    ]);
assert!(err.is_err());
assert_eq!(err.unwrap_err().kind, ErrorKind::MissingRequiredArgument);

This next example shows that it is no longer error to not use a required argument if a valid subcommand is used.

let noerr = App::new("myprog")
    .setting(AppSettings::SubcommandsNegateReqs)
    .arg(Arg::new("opt").required(true))
    .subcommand(App::new("test"))
    .try_get_matches_from(vec![
        "myprog", "test"
    ]);
assert!(noerr.is_ok());

SubcommandRequiredElseHelp

Specifies that the help text should be displayed (before exiting gracefully) if no subcommands are present at runtime (i.e. an empty run such as $ myprog).

NOTE: This should not be used with AppSettings::SubcommandRequired as they do nearly same thing; this prints the help text, and the other 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 AppSettings::ArgRequiredElseHelp instead.

Examples

App::new("myprog")
    .setting(AppSettings::SubcommandRequiredElseHelp);

UseLongFormatForHelpSubcommand

Specifies that the help subcommand should print the long format help message.

NOTE: This setting is useless if AppSettings::DisableHelpSubcommand or AppSettings::NoAutoHelp is set, or if the app contains no subcommands at all.

Examples

App::new("myprog")
    .setting(AppSettings::UseLongFormatForHelpSubcommand)
    .subcommand(App::new("test")
        .arg(Arg::new("foo")
            .about("short form about message")
            .long_about("long form about message")
        )
    )
    .get_matches();

SubcommandRequired

Allows specifying that if no subcommand is present at runtime, error and exit gracefully.

Examples

let err = App::new("myprog")
    .setting(AppSettings::SubcommandRequired)
    .subcommand(App::new("test"))
    .try_get_matches_from(vec![
        "myprog",
    ]);
assert!(err.is_err());
assert_eq!(err.unwrap_err().kind, ErrorKind::MissingSubcommand);

TrailingVarArg

Specifies that the final positional argument is a “VarArg” and that clap should not attempt to parse any further args.

The values of the trailing positional argument will contain all args from itself on.

NOTE: The final positional argument must have Arg::multiple_values(true) or the usage string equivalent.

Examples

let m = App::new("myprog")
    .setting(AppSettings::TrailingVarArg)
    .arg(Arg::from("<cmd>... 'commands to run'"))
    .get_matches_from(vec!["myprog", "arg1", "-r", "val1"]);

let trail: Vec<&str> = m.values_of("cmd").unwrap().collect();
assert_eq!(trail, ["arg1", "-r", "val1"]);

WaitOnError

Will display a message “Press [ENTER]/[RETURN] to continue…” and wait for 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.

Examples

App::new("myprog")
    .setting(AppSettings::WaitOnError);

NoAutoHelp

Tells clap to treat the auto-generated -h, --help flags just like any other flag, and not print the help message. This allows one to handle printing of the help message manually.

let result = App::new("myprog")
    .setting(AppSettings::NoAutoHelp)
    .try_get_matches_from("myprog --help".split(" "));

// Normally, if `--help` is used clap prints the help message and returns an
// ErrorKind::DisplayHelp
//
// However, `--help` was treated like a normal flag

assert!(result.is_ok());
assert!(result.unwrap().is_present("help"));

NoAutoVersion

Tells clap to treat the auto-generated -V, --version flags just like any other flag, and not print the version message. This allows one to handle printing of the version message manually.

let result = App::new("myprog")
    .version("3.0")
    .setting(AppSettings::NoAutoVersion)
    .try_get_matches_from("myprog --version".split(" "));

// Normally, if `--version` is used clap prints the version message and returns an
// ErrorKind::DisplayVersion
//
// However, `--version` was treated like a normal flag

assert!(result.is_ok());
assert!(result.unwrap().is_present("version"));

Trait Implementations

The resulting type after applying the | operator.

Performs the | operation. Read more

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

The associated error which can be returned from parsing.

Parses a string s to return a value of this type. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.