Struct clap::App [−][src]
pub struct App<'help> { /* fields omitted */ }
Expand description
Build a command-line interface.
This includes defining arguments, subcommands, parser behavior, and help output.
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).
When deriving a Parser
, you can use
IntoApp::into_app
to access the
App
.
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
Creates a new instance of an App
.
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.
See also app_from_crate!!
and crate_name!
.
Examples
App::new("My Program")
Examples found in repository
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
fn applet_commands() -> [App<'static>; 2] {
[
App::new("true").about("does nothing successfully"),
App::new("false").about("does nothing unsuccessfully"),
]
}
fn main() {
let app = App::new(env!("CARGO_CRATE_NAME"))
.setting(AppSettings::Multicall)
.subcommand(
App::new("busybox")
.setting(AppSettings::ArgRequiredElseHelp)
.subcommand_value_name("APPLET")
.subcommand_help_heading("APPLETS")
.arg(
Arg::new("install")
.long("install")
.help("Install hardlinks for all subcommands in path")
.exclusive(true)
.takes_value(true)
.default_missing_value("/usr/local/bin")
.use_delimiter(false),
)
.subcommands(applet_commands()),
)
.subcommands(applet_commands());
let matches = app.get_matches();
let mut subcommand = matches.subcommand();
if let Some(("busybox", cmd)) = subcommand {
if cmd.occurrences_of("install") > 0 {
unimplemented!("Make hardlinks to the executable here");
}
subcommand = cmd.subcommand();
}
match subcommand {
Some(("false", _)) => exit(1),
Some(("true", _)) => exit(0),
_ => unreachable!("parser should ensure only valid subcommand names are used"),
}
}
More examples
3 4 5 6 7 8 9 10 11 12 13 14
fn main() {
let matches = App::new("MyApp")
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>")
.about("Does awesome things")
.arg(arg!(--two <VALUE>))
.arg(arg!(--one <VALUE>))
.get_matches();
println!("two: {:?}", matches.value_of("two").expect("required"));
println!("one: {:?}", matches.value_of("one").expect("required"));
}
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
fn main() {
let matches = app_from_crate!()
.global_setting(AppSettings::PropagateVersion)
.global_setting(AppSettings::UseLongFormatForHelpSubcommand)
.setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(
App::new("add")
.about("Adds files to myapp")
.arg(arg!([NAME])),
)
.get_matches();
match matches.subcommand() {
Some(("add", sub_matches)) => println!(
"'myapp add' was used, name is: {:?}",
sub_matches.value_of("NAME")
),
_ => unreachable!(),
}
}
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
fn main() {
let app = App::new(env!("CARGO_CRATE_NAME"))
.setting(AppSettings::ArgRequiredElseHelp)
.subcommand_value_name("APPLET")
.subcommand_help_heading("APPLETS")
.subcommand(App::new("hostname").about("show hostname part of FQDN"))
.subcommand(App::new("dnsdomainname").about("show domain name part of FQDN"));
let app = app.setting(AppSettings::Multicall);
match app.get_matches().subcommand_name() {
Some("hostname") => println!("www"),
Some("dnsdomainname") => println!("example.com"),
_ => unreachable!("parser should ensure only valid subcommand names are used"),
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
fn main() {
let app = clap::App::new("cargo")
.bin_name("cargo")
.setting(clap::AppSettings::SubcommandRequired)
.subcommand(
clap::app_from_crate!().name("example").arg(
clap::arg!(--"manifest-path" <PATH>)
.required(false)
.allow_invalid_utf8(true),
),
);
let matches = app.get_matches();
let matches = match matches.subcommand() {
Some(("example", matches)) => matches,
_ => unreachable!("clap should ensure we don't get here"),
};
let manifest_path = matches
.value_of_os("manifest-path")
.map(std::path::PathBuf::from);
println!("{:?}", manifest_path);
}
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
fn main() {
let matches = app_from_crate!()
.arg(arg!([name] "Optional name to operate on"))
.arg(
arg!(
-c --config <FILE> "Sets a custom config file"
)
// We don't have syntax yet for optional options, so manually calling `required`
.required(false)
// Support non-UTF8 paths
.allow_invalid_utf8(true),
)
.arg(arg!(
-d --debug ... "Turn debugging information on"
))
.subcommand(
App::new("test")
.about("does testing things")
.arg(arg!(-l --list "lists test values")),
)
.get_matches();
// You can check the value provided by positional arguments, or option arguments
if let Some(name) = matches.value_of("name") {
println!("Value for name: {}", name);
}
if let Some(raw_config) = matches.value_of_os("config") {
let config_path = Path::new(raw_config);
println!("Value for config: {}", config_path.display());
}
// You can see how many times a particular flag or argument occurred
// Note, only flags can have multiple occurrences
match matches.occurrences_of("debug") {
0 => println!("Debug mode is off"),
1 => println!("Debug mode is kind of on"),
2 => println!("Debug mode is on"),
_ => println!("Don't be crazy"),
}
// You can check for the existence of subcommands, and if found use their
// matches just as you would the top level app
if let Some(matches) = matches.subcommand_matches("test") {
// "$ myapp test" was run
if matches.is_present("list") {
// "$ myapp test -l" was run
println!("Printing testing lists...");
} else {
println!("Not printing testing lists...");
}
}
// Continued program logic goes here...
}
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')
.help("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!(-c --config <CONFIG> "Optionally sets a config file to use")
)
Examples found in repository
More examples
3 4 5 6 7 8 9 10 11 12 13 14
fn main() {
let matches = app_from_crate!()
.arg(arg!([NAME]).default_value("alice"))
.get_matches();
println!(
"NAME: {:?}",
matches
.value_of("NAME")
.expect("default ensures there is always a value")
);
}
- examples/tutorial_builder/02_apps.rs
- examples/tutorial_builder/04_02_validate.rs
- examples/tutorial_builder/02_app_settings.rs
- examples/tutorial_builder/04_01_enum.rs
- examples/tutorial_builder/04_01_possible.rs
- examples/tutorial_builder/03_04_subcommands.rs
- examples/cargo-example.rs
- examples/escaped-positional.rs
- examples/multicall-busybox.rs
- examples/tutorial_builder/01_quick.rs
- examples/git.rs
- examples/tutorial_builder/04_03_relations.rs
- examples/tutorial_builder/04_04_custom.rs
- examples/pacman.rs
Allows one to mutate an Arg
after it’s been added to an App
.
This can be useful for modifying the auto-generated help or version arguments.
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());
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.
Example use cases:
- Make an entire
ArgGroup
required, meaning that one (and only one) argument from that group must be present at runtime. - 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. - Ensure exclusion between arguments.
- Extract a value from a group instead of determining exactly which argument was used.
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(arg!("--set-ver [ver] 'set the version manually'"))
.arg(arg!("--major 'auto increase major'"))
.arg(arg!("--minor 'auto increase minor'"))
.arg(arg!("--patch 'auto increase patch'"))
.group(ArgGroup::new("vers")
.args(&["set-ver", "major", "minor","patch"])
.required(true))
Examples found in repository
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
fn main() {
// Create application like normal
let matches = app_from_crate!()
// Add the version arguments
.arg(arg!(--"set-ver" <VER> "set version manually").required(false))
.arg(arg!(--major "auto inc major"))
.arg(arg!(--minor "auto inc minor"))
.arg(arg!(--patch "auto inc patch"))
// Create a group, make it required, and add the above arguments
.group(
ArgGroup::new("vers")
.required(true)
.args(&["set-ver", "major", "minor", "patch"]),
)
// Arguments can also be added to a group individually, these two arguments
// are part of the "input" group which is not required
.arg(arg!([INPUT_FILE] "some regular input").group("input"))
.arg(
arg!(--"spec-in" <SPEC_IN> "some special input argument")
.required(false)
.group("input"),
)
// Now let's assume we have a -c [config] argument which requires one of
// (but **not** both) the "input" arguments
.arg(arg!(config: -c <CONFIG>).required(false).requires("input"))
.get_matches();
// Let's assume the old version 1.2.3
let mut major = 1;
let mut minor = 2;
let mut patch = 3;
// See if --set-ver was used to set the version manually
let version = if let Some(ver) = matches.value_of("set-ver") {
ver.to_string()
} else {
// Increment the one requested (in a real program, we'd reset the lower numbers)
let (maj, min, pat) = (
matches.is_present("major"),
matches.is_present("minor"),
matches.is_present("patch"),
);
match (maj, min, pat) {
(true, _, _) => major += 1,
(_, true, _) => minor += 1,
(_, _, true) => patch += 1,
_ => unreachable!(),
};
format!("{}.{}.{}", major, minor, patch)
};
println!("Version: {}", version);
// Check for usage of -c
if matches.is_present("config") {
let input = matches
.value_of("INPUT_FILE")
.unwrap_or_else(|| matches.value_of("spec-in").unwrap());
println!(
"Doing work using input {} and config {}",
input,
matches.value_of("config").unwrap()
);
}
}
pub 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(arg!("--set-ver [ver] 'set the version manually'"))
.arg(arg!("--major 'auto increase major'"))
.arg(arg!("--minor 'auto increase minor'"))
.arg(arg!("--patch 'auto increase patch'"))
.arg(arg!("-c [FILE] 'a config file'"))
.arg(arg!("-i [IFACE] 'an interface'"))
.groups(&[
ArgGroup::new("vers")
.args(&["set-ver", "major", "minor","patch"])
.required(true),
ArgGroup::new("input")
.args(&["c", "i"])
])
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.
A subcommand’s App::name
will be used for:
- The argument the user passes in
- Programmatically looking up the subcommand
Examples
App::new("myprog")
.subcommand(App::new("config")
.about("Controls configuration features")
.arg(arg!("<config> 'Required configuration file to use'")))
Examples found in repository
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
fn main() {
let matches = app_from_crate!()
.global_setting(AppSettings::PropagateVersion)
.global_setting(AppSettings::UseLongFormatForHelpSubcommand)
.setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(
App::new("add")
.about("Adds files to myapp")
.arg(arg!([NAME])),
)
.get_matches();
match matches.subcommand() {
Some(("add", sub_matches)) => println!(
"'myapp add' was used, name is: {:?}",
sub_matches.value_of("NAME")
),
_ => unreachable!(),
}
}
More examples
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
fn main() {
let app = App::new(env!("CARGO_CRATE_NAME"))
.setting(AppSettings::ArgRequiredElseHelp)
.subcommand_value_name("APPLET")
.subcommand_help_heading("APPLETS")
.subcommand(App::new("hostname").about("show hostname part of FQDN"))
.subcommand(App::new("dnsdomainname").about("show domain name part of FQDN"));
let app = app.setting(AppSettings::Multicall);
match app.get_matches().subcommand_name() {
Some("hostname") => println!("www"),
Some("dnsdomainname") => println!("example.com"),
_ => unreachable!("parser should ensure only valid subcommand names are used"),
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
fn main() {
let app = clap::App::new("cargo")
.bin_name("cargo")
.setting(clap::AppSettings::SubcommandRequired)
.subcommand(
clap::app_from_crate!().name("example").arg(
clap::arg!(--"manifest-path" <PATH>)
.required(false)
.allow_invalid_utf8(true),
),
);
let matches = app.get_matches();
let matches = match matches.subcommand() {
Some(("example", matches)) => matches,
_ => unreachable!("clap should ensure we don't get here"),
};
let manifest_path = matches
.value_of_os("manifest-path")
.map(std::path::PathBuf::from);
println!("{:?}", manifest_path);
}
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
fn main() {
let app = App::new(env!("CARGO_CRATE_NAME"))
.setting(AppSettings::Multicall)
.subcommand(
App::new("busybox")
.setting(AppSettings::ArgRequiredElseHelp)
.subcommand_value_name("APPLET")
.subcommand_help_heading("APPLETS")
.arg(
Arg::new("install")
.long("install")
.help("Install hardlinks for all subcommands in path")
.exclusive(true)
.takes_value(true)
.default_missing_value("/usr/local/bin")
.use_delimiter(false),
)
.subcommands(applet_commands()),
)
.subcommands(applet_commands());
let matches = app.get_matches();
let mut subcommand = matches.subcommand();
if let Some(("busybox", cmd)) = subcommand {
if cmd.occurrences_of("install") > 0 {
unimplemented!("Make hardlinks to the executable here");
}
subcommand = cmd.subcommand();
}
match subcommand {
Some(("false", _)) => exit(1),
Some(("true", _)) => exit(0),
_ => unreachable!("parser should ensure only valid subcommand names are used"),
}
}
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
fn main() {
let matches = app_from_crate!()
.arg(arg!([name] "Optional name to operate on"))
.arg(
arg!(
-c --config <FILE> "Sets a custom config file"
)
// We don't have syntax yet for optional options, so manually calling `required`
.required(false)
// Support non-UTF8 paths
.allow_invalid_utf8(true),
)
.arg(arg!(
-d --debug ... "Turn debugging information on"
))
.subcommand(
App::new("test")
.about("does testing things")
.arg(arg!(-l --list "lists test values")),
)
.get_matches();
// You can check the value provided by positional arguments, or option arguments
if let Some(name) = matches.value_of("name") {
println!("Value for name: {}", name);
}
if let Some(raw_config) = matches.value_of_os("config") {
let config_path = Path::new(raw_config);
println!("Value for config: {}", config_path.display());
}
// You can see how many times a particular flag or argument occurred
// Note, only flags can have multiple occurrences
match matches.occurrences_of("debug") {
0 => println!("Debug mode is off"),
1 => println!("Debug mode is kind of on"),
2 => println!("Debug mode is on"),
_ => println!("Don't be crazy"),
}
// You can check for the existence of subcommands, and if found use their
// matches just as you would the top level app
if let Some(matches) = matches.subcommand_matches("test") {
// "$ myapp test" was run
if matches.is_present("list") {
// "$ myapp test -l" was run
println!("Printing testing lists...");
} else {
println!("Not printing testing lists...");
}
}
// Continued program logic goes here...
}
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
fn main() {
let matches = App::new("git")
.about("A fictional versioning CLI")
.setting(AppSettings::SubcommandRequiredElseHelp)
.setting(AppSettings::AllowExternalSubcommands)
.setting(AppSettings::AllowInvalidUtf8ForExternalSubcommands)
.subcommand(
App::new("clone")
.about("Clones repos")
.arg(arg!(<REMOTE> "The remote to clone"))
.setting(AppSettings::ArgRequiredElseHelp),
)
.subcommand(
App::new("push")
.about("pushes things")
.arg(arg!(<REMOTE> "The remote to target"))
.setting(AppSettings::ArgRequiredElseHelp),
)
.subcommand(
App::new("add")
.about("adds things")
.setting(AppSettings::ArgRequiredElseHelp)
.arg(arg!(<PATH> ... "Stuff to add").allow_invalid_utf8(true)),
)
.get_matches();
match matches.subcommand() {
Some(("clone", sub_matches)) => {
println!(
"Cloning {}",
sub_matches.value_of("REMOTE").expect("required")
);
}
Some(("push", sub_matches)) => {
println!(
"Pushing to {}",
sub_matches.value_of("REMOTE").expect("required")
);
}
Some(("add", sub_matches)) => {
let paths = sub_matches
.values_of_os("PATH")
.unwrap_or_default()
.map(PathBuf::from)
.collect::<Vec<_>>();
println!("Adding {:?}", paths);
}
Some((ext, sub_matches)) => {
let args = sub_matches
.values_of_os("")
.unwrap_or_default()
.collect::<Vec<_>>();
println!("Calling out to {:?} with {:?}", ext, args);
}
_ => unreachable!(), // If all subcommands are defined above, anything else is unreachabe!()
}
// Continued program logic goes here...
}
pub 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.
Examples
.subcommands( vec![
App::new("config").about("Controls configuration functionality")
.arg(Arg::new("config_file").index(1)),
App::new("debug").about("Controls debug functionality")])
Examples found in repository
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
fn main() {
let app = App::new(env!("CARGO_CRATE_NAME"))
.setting(AppSettings::Multicall)
.subcommand(
App::new("busybox")
.setting(AppSettings::ArgRequiredElseHelp)
.subcommand_value_name("APPLET")
.subcommand_help_heading("APPLETS")
.arg(
Arg::new("install")
.long("install")
.help("Install hardlinks for all subcommands in path")
.exclusive(true)
.takes_value(true)
.default_missing_value("/usr/local/bin")
.use_delimiter(false),
)
.subcommands(applet_commands()),
)
.subcommands(applet_commands());
let matches = app.get_matches();
let mut subcommand = matches.subcommand();
if let Some(("busybox", cmd)) = subcommand {
if cmd.occurrences_of("install") > 0 {
unimplemented!("Make hardlinks to the executable here");
}
subcommand = cmd.subcommand();
}
match subcommand {
Some(("false", _)) => exit(1),
Some(("true", _)) => exit(0),
_ => unreachable!("parser should ensure only valid subcommand names are used"),
}
}
Catch problems earlier in the development cycle.
Most error states are handled as asserts under the assumption they are programming mistake and not something to handle at runtime. Rather than relying on tests (manual or automated) that exhaustively test your CLI to ensure the asserts are evaluated, this will run those asserts in a way convenient for running as a test.
Note:: This will not help with asserts in ArgMatches
, those will need exhaustive
testing of your CLI.
Examples
fn app() -> App<'static> {
App::new("foo")
.arg(Arg::new("bar").short('b')
)
}
#[test]
fn verify_app() {
app().debug_assert();
}
fn main() {
let m = app().get_matches_from(vec!["foo", "-b"]);
println!("{}", m.is_present("bar"));
}
Custom error message for post-parsing validation
Examples
let mut app = App::new("myprog");
let err = app.error(ErrorKind::InvalidValue, "Some failure case");
Examples found in repository
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
fn main() {
let cli = Cli::parse();
// Let's assume the old version 1.2.3
let mut major = 1;
let mut minor = 2;
let mut patch = 3;
// See if --set-ver was used to set the version manually
let version = if let Some(ver) = cli.set_ver.as_deref() {
if cli.major || cli.minor || cli.patch {
let mut app = Cli::into_app();
app.error(
ErrorKind::ArgumentConflict,
"Can't do relative and absolute version change",
)
.exit();
}
ver.to_string()
} else {
// Increment the one requested (in a real program, we'd reset the lower numbers)
let (maj, min, pat) = (cli.major, cli.minor, cli.patch);
match (maj, min, pat) {
(true, false, false) => major += 1,
(false, true, false) => minor += 1,
(false, false, true) => patch += 1,
_ => {
let mut app = Cli::into_app();
app.error(
ErrorKind::ArgumentConflict,
"Cam only modify one version field",
)
.exit();
}
};
format!("{}.{}.{}", major, minor, patch)
};
println!("Version: {}", version);
// Check for usage of -c
if let Some(config) = cli.config.as_deref() {
let input = cli
.input_file
.as_deref()
.or_else(|| cli.spec_in.as_deref())
.unwrap_or_else(|| {
let mut app = Cli::into_app();
app.error(
ErrorKind::MissingRequiredArgument,
"INPUT_FILE or --spec-in is required when using --config",
)
.exit()
});
println!("Doing work using input {} and config {}", input, config);
}
}
More examples
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
fn main() {
// Create application like normal
let mut app = app_from_crate!()
// Add the version arguments
.arg(arg!(--"set-ver" <VER> "set version manually").required(false))
.arg(arg!(--major "auto inc major"))
.arg(arg!(--minor "auto inc minor"))
.arg(arg!(--patch "auto inc patch"))
// Arguments can also be added to a group individually, these two arguments
// are part of the "input" group which is not required
.arg(arg!([INPUT_FILE] "some regular input"))
.arg(arg!(--"spec-in" <SPEC_IN> "some special input argument").required(false))
// Now let's assume we have a -c [config] argument which requires one of
// (but **not** both) the "input" arguments
.arg(arg!(config: -c <CONFIG>).required(false));
let matches = app.get_matches_mut();
// Let's assume the old version 1.2.3
let mut major = 1;
let mut minor = 2;
let mut patch = 3;
// See if --set-ver was used to set the version manually
let version = if let Some(ver) = matches.value_of("set-ver") {
if matches.is_present("major") || matches.is_present("minor") || matches.is_present("patch")
{
app.error(
ErrorKind::ArgumentConflict,
"Can't do relative and absolute version change",
)
.exit();
}
ver.to_string()
} else {
// Increment the one requested (in a real program, we'd reset the lower numbers)
let (maj, min, pat) = (
matches.is_present("major"),
matches.is_present("minor"),
matches.is_present("patch"),
);
match (maj, min, pat) {
(true, false, false) => major += 1,
(false, true, false) => minor += 1,
(false, false, true) => patch += 1,
_ => {
app.error(
ErrorKind::ArgumentConflict,
"Cam only modify one version field",
)
.exit();
}
};
format!("{}.{}.{}", major, minor, patch)
};
println!("Version: {}", version);
// Check for usage of -c
if matches.is_present("config") {
let input = matches
.value_of("INPUT_FILE")
.or_else(|| matches.value_of("spec-in"))
.unwrap_or_else(|| {
app.error(
ErrorKind::MissingRequiredArgument,
"INPUT_FILE or --spec-in is required when using --config",
)
.exit()
});
println!(
"Doing work using input {} and config {}",
input,
matches.value_of("config").unwrap()
);
}
}
Parse env::args_os
, exiting on failure.
Panics
If contradictory arguments or settings exist.
Examples
let matches = App::new("myprog")
// Args and options go here...
.get_matches();
Examples found in repository
More examples
3 4 5 6 7 8 9 10 11 12 13 14
fn main() {
let matches = app_from_crate!()
.arg(arg!([NAME]).default_value("alice"))
.get_matches();
println!(
"NAME: {:?}",
matches
.value_of("NAME")
.expect("default ensures there is always a value")
);
}
- examples/tutorial_builder/02_apps.rs
- examples/tutorial_builder/04_02_validate.rs
- examples/tutorial_builder/02_app_settings.rs
- examples/tutorial_builder/04_01_enum.rs
- examples/tutorial_builder/04_01_possible.rs
- examples/tutorial_builder/03_04_subcommands.rs
- examples/multicall-hostname.rs
- examples/cargo-example.rs
- examples/escaped-positional.rs
- examples/multicall-busybox.rs
- examples/tutorial_builder/01_quick.rs
- examples/git.rs
- examples/tutorial_builder/04_03_relations.rs
- examples/pacman.rs
Parse env::args_os
, exiting on failure.
Like App::get_matches
but doesn’t consume the App
.
Panics
If contradictory arguments or settings exist.
Examples
let mut app = App::new("myprog")
// Args and options go here...
;
let matches = app.get_matches_mut();
Examples found in repository
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
fn main() {
// Create application like normal
let mut app = app_from_crate!()
// Add the version arguments
.arg(arg!(--"set-ver" <VER> "set version manually").required(false))
.arg(arg!(--major "auto inc major"))
.arg(arg!(--minor "auto inc minor"))
.arg(arg!(--patch "auto inc patch"))
// Arguments can also be added to a group individually, these two arguments
// are part of the "input" group which is not required
.arg(arg!([INPUT_FILE] "some regular input"))
.arg(arg!(--"spec-in" <SPEC_IN> "some special input argument").required(false))
// Now let's assume we have a -c [config] argument which requires one of
// (but **not** both) the "input" arguments
.arg(arg!(config: -c <CONFIG>).required(false));
let matches = app.get_matches_mut();
// Let's assume the old version 1.2.3
let mut major = 1;
let mut minor = 2;
let mut patch = 3;
// See if --set-ver was used to set the version manually
let version = if let Some(ver) = matches.value_of("set-ver") {
if matches.is_present("major") || matches.is_present("minor") || matches.is_present("patch")
{
app.error(
ErrorKind::ArgumentConflict,
"Can't do relative and absolute version change",
)
.exit();
}
ver.to_string()
} else {
// Increment the one requested (in a real program, we'd reset the lower numbers)
let (maj, min, pat) = (
matches.is_present("major"),
matches.is_present("minor"),
matches.is_present("patch"),
);
match (maj, min, pat) {
(true, false, false) => major += 1,
(false, true, false) => minor += 1,
(false, false, true) => patch += 1,
_ => {
app.error(
ErrorKind::ArgumentConflict,
"Cam only modify one version field",
)
.exit();
}
};
format!("{}.{}.{}", major, minor, patch)
};
println!("Version: {}", version);
// Check for usage of -c
if matches.is_present("config") {
let input = matches
.value_of("INPUT_FILE")
.or_else(|| matches.value_of("spec-in"))
.unwrap_or_else(|| {
app.error(
ErrorKind::MissingRequiredArgument,
"INPUT_FILE or --spec-in is required when using --config",
)
.exit()
});
println!(
"Doing work using input {} and config {}",
input,
matches.value_of("config").unwrap()
);
}
}
Parse env::args_os
, returning a clap::Result
on failure.
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
.
Panics
If contradictory arguments or settings exist.
Examples
let matches = App::new("myprog")
// Args and options go here...
.try_get_matches()
.unwrap_or_else(|e| e.exit());
pub 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,
Parse the specified arguments, exiting on failure.
NOTE: The first argument will be parsed as the binary name unless
AppSettings::NoBinaryName
is used.
Panics
If contradictory arguments or settings exist.
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);
pub 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,
Parse the specified arguments, returning a clap::Result
on failure.
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.
Panics
If contradictory arguments or settings exist.
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());
pub 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,
Parse the specified arguments, returning a clap::Result
on failure.
Like App::try_get_matches_from
but doesn’t consume the App
.
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.
Panics
If contradictory arguments or settings exist.
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());
Prints the short help message (-h
) to io::stdout()
.
See also App::print_long_help
.
Examples
let mut app = App::new("myprog");
app.print_help();
Prints the long help message (--help
) to io::stdout()
.
See also App::print_help
.
Examples
let mut app = App::new("myprog");
app.print_long_help();
Writes the short help message (-h
) to a io::Write
object.
See also App::write_long_help
.
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");
Writes the long help message (--help
) to a io::Write
object.
See also App::write_help
.
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");
Version message rendered as if the user ran -V
.
See also App::render_long_version
.
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());
Version message rendered as if the user ran --version
.
See also App::render_version
.
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());
Usage statement
Examples
use std::io;
let mut app = App::new("myprog");
println!("{}", app.render_usage());
App Settings
(Re)Sets the program’s name.
See App::new
for more details.
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.
Examples found in repository
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
fn main() {
let app = clap::App::new("cargo")
.bin_name("cargo")
.setting(clap::AppSettings::SubcommandRequired)
.subcommand(
clap::app_from_crate!().name("example").arg(
clap::arg!(--"manifest-path" <PATH>)
.required(false)
.allow_invalid_utf8(true),
),
);
let matches = app.get_matches();
let matches = match matches.subcommand() {
Some(("example", matches)) => matches,
_ => unreachable!("clap should ensure we don't get here"),
};
let manifest_path = matches
.value_of_os("manifest-path")
.map(std::path::PathBuf::from);
println!("{:?}", manifest_path);
}
Overrides the runtime-determined name of the binary for help and error messages.
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.
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")
Examples found in repository
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
fn main() {
let app = clap::App::new("cargo")
.bin_name("cargo")
.setting(clap::AppSettings::SubcommandRequired)
.subcommand(
clap::app_from_crate!().name("example").arg(
clap::arg!(--"manifest-path" <PATH>)
.required(false)
.allow_invalid_utf8(true),
),
);
let matches = app.get_matches();
let matches = match matches.subcommand() {
Some(("example", matches)) => matches,
_ => unreachable!("clap should ensure we don't get here"),
};
let manifest_path = matches
.value_of_os("manifest-path")
.map(std::path::PathBuf::from);
println!("{:?}", manifest_path);
}
Sets the author(s) for 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.
Examples
App::new("myprog")
.author("Me, me@mymain.com")
Examples found in repository
3 4 5 6 7 8 9 10 11 12 13 14
fn main() {
let matches = App::new("MyApp")
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>")
.about("Does awesome things")
.arg(arg!(--two <VALUE>))
.arg(arg!(--one <VALUE>))
.get_matches();
println!("two: {:?}", matches.value_of("two").expect("required"));
println!("one: {:?}", matches.value_of("one").expect("required"));
}
More examples
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
fn main() {
let matches = App::new("pacman")
.about("package manager utility")
.version("5.2.1")
.setting(AppSettings::SubcommandRequiredElseHelp)
.author("Pacman Development Team")
// Query subcommand
//
// Only a few of its arguments are implemented below.
.subcommand(
App::new("query")
.short_flag('Q')
.long_flag("query")
.about("Query the package database.")
.arg(
Arg::new("search")
.short('s')
.long("search")
.help("search locally installed packages for matching strings")
.conflicts_with("info")
.takes_value(true)
.multiple_values(true),
)
.arg(
Arg::new("info")
.long("info")
.short('i')
.conflicts_with("search")
.help("view package information")
.takes_value(true)
.multiple_values(true),
),
)
// Sync subcommand
//
// Only a few of its arguments are implemented below.
.subcommand(
App::new("sync")
.short_flag('S')
.long_flag("sync")
.about("Synchronize packages.")
.arg(
Arg::new("search")
.short('s')
.long("search")
.conflicts_with("info")
.takes_value(true)
.multiple_values(true)
.help("search remote repositories for matching strings"),
)
.arg(
Arg::new("info")
.long("info")
.conflicts_with("search")
.short('i')
.help("view package information"),
)
.arg(
Arg::new("package")
.help("packages")
.required_unless_present("search")
.takes_value(true)
.multiple_values(true),
),
)
.get_matches();
match matches.subcommand() {
Some(("sync", sync_matches)) => {
if sync_matches.is_present("search") {
let packages: Vec<_> = sync_matches.values_of("search").unwrap().collect();
let values = packages.join(", ");
println!("Searching for {}...", values);
return;
}
let packages: Vec<_> = sync_matches.values_of("package").unwrap().collect();
let values = packages.join(", ");
if sync_matches.is_present("info") {
println!("Retrieving info for {}...", values);
} else {
println!("Installing {}...", values);
}
}
Some(("query", query_matches)) => {
if let Some(packages) = query_matches.values_of("info") {
let comma_sep = packages.collect::<Vec<_>>().join(", ");
println!("Retrieving info for {}...", comma_sep);
} else if let Some(queries) = query_matches.values_of("search") {
let comma_sep = queries.collect::<Vec<_>>().join(", ");
println!("Searching Locally for {}...", comma_sep);
} else {
println!("Displaying all locally installed packages...");
}
}
_ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
}
}
Sets the program’s description for the short help (-h
).
If App::long_about
is not specified, this message will be displayed for --help
.
NOTE: Only App::about
(short format) is used in completion
script generation in order to be concise.
See also crate_description!
.
Examples
App::new("myprog")
.about("Does really amazing things for great people")
Examples found in repository
More examples
3 4 5 6 7 8 9 10 11 12 13 14
fn main() {
let matches = App::new("MyApp")
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>")
.about("Does awesome things")
.arg(arg!(--two <VALUE>))
.arg(arg!(--one <VALUE>))
.get_matches();
println!("two: {:?}", matches.value_of("two").expect("required"));
println!("one: {:?}", matches.value_of("one").expect("required"));
}
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
fn main() {
let matches = app_from_crate!()
.global_setting(AppSettings::PropagateVersion)
.global_setting(AppSettings::UseLongFormatForHelpSubcommand)
.setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(
App::new("add")
.about("Adds files to myapp")
.arg(arg!([NAME])),
)
.get_matches();
match matches.subcommand() {
Some(("add", sub_matches)) => println!(
"'myapp add' was used, name is: {:?}",
sub_matches.value_of("NAME")
),
_ => unreachable!(),
}
}
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
fn main() {
let app = App::new(env!("CARGO_CRATE_NAME"))
.setting(AppSettings::ArgRequiredElseHelp)
.subcommand_value_name("APPLET")
.subcommand_help_heading("APPLETS")
.subcommand(App::new("hostname").about("show hostname part of FQDN"))
.subcommand(App::new("dnsdomainname").about("show domain name part of FQDN"));
let app = app.setting(AppSettings::Multicall);
match app.get_matches().subcommand_name() {
Some("hostname") => println!("www"),
Some("dnsdomainname") => println!("example.com"),
_ => unreachable!("parser should ensure only valid subcommand names are used"),
}
}
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
fn main() {
let matches = app_from_crate!()
.arg(arg!([name] "Optional name to operate on"))
.arg(
arg!(
-c --config <FILE> "Sets a custom config file"
)
// We don't have syntax yet for optional options, so manually calling `required`
.required(false)
// Support non-UTF8 paths
.allow_invalid_utf8(true),
)
.arg(arg!(
-d --debug ... "Turn debugging information on"
))
.subcommand(
App::new("test")
.about("does testing things")
.arg(arg!(-l --list "lists test values")),
)
.get_matches();
// You can check the value provided by positional arguments, or option arguments
if let Some(name) = matches.value_of("name") {
println!("Value for name: {}", name);
}
if let Some(raw_config) = matches.value_of_os("config") {
let config_path = Path::new(raw_config);
println!("Value for config: {}", config_path.display());
}
// You can see how many times a particular flag or argument occurred
// Note, only flags can have multiple occurrences
match matches.occurrences_of("debug") {
0 => println!("Debug mode is off"),
1 => println!("Debug mode is kind of on"),
2 => println!("Debug mode is on"),
_ => println!("Don't be crazy"),
}
// You can check for the existence of subcommands, and if found use their
// matches just as you would the top level app
if let Some(matches) = matches.subcommand_matches("test") {
// "$ myapp test" was run
if matches.is_present("list") {
// "$ myapp test -l" was run
println!("Printing testing lists...");
} else {
println!("Not printing testing lists...");
}
}
// Continued program logic goes here...
}
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
fn main() {
let matches = App::new("git")
.about("A fictional versioning CLI")
.setting(AppSettings::SubcommandRequiredElseHelp)
.setting(AppSettings::AllowExternalSubcommands)
.setting(AppSettings::AllowInvalidUtf8ForExternalSubcommands)
.subcommand(
App::new("clone")
.about("Clones repos")
.arg(arg!(<REMOTE> "The remote to clone"))
.setting(AppSettings::ArgRequiredElseHelp),
)
.subcommand(
App::new("push")
.about("pushes things")
.arg(arg!(<REMOTE> "The remote to target"))
.setting(AppSettings::ArgRequiredElseHelp),
)
.subcommand(
App::new("add")
.about("adds things")
.setting(AppSettings::ArgRequiredElseHelp)
.arg(arg!(<PATH> ... "Stuff to add").allow_invalid_utf8(true)),
)
.get_matches();
match matches.subcommand() {
Some(("clone", sub_matches)) => {
println!(
"Cloning {}",
sub_matches.value_of("REMOTE").expect("required")
);
}
Some(("push", sub_matches)) => {
println!(
"Pushing to {}",
sub_matches.value_of("REMOTE").expect("required")
);
}
Some(("add", sub_matches)) => {
let paths = sub_matches
.values_of_os("PATH")
.unwrap_or_default()
.map(PathBuf::from)
.collect::<Vec<_>>();
println!("Adding {:?}", paths);
}
Some((ext, sub_matches)) => {
let args = sub_matches
.values_of_os("")
.unwrap_or_default()
.collect::<Vec<_>>();
println!("Calling out to {:?} with {:?}", ext, args);
}
_ => unreachable!(), // If all subcommands are defined above, anything else is unreachabe!()
}
// Continued program logic goes here...
}
Sets the program’s description for the long help (--help
).
If App::about
is not specified, this message will be displayed for -h
.
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!")
Free-form help text for after auto-generated short help (-h
).
This is often used to describe how to use the arguments, caveats to be noted, or license and contact information.
If App::after_long_help
is not specified, this message will be displayed for --help
.
Examples
App::new("myprog")
.after_help("Does really amazing things for great people... but be careful with -R!")
Free-form help text for after auto-generated long help (--help
).
This is often used to describe how to use the arguments, caveats to be noted, or license and contact information.
If App::after_help
is not specified, this message will be displayed for -h
.
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!")
Free-form help text for before auto-generated short help (-h
).
This is often used for header, copyright, or license information.
If App::before_long_help
is not specified, this message will be displayed for --help
.
Examples
App::new("myprog")
.before_help("Some info I'd like to appear before the help info")
Free-form help text for before auto-generated long help (--help
).
This is often used for header, copyright, or license information.
If App::before_help
is not specified, this message will be displayed for -h
.
Examples
App::new("myprog")
.before_long_help("Some verbose and long info I'd like to appear before the help info")
Sets the version for the short version (-V
) and help messages.
If App::long_version
is not specified, this message will be displayed for --version
.
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.
Examples
App::new("myprog")
.version("v0.1.24")
Examples found in repository
3 4 5 6 7 8 9 10 11 12 13 14
fn main() {
let matches = App::new("MyApp")
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>")
.about("Does awesome things")
.arg(arg!(--two <VALUE>))
.arg(arg!(--one <VALUE>))
.get_matches();
println!("two: {:?}", matches.value_of("two").expect("required"));
println!("one: {:?}", matches.value_of("one").expect("required"));
}
More examples
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
fn main() {
let matches = App::new("pacman")
.about("package manager utility")
.version("5.2.1")
.setting(AppSettings::SubcommandRequiredElseHelp)
.author("Pacman Development Team")
// Query subcommand
//
// Only a few of its arguments are implemented below.
.subcommand(
App::new("query")
.short_flag('Q')
.long_flag("query")
.about("Query the package database.")
.arg(
Arg::new("search")
.short('s')
.long("search")
.help("search locally installed packages for matching strings")
.conflicts_with("info")
.takes_value(true)
.multiple_values(true),
)
.arg(
Arg::new("info")
.long("info")
.short('i')
.conflicts_with("search")
.help("view package information")
.takes_value(true)
.multiple_values(true),
),
)
// Sync subcommand
//
// Only a few of its arguments are implemented below.
.subcommand(
App::new("sync")
.short_flag('S')
.long_flag("sync")
.about("Synchronize packages.")
.arg(
Arg::new("search")
.short('s')
.long("search")
.conflicts_with("info")
.takes_value(true)
.multiple_values(true)
.help("search remote repositories for matching strings"),
)
.arg(
Arg::new("info")
.long("info")
.conflicts_with("search")
.short('i')
.help("view package information"),
)
.arg(
Arg::new("package")
.help("packages")
.required_unless_present("search")
.takes_value(true)
.multiple_values(true),
),
)
.get_matches();
match matches.subcommand() {
Some(("sync", sync_matches)) => {
if sync_matches.is_present("search") {
let packages: Vec<_> = sync_matches.values_of("search").unwrap().collect();
let values = packages.join(", ");
println!("Searching for {}...", values);
return;
}
let packages: Vec<_> = sync_matches.values_of("package").unwrap().collect();
let values = packages.join(", ");
if sync_matches.is_present("info") {
println!("Retrieving info for {}...", values);
} else {
println!("Installing {}...", values);
}
}
Some(("query", query_matches)) => {
if let Some(packages) = query_matches.values_of("info") {
let comma_sep = packages.collect::<Vec<_>>().join(", ");
println!("Retrieving info for {}...", comma_sep);
} else if let Some(queries) = query_matches.values_of("search") {
let comma_sep = queries.collect::<Vec<_>>().join(", ");
println!("Searching Locally for {}...", comma_sep);
} else {
println!("Displaying all locally installed packages...");
}
}
_ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
}
}
Sets the version for the long version (--version
) and help messages.
If App::version
is not specified, this message will be displayed for -V
.
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.
Examples
App::new("myprog")
.long_version(
"v0.1.24
commit: abcdef89726d
revision: 123
release: 2
binary: myprog")
Overrides the clap
generated usage string for help and error messages.
NOTE: 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!
Examples
App::new("myprog")
.override_usage("myapp [-clDas] <some_file>")
Overrides the clap
generated help message (both -h
and --help
).
This should only be used when the auto-generated message does not suffice.
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> <command>\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\
Commands:\n\
help Print this message\n\
work Do some work")
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}")
Apply a setting for the current command or subcommand.
See App::global_setting
to apply a setting to this command and all subcommands.
See AppSettings
for a full list of possibilities and examples.
Examples
App::new("myprog")
.setting(AppSettings::SubcommandRequired)
.setting(AppSettings::AllowLeadingHyphen)
or
App::new("myprog")
.setting(AppSettings::SubcommandRequired | AppSettings::AllowLeadingHyphen)
Examples found in repository
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
fn main() {
let matches = app_from_crate!()
.global_setting(AppSettings::PropagateVersion)
.global_setting(AppSettings::UseLongFormatForHelpSubcommand)
.setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(
App::new("add")
.about("Adds files to myapp")
.arg(arg!([NAME])),
)
.get_matches();
match matches.subcommand() {
Some(("add", sub_matches)) => println!(
"'myapp add' was used, name is: {:?}",
sub_matches.value_of("NAME")
),
_ => unreachable!(),
}
}
More examples
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
fn main() {
let app = App::new(env!("CARGO_CRATE_NAME"))
.setting(AppSettings::ArgRequiredElseHelp)
.subcommand_value_name("APPLET")
.subcommand_help_heading("APPLETS")
.subcommand(App::new("hostname").about("show hostname part of FQDN"))
.subcommand(App::new("dnsdomainname").about("show domain name part of FQDN"));
let app = app.setting(AppSettings::Multicall);
match app.get_matches().subcommand_name() {
Some("hostname") => println!("www"),
Some("dnsdomainname") => println!("example.com"),
_ => unreachable!("parser should ensure only valid subcommand names are used"),
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
fn main() {
let app = clap::App::new("cargo")
.bin_name("cargo")
.setting(clap::AppSettings::SubcommandRequired)
.subcommand(
clap::app_from_crate!().name("example").arg(
clap::arg!(--"manifest-path" <PATH>)
.required(false)
.allow_invalid_utf8(true),
),
);
let matches = app.get_matches();
let matches = match matches.subcommand() {
Some(("example", matches)) => matches,
_ => unreachable!("clap should ensure we don't get here"),
};
let manifest_path = matches
.value_of_os("manifest-path")
.map(std::path::PathBuf::from);
println!("{:?}", manifest_path);
}
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
fn main() {
let app = App::new(env!("CARGO_CRATE_NAME"))
.setting(AppSettings::Multicall)
.subcommand(
App::new("busybox")
.setting(AppSettings::ArgRequiredElseHelp)
.subcommand_value_name("APPLET")
.subcommand_help_heading("APPLETS")
.arg(
Arg::new("install")
.long("install")
.help("Install hardlinks for all subcommands in path")
.exclusive(true)
.takes_value(true)
.default_missing_value("/usr/local/bin")
.use_delimiter(false),
)
.subcommands(applet_commands()),
)
.subcommands(applet_commands());
let matches = app.get_matches();
let mut subcommand = matches.subcommand();
if let Some(("busybox", cmd)) = subcommand {
if cmd.occurrences_of("install") > 0 {
unimplemented!("Make hardlinks to the executable here");
}
subcommand = cmd.subcommand();
}
match subcommand {
Some(("false", _)) => exit(1),
Some(("true", _)) => exit(0),
_ => unreachable!("parser should ensure only valid subcommand names are used"),
}
}
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
fn main() {
let matches = App::new("git")
.about("A fictional versioning CLI")
.setting(AppSettings::SubcommandRequiredElseHelp)
.setting(AppSettings::AllowExternalSubcommands)
.setting(AppSettings::AllowInvalidUtf8ForExternalSubcommands)
.subcommand(
App::new("clone")
.about("Clones repos")
.arg(arg!(<REMOTE> "The remote to clone"))
.setting(AppSettings::ArgRequiredElseHelp),
)
.subcommand(
App::new("push")
.about("pushes things")
.arg(arg!(<REMOTE> "The remote to target"))
.setting(AppSettings::ArgRequiredElseHelp),
)
.subcommand(
App::new("add")
.about("adds things")
.setting(AppSettings::ArgRequiredElseHelp)
.arg(arg!(<PATH> ... "Stuff to add").allow_invalid_utf8(true)),
)
.get_matches();
match matches.subcommand() {
Some(("clone", sub_matches)) => {
println!(
"Cloning {}",
sub_matches.value_of("REMOTE").expect("required")
);
}
Some(("push", sub_matches)) => {
println!(
"Pushing to {}",
sub_matches.value_of("REMOTE").expect("required")
);
}
Some(("add", sub_matches)) => {
let paths = sub_matches
.values_of_os("PATH")
.unwrap_or_default()
.map(PathBuf::from)
.collect::<Vec<_>>();
println!("Adding {:?}", paths);
}
Some((ext, sub_matches)) => {
let args = sub_matches
.values_of_os("")
.unwrap_or_default()
.collect::<Vec<_>>();
println!("Calling out to {:?} with {:?}", ext, args);
}
_ => unreachable!(), // If all subcommands are defined above, anything else is unreachabe!()
}
// Continued program logic goes here...
}
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
fn main() {
let matches = App::new("pacman")
.about("package manager utility")
.version("5.2.1")
.setting(AppSettings::SubcommandRequiredElseHelp)
.author("Pacman Development Team")
// Query subcommand
//
// Only a few of its arguments are implemented below.
.subcommand(
App::new("query")
.short_flag('Q')
.long_flag("query")
.about("Query the package database.")
.arg(
Arg::new("search")
.short('s')
.long("search")
.help("search locally installed packages for matching strings")
.conflicts_with("info")
.takes_value(true)
.multiple_values(true),
)
.arg(
Arg::new("info")
.long("info")
.short('i')
.conflicts_with("search")
.help("view package information")
.takes_value(true)
.multiple_values(true),
),
)
// Sync subcommand
//
// Only a few of its arguments are implemented below.
.subcommand(
App::new("sync")
.short_flag('S')
.long_flag("sync")
.about("Synchronize packages.")
.arg(
Arg::new("search")
.short('s')
.long("search")
.conflicts_with("info")
.takes_value(true)
.multiple_values(true)
.help("search remote repositories for matching strings"),
)
.arg(
Arg::new("info")
.long("info")
.conflicts_with("search")
.short('i')
.help("view package information"),
)
.arg(
Arg::new("package")
.help("packages")
.required_unless_present("search")
.takes_value(true)
.multiple_values(true),
),
)
.get_matches();
match matches.subcommand() {
Some(("sync", sync_matches)) => {
if sync_matches.is_present("search") {
let packages: Vec<_> = sync_matches.values_of("search").unwrap().collect();
let values = packages.join(", ");
println!("Searching for {}...", values);
return;
}
let packages: Vec<_> = sync_matches.values_of("package").unwrap().collect();
let values = packages.join(", ");
if sync_matches.is_present("info") {
println!("Retrieving info for {}...", values);
} else {
println!("Installing {}...", values);
}
}
Some(("query", query_matches)) => {
if let Some(packages) = query_matches.values_of("info") {
let comma_sep = packages.collect::<Vec<_>>().join(", ");
println!("Retrieving info for {}...", comma_sep);
} else if let Some(queries) = query_matches.values_of("search") {
let comma_sep = queries.collect::<Vec<_>>().join(", ");
println!("Searching Locally for {}...", comma_sep);
} else {
println!("Displaying all locally installed packages...");
}
}
_ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
}
}
Remove a setting for the current command or subcommand.
See AppSettings
for a full list of possibilities and examples.
Examples
App::new("myprog")
.unset_setting(AppSettings::SubcommandRequired)
.setting(AppSettings::AllowLeadingHyphen)
or
App::new("myprog")
.unset_setting(AppSettings::SubcommandRequired | AppSettings::AllowLeadingHyphen)
Apply a setting for the current command and all subcommands.
See App::setting
to apply a setting only to this command.
See AppSettings
for a full list of possibilities and examples.
Examples
App::new("myprog")
.global_setting(AppSettings::AllowNegativeNumbers)
Examples found in repository
3 4 5 6 7 8 9 10 11 12 13 14
fn main() {
let matches = app_from_crate!()
.global_setting(AppSettings::AllArgsOverrideSelf)
.global_setting(AppSettings::DeriveDisplayOrder)
.global_setting(AppSettings::AllowNegativeNumbers)
.arg(arg!(--two <VALUE>))
.arg(arg!(--one <VALUE>))
.get_matches();
println!("two: {:?}", matches.value_of("two").expect("required"));
println!("one: {:?}", matches.value_of("one").expect("required"));
}
More examples
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
fn main() {
let matches = app_from_crate!()
.global_setting(AppSettings::PropagateVersion)
.global_setting(AppSettings::UseLongFormatForHelpSubcommand)
.setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(
App::new("add")
.about("Adds files to myapp")
.arg(arg!([NAME])),
)
.get_matches();
match matches.subcommand() {
Some(("add", sub_matches)) => println!(
"'myapp add' was used, name is: {:?}",
sub_matches.value_of("NAME")
),
_ => unreachable!(),
}
}
Remove a setting and stop propagating down to subcommands.
See AppSettings
for a full list of possibilities and examples.
Examples
App::new("myprog")
.unset_global_setting(AppSettings::AllowNegativeNumbers)
Sets when to color output.
NOTE: This choice is propagated to all child subcommands.
NOTE: Default behaviour is ColorChoice::Auto
.
Examples
App::new("myprog")
.color(ColorChoice::Never)
.get_matches();
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.
For subcommands, see App::subcommand_help_heading
Sets the terminal width at which to wrap help messages.
Using 0
will ignore terminal widths and use source formatting.
Defaults to current terminal width when wrap_help
feature flag is enabled. If the flag
is disabled or it cannot be determined, the default is 100.
NOTE: This setting applies globally and not on a per-command basis.
Examples
App::new("myprog")
.term_width(80)
Sets the maximum terminal width at which to wrap help messages.
This only applies when setting the current terminal width. See App::term_width
for
more details.
Using 0
will ignore terminal widths and use source formatting.
NOTE: This setting applies globally and not on a per-command basis.
Examples
App::new("myprog")
.max_term_width(100)
Replaces an argument or subcommand used on the CLI at runtime with other arguments or subcommands.
Note: This is gated behind unstable-replace
When this method is used, name
is removed from the CLI, and target
is inserted in its place. Parsing continues as if the user typed
target
instead of name
.
This can be used to create “shortcuts” for subcommands, or if a particular argument has the semantic meaning of several other specific arguments and values.
Examples
We’ll start with the “subcommand short” example. In this example, let’s
assume we have a program with a subcommand module
which can be invoked
via app module
. Now let’s also assume module
also has a subcommand
called install
which can be invoked app module install
. If for some
reason users needed to be able to reach app module install
via the
short-hand app install
, we’d have several options.
We could create another sibling subcommand to module
called
install
, but then we would need to manage another subcommand and manually
dispatch to app module install
handling code. This is error prone and
tedious.
We could instead use App::replace
so that, when the user types app install
, clap
will replace install
with module install
which will
end up getting parsed as if the user typed the entire incantation.
let m = App::new("app")
.subcommand(App::new("module")
.subcommand(App::new("install")))
.replace("install", &["module", "install"])
.get_matches_from(vec!["app", "install"]);
assert!(m.subcommand_matches("module").is_some());
assert!(m.subcommand_matches("module").unwrap().subcommand_matches("install").is_some());
Now let’s show an argument example!
Let’s assume we have an application with two flags --save-context
and
--save-runtime
. But often users end up needing to do both at the
same time. We can add a third flag --save-all
which semantically means
the same thing as app --save-context --save-runtime
. To implement that,
we have several options.
We could create this third argument and manually check if that argument
and in our own consumer code handle the fact that both --save-context
and --save-runtime
should have been used. But again this is error
prone and tedious. If we had code relying on checking --save-context
and we forgot to update that code to also check --save-all
it’d mean
an error!
Luckily we can use App::replace
so that when the user types
--save-all
, clap
will replace that argument with --save-context --save-runtime
, and parsing will continue like normal. Now all our code
that was originally checking for things like --save-context
doesn’t
need to change!
let m = App::new("app")
.arg(Arg::new("save-context")
.long("save-context"))
.arg(Arg::new("save-runtime")
.long("save-runtime"))
.replace("--save-all", &["--save-context", "--save-runtime"])
.get_matches_from(vec!["app", "--save-all"]);
assert!(m.is_present("save-context"));
assert!(m.is_present("save-runtime"));
This can also be used with options, for example if our application with
--save-*
above also had a --format=TYPE
option. Let’s say it
accepted txt
or json
values. However, when --save-all
is used,
only --format=json
is allowed, or valid. We could change the example
above to enforce this:
let m = App::new("app")
.arg(Arg::new("save-context")
.long("save-context"))
.arg(Arg::new("save-runtime")
.long("save-runtime"))
.arg(Arg::new("format")
.long("format")
.takes_value(true)
.possible_values(["txt", "json"]))
.replace("--save-all", &["--save-context", "--save-runtime", "--format=json"])
.get_matches_from(vec!["app", "--save-all"]);
assert!(m.is_present("save-context"));
assert!(m.is_present("save-runtime"));
assert_eq!(m.value_of("format"), Some("json"));
Subcommand-specific Settings
Sets the short version of the subcommand flag without the preceding -
.
Allows the subcommand to be used as if it were an Arg::short
.
Examples
let matches = App::new("pacman")
.subcommand(
App::new("sync").short_flag('S').arg(
Arg::new("search")
.short('s')
.long("search")
.help("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"));
Examples found in repository
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
fn main() {
let matches = App::new("pacman")
.about("package manager utility")
.version("5.2.1")
.setting(AppSettings::SubcommandRequiredElseHelp)
.author("Pacman Development Team")
// Query subcommand
//
// Only a few of its arguments are implemented below.
.subcommand(
App::new("query")
.short_flag('Q')
.long_flag("query")
.about("Query the package database.")
.arg(
Arg::new("search")
.short('s')
.long("search")
.help("search locally installed packages for matching strings")
.conflicts_with("info")
.takes_value(true)
.multiple_values(true),
)
.arg(
Arg::new("info")
.long("info")
.short('i')
.conflicts_with("search")
.help("view package information")
.takes_value(true)
.multiple_values(true),
),
)
// Sync subcommand
//
// Only a few of its arguments are implemented below.
.subcommand(
App::new("sync")
.short_flag('S')
.long_flag("sync")
.about("Synchronize packages.")
.arg(
Arg::new("search")
.short('s')
.long("search")
.conflicts_with("info")
.takes_value(true)
.multiple_values(true)
.help("search remote repositories for matching strings"),
)
.arg(
Arg::new("info")
.long("info")
.conflicts_with("search")
.short('i')
.help("view package information"),
)
.arg(
Arg::new("package")
.help("packages")
.required_unless_present("search")
.takes_value(true)
.multiple_values(true),
),
)
.get_matches();
match matches.subcommand() {
Some(("sync", sync_matches)) => {
if sync_matches.is_present("search") {
let packages: Vec<_> = sync_matches.values_of("search").unwrap().collect();
let values = packages.join(", ");
println!("Searching for {}...", values);
return;
}
let packages: Vec<_> = sync_matches.values_of("package").unwrap().collect();
let values = packages.join(", ");
if sync_matches.is_present("info") {
println!("Retrieving info for {}...", values);
} else {
println!("Installing {}...", values);
}
}
Some(("query", query_matches)) => {
if let Some(packages) = query_matches.values_of("info") {
let comma_sep = packages.collect::<Vec<_>>().join(", ");
println!("Retrieving info for {}...", comma_sep);
} else if let Some(queries) = query_matches.values_of("search") {
let comma_sep = queries.collect::<Vec<_>>().join(", ");
println!("Searching Locally for {}...", comma_sep);
} else {
println!("Displaying all locally installed packages...");
}
}
_ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
}
}
Sets the long version of the subcommand flag without the preceding --
.
Allows the subcommand to be used as if it were an Arg::long
.
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")
.help("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"));
Examples found in repository
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
fn main() {
let matches = App::new("pacman")
.about("package manager utility")
.version("5.2.1")
.setting(AppSettings::SubcommandRequiredElseHelp)
.author("Pacman Development Team")
// Query subcommand
//
// Only a few of its arguments are implemented below.
.subcommand(
App::new("query")
.short_flag('Q')
.long_flag("query")
.about("Query the package database.")
.arg(
Arg::new("search")
.short('s')
.long("search")
.help("search locally installed packages for matching strings")
.conflicts_with("info")
.takes_value(true)
.multiple_values(true),
)
.arg(
Arg::new("info")
.long("info")
.short('i')
.conflicts_with("search")
.help("view package information")
.takes_value(true)
.multiple_values(true),
),
)
// Sync subcommand
//
// Only a few of its arguments are implemented below.
.subcommand(
App::new("sync")
.short_flag('S')
.long_flag("sync")
.about("Synchronize packages.")
.arg(
Arg::new("search")
.short('s')
.long("search")
.conflicts_with("info")
.takes_value(true)
.multiple_values(true)
.help("search remote repositories for matching strings"),
)
.arg(
Arg::new("info")
.long("info")
.conflicts_with("search")
.short('i')
.help("view package information"),
)
.arg(
Arg::new("package")
.help("packages")
.required_unless_present("search")
.takes_value(true)
.multiple_values(true),
),
)
.get_matches();
match matches.subcommand() {
Some(("sync", sync_matches)) => {
if sync_matches.is_present("search") {
let packages: Vec<_> = sync_matches.values_of("search").unwrap().collect();
let values = packages.join(", ");
println!("Searching for {}...", values);
return;
}
let packages: Vec<_> = sync_matches.values_of("package").unwrap().collect();
let values = packages.join(", ");
if sync_matches.is_present("info") {
println!("Retrieving info for {}...", values);
} else {
println!("Installing {}...", values);
}
}
Some(("query", query_matches)) => {
if let Some(packages) = query_matches.values_of("info") {
let comma_sep = packages.collect::<Vec<_>>().join(", ");
println!("Retrieving info for {}...", comma_sep);
} else if let Some(queries) = query_matches.values_of("search") {
let comma_sep = queries.collect::<Vec<_>>().join(", ");
println!("Searching Locally for {}...", comma_sep);
} else {
println!("Displaying all locally installed packages...");
}
}
_ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
}
}
Sets a hidden alias to this subcommand.
This allows the 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"));
Add an alias, which functions as “hidden” short flag subcommand
This will 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"));
Add an alias, which functions as a “hidden” long flag subcommand.
This will 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"));
Sets multiple hidden aliases to this subcommand.
This allows the 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")
.help("the file to add")
.index(1)
.required(false))
.get_matches_from(vec!["myprog", "do-tests"]);
assert_eq!(m.subcommand_name(), Some("test"));
Add aliases, which function as “hidden” short flag subcommands.
These will 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")
.help("the file to add")
.index(1)
.required(false))
.get_matches_from(vec!["myprog", "-a"]);
assert_eq!(m.subcommand_name(), Some("test"));
Add aliases, which function as “hidden” long flag subcommands.
These will 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")
.help("the file to add")
.index(1)
.required(false))
.get_matches_from(vec!["myprog", "--testing"]);
assert_eq!(m.subcommand_name(), Some("test"));
Sets a visible alias to this subcommand.
This allows the 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"));
Add an alias, which functions as “visible” short flag subcommand
This will 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.
See also App::short_flag_alias
.
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"));
Add an alias, which functions as a “visible” long flag subcommand.
This will 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.
See also App::long_flag_alias
.
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"));
Sets multiple visible aliases to this subcommand.
This allows the 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"));
Add aliases, which function as visible short flag subcommands.
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"));
Add aliases, which function as visible long flag subcommands.
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"));
Set the placement of this subcommand within the help.
Subcommands with a lower value will be displayed first in the help message. Subcommands with duplicate display orders will be displayed in alphabetical order.
This is helpful when one would like to emphasize frequently used subcommands, or prioritize those towards the top of the list.
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
Sets the value name used for subcommands when printing usage and help.
By default, this is “SUBCOMMAND”.
See also App::subcommand_help_heading
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_value_name
App::new("myprog")
.subcommand(App::new("sub1"))
.subcommand_value_name("THING")
.print_help()
will produce
myprog
USAGE:
myprog [THING]
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
Examples found in repository
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
fn main() {
let app = App::new(env!("CARGO_CRATE_NAME"))
.setting(AppSettings::ArgRequiredElseHelp)
.subcommand_value_name("APPLET")
.subcommand_help_heading("APPLETS")
.subcommand(App::new("hostname").about("show hostname part of FQDN"))
.subcommand(App::new("dnsdomainname").about("show domain name part of FQDN"));
let app = app.setting(AppSettings::Multicall);
match app.get_matches().subcommand_name() {
Some("hostname") => println!("www"),
Some("dnsdomainname") => println!("example.com"),
_ => unreachable!("parser should ensure only valid subcommand names are used"),
}
}
More examples
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
fn main() {
let app = App::new(env!("CARGO_CRATE_NAME"))
.setting(AppSettings::Multicall)
.subcommand(
App::new("busybox")
.setting(AppSettings::ArgRequiredElseHelp)
.subcommand_value_name("APPLET")
.subcommand_help_heading("APPLETS")
.arg(
Arg::new("install")
.long("install")
.help("Install hardlinks for all subcommands in path")
.exclusive(true)
.takes_value(true)
.default_missing_value("/usr/local/bin")
.use_delimiter(false),
)
.subcommands(applet_commands()),
)
.subcommands(applet_commands());
let matches = app.get_matches();
let mut subcommand = matches.subcommand();
if let Some(("busybox", cmd)) = subcommand {
if cmd.occurrences_of("install") > 0 {
unimplemented!("Make hardlinks to the executable here");
}
subcommand = cmd.subcommand();
}
match subcommand {
Some(("false", _)) => exit(1),
Some(("true", _)) => exit(0),
_ => unreachable!("parser should ensure only valid subcommand names are used"),
}
}
Sets the help heading used for subcommands when printing usage and help.
By default, this is “SUBCOMMANDS”.
See also App::subcommand_value_name
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_help_heading
App::new("myprog")
.subcommand(App::new("sub1"))
.subcommand_help_heading("THINGS")
.print_help()
will produce
myprog
USAGE:
myprog [SUBCOMMAND]
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
Examples found in repository
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
fn main() {
let app = App::new(env!("CARGO_CRATE_NAME"))
.setting(AppSettings::ArgRequiredElseHelp)
.subcommand_value_name("APPLET")
.subcommand_help_heading("APPLETS")
.subcommand(App::new("hostname").about("show hostname part of FQDN"))
.subcommand(App::new("dnsdomainname").about("show domain name part of FQDN"));
let app = app.setting(AppSettings::Multicall);
match app.get_matches().subcommand_name() {
Some("hostname") => println!("www"),
Some("dnsdomainname") => println!("example.com"),
_ => unreachable!("parser should ensure only valid subcommand names are used"),
}
}
More examples
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
fn main() {
let app = App::new(env!("CARGO_CRATE_NAME"))
.setting(AppSettings::Multicall)
.subcommand(
App::new("busybox")
.setting(AppSettings::ArgRequiredElseHelp)
.subcommand_value_name("APPLET")
.subcommand_help_heading("APPLETS")
.arg(
Arg::new("install")
.long("install")
.help("Install hardlinks for all subcommands in path")
.exclusive(true)
.takes_value(true)
.default_missing_value("/usr/local/bin")
.use_delimiter(false),
)
.subcommands(applet_commands()),
)
.subcommands(applet_commands());
let matches = app.get_matches();
let mut subcommand = matches.subcommand();
if let Some(("busybox", cmd)) = subcommand {
if cmd.occurrences_of("install") > 0 {
unimplemented!("Make hardlinks to the executable here");
}
subcommand = cmd.subcommand();
}
match subcommand {
Some(("false", _)) => exit(1),
Some(("true", _)) => exit(0),
_ => unreachable!("parser should ensure only valid subcommand names are used"),
}
}
Reflection
Get the name of the binary.
Set binary name. Uses &mut self
instead of self
.
Get the short flag of the subcommand.
Get the long flag of the subcommand.
Get the help message specified via App::about
.
Get the help message specified via App::long_about
.
Get the custom section heading specified via App::help_heading
.
Iterate through the visible aliases for this subcommand.
Iterate through the visible short aliases for this subcommand.
Iterate through the visible long aliases for this subcommand.
Iterate through the set of all the aliases for this subcommand, both visible and hidden.
Iterate through the set of all the short aliases for this subcommand, both visible and hidden.
Iterate through the set of all the long aliases for this subcommand, both visible and hidden.
Check if the given AppSettings
variant is currently set on the App
.
This checks both local and global settings.
Should we color the output?
Iterate through the set of subcommands, getting a reference to each.
Iterate through the set of subcommands, getting a mutable reference to each.
Returns true
if this App
has subcommands.
Find subcommand such that its name or one of aliases equals name
.
This does not recurse through subcommands of subcommands.
Iterate through the set of arguments.
Iterate through the positionals arguments.
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
.
Deprecated
👎 Deprecated since 3.0.0: Deprecated in Issue #3087, maybe clap::Parser would fit your use case?
Deprecated in Issue #3087, maybe clap::Parser would fit your use case?
Deprecated in Issue #3087, maybe clap::Parser
would fit your use case?
👎 Deprecated since 3.0.0: Replaced with App::override_usage
Replaced with App::override_usage
Deprecated, replaced with App::override_usage
👎 Deprecated since 3.0.0: Replaced with App::override_help
Replaced with App::override_help
Deprecated, replaced with App::override_help
👎 Deprecated since 3.0.0: Replaced with App::mut_arg
Replaced with App::mut_arg
Deprecated, replaced with App::mut_arg
👎 Deprecated since 3.0.0: Replaced with App::mut_arg
Replaced with App::mut_arg
Deprecated, replaced with App::mut_arg
👎 Deprecated since 3.0.0: Replaced with App::mut_arg
Replaced with App::mut_arg
Deprecated, replaced with App::mut_arg
👎 Deprecated since 3.0.0: Replaced with App::mut_arg
Replaced with App::mut_arg
Deprecated, replaced with App::mut_arg
👎 Deprecated since 3.0.0: Replaced with App::help_template
Replaced with App::help_template
Deprecated, replaced with App::help_template
👎 Deprecated since 3.0.0: Replaced with App::setting(a | b)
Replaced with App::setting(a | b)
Deprecated, replaced with [App::setting(a| b)
]
👎 Deprecated since 3.0.0: Replaced with App::unset_setting(a | b)
Replaced with App::unset_setting(a | b)
Deprecated, replaced with [App::unset_setting(a| b)
]
👎 Deprecated since 3.0.0: Replaced with App::global_setting(a | b)
Replaced with App::global_setting(a | b)
Deprecated, replaced with [App::global_setting(a| b)
]
👎 Deprecated since 3.0.0: Replaced with App::term_width
Replaced with App::term_width
Deprecated, replaced with App::term_width
👎 Deprecated since 3.0.0: Deprecated in Issue #3086, see `clap::arg!
Deprecated in Issue #3086, see `clap::arg!
Deprecated in Issue #3086, see arg!
.
👎 Deprecated since 3.0.0: Deprecated in Issue #3086, see `clap::arg!
Deprecated in Issue #3086, see `clap::arg!
Deprecated in Issue #3086, see arg!
.
👎 Deprecated since 3.0.0: Replaced with App::render_version
Replaced with App::render_version
Deprecated, replaced with App::render_version
👎 Deprecated since 3.0.0: Replaced with App::render_long_version
Replaced with App::render_long_version
Deprecated, replaced with App::render_long_version
👎 Deprecated since 3.0.0: Replaced with App::try_get_matches
Replaced with App::try_get_matches
Deprecated, replaced with App::try_get_matches
pub 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, replaced with App::try_get_matches_from
pub 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, replaced with App::try_get_matches_from_mut
Trait Implementations
Auto Trait Implementations
impl<'help> RefUnwindSafe for App<'help>
impl<'help> UnwindSafe for App<'help>
Blanket Implementations
Mutably borrows from an owned value. Read more
Compare self to key
and return true
if they are equal.