Reputation: 47
I'm writing a CLI tool using Clap. Usage should look like this:
$ my_tool command argument
The argument is necessary for the command to work. This is the code I have at the moment:
use::clap::{Parser, Subcommand};
#[derive(Parser)]
#[clap(author, version, about)]
struct Cli {
#[clap(subcommand)]
subcommand: Subcommands,
}
#[derive(Subcommand)]
enum Subcommands {
Command {
#[clap(value_parser)]
argument: Vec<String>,
}
// --snip--
}
fn main() {
let _cli = Cli::parse();
// --snip--
}
I get this when trying to use the tool:
~/my_tool$ cargo run -- command
Compiling my_tool v0.1.0 (/home/derch/my_tool)
Finished dev [unoptimized + debuginfo] target(s) in 0.78s
Running `target/debug/my_tool command`
~/my_tool$
I was expecting an error message because I didn't provide an argument after the command. How do I make the program to require the argument?
Upvotes: 2
Views: 1381
Reputation: 71350
Because this is a Vec
, by default it allows zero values. You can fix that by making it explicitly required
:
#[derive(Subcommand)]
enum Subcommands {
Command {
#[clap(value_parser, required = true)]
argument: Vec<String>,
}
// --snip--
}
Upvotes: 3