clap/examples/14_groups.rs

73 lines
2.4 KiB
Rust
Raw Normal View History

2021-11-19 20:33:11 +00:00
use clap::{arg, App, Arg, ArgGroup};
fn main() {
// Create application like normal
let matches = App::new("myapp")
2018-11-14 17:05:06 +00:00
// Add the version arguments
2021-11-19 20:33:11 +00:00
.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"))
2018-11-14 17:05:06 +00:00
// Create a group, make it required, and add the above arguments
.group(
ArgGroup::new("vers")
2018-11-14 17:05:06 +00:00
.required(true)
.args(&["set-ver", "major", "minor", "patch"]),
2018-11-14 17:05:06 +00:00
)
// Arguments can also be added to a group individually, these two arguments
// are part of the "input" group which is not required
2021-11-19 20:33:11 +00:00
.arg(arg!([INPUT_FILE] "some regular input").group("input"))
.arg(
arg!(--"spec-in" <SPEC_IN> "some special input argument")
.required(false)
.group("input"),
)
2018-11-14 17:05:06 +00:00
// Now let's assume we have a -c [config] argument which requires one of
// (but **not** both) the "input" arguments
.arg(
Arg::new("config")
2018-11-14 17:05:06 +00:00
.short('c')
.takes_value(true)
.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
2021-11-12 01:08:03 +00:00
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)
2018-01-25 04:05:05 +00:00
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,
2018-01-25 04:05:05 +00:00
_ => unreachable!(),
};
format!("{}.{}.{}", major, minor, patch)
};
println!("Version: {}", version);
// Check for usage of -c
if matches.is_present("config") {
2018-01-25 04:05:05 +00:00
let input = matches
.value_of("INPUT_FILE")
2021-11-12 01:08:03 +00:00
.unwrap_or_else(|| matches.value_of("spec-in").unwrap());
2018-01-25 04:05:05 +00:00
println!(
"Doing work using input {} and config {}",
input,
matches.value_of("config").unwrap()
);
}
}