Created
January 11, 2023 05:07
-
-
Save mysteriouspants/e1328a60ab368cf09baa3da168d95e09 to your computer and use it in GitHub Desktop.
Example use of a subcommand dispatcher for the Clap argument parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::error::Error; | |
use clap::{Arg, ArgMatches, builder::NonEmptyStringValueParser, Command}; | |
use mysteriouspants_clap_action_command::{ | |
ActionCommand, CommandMap, get_one, vec1::{Vec1, vec1} | |
}; | |
static NAME_ARG: &str = "name"; | |
struct HelloWorldCommand {} | |
impl ActionCommand for HelloWorldCommand { | |
fn name(&self) -> &'static str { | |
"hello-world" | |
} | |
fn command(&self, command: Command) -> Command { | |
command | |
.about("Say hello to the world") | |
.alias("h") | |
.arg( | |
Arg::new(NAME_ARG) | |
.short('n') | |
.value_name("NAME") | |
.required(false) | |
.value_parser(NonEmptyStringValueParser::new()) | |
) | |
} | |
fn action( | |
&self, matches: Vec1<&ArgMatches> | |
) -> Result<(), Box<dyn Error>> { | |
if let Some(name) = get_one::<String>(&matches, NAME_ARG) { | |
println!("Hello, {}!", name); | |
} else { | |
println!("Hello, world!"); | |
} | |
Ok(()) | |
} | |
} | |
let command_map = CommandMap::builder() | |
.push(HelloWorldCommand {}) | |
// adding a new subcommand is as easy as referencing it here | |
.build(); | |
let command = Command::new("my-program").subcommands(command_map.commands()); | |
let matches = command.get_matches_from([ | |
"my-program", "hello-world", "-n", "Steeve" | |
]); | |
command_map.dispatch(vec1![&matches]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment