Clap 3.0:
To do custom parsing, you should use #[clap(parse(try_from_str = ...))]
and define a custom function to parsing the argument. Here's an example:
use clap::Parser;
#[derive(Debug, Parser)]
pub struct Config {
#[clap(parse(try_from_str = parse_duration))]
interval: std::time::Duration,
}
fn parse_duration(arg: &str) -> Result<std::time::Duration, std::num::ParseIntError> {
let seconds = arg.parse()?;
Ok(std::time::Duration::from_secs(seconds))
}
Clap 4.0:
Almost same as above; the helper function can stay the same, but the attribute syntax has changed:
use clap::Parser;
#[derive(Debug, Parser)]
pub struct Config {
#[arg(value_parser = parse_duration)]
interval: std::time::Duration,
}
fn parse_duration(arg: &str) -> Result<std::time::Duration, std::num::ParseIntError> {
let seconds = arg.parse()?;
Ok(std::time::Duration::from_secs(seconds))
}
This parsing is pretty limited (I don't know what format you'd expect the duration to be in), but it shows how you'd do it.
If you want to be flexible with your duration arguments, consider using a crate like humantime; their Duration
can be used with clap without special attributes since it implements FromStr
.