-
I want to do some custom parsing/validation on a Vec with Cli is that basic approach that works fine, but when i replace it with a custom type it doesn't allow parsing from a Vec I also tried implementing Thanks! use std::str::FromStr;
use clap::{Parser, ValueHint, value_parser};
#[derive(Debug, Parser)]
pub struct Cli {
#[clap(value_hint = ValueHint::CommandWithArguments, num_args = 1.., trailing_var_arg = true, required = true)]
command: Vec<String>,
}
#[derive(Debug, Parser)]
pub struct Cli2 {
#[clap(value_hint = ValueHint::CommandWithArguments, num_args = 1.., trailing_var_arg = true, required = true, value_parser = value_parser!(ValidCommand))]
command: ValidCommand,
}
#[derive(Debug, Clone)]
struct ValidCommand(Vec<String>);
// doesn't do anything
impl TryFrom<Vec<String>> for ValidCommand {
type Error = String;
fn try_from(value: Vec<String>) -> Result<Self, Self::Error> {
for v in &value {
if !v.is_ascii() {
return Err(String::new());
}
}
Ok(Self(value))
}
}
fn main() {
println!("Hello, world!");
let args = ["bin", "arg1", "arg2", "arg3"];
let cmd = Cli::try_parse_from(args).expect("valid command");
assert_eq!(cmd.command, args[1..]);
let args = ["bin", "arg1", "arg2", "arg3"];
let cmd = Cli2::try_parse_from(args).expect("valid command");
assert_eq!(cmd.command.0, args[1..]);
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
Beta Was this translation helpful? Give feedback.
value_parser
takes a single value and outputs whatever value you want, including a series of values. It does not operate on a series of values. That would need to be handled by custom validation logic. Right now that must be done after parsing in application code. We are considering what ways to allow users to extend validation.