dur/
clap_arg.rs

1use std::ffi::OsStr;
2
3use clap::{
4	builder::{
5		StringValueParser,
6		TypedValueParser,
7		ValueParserFactory,
8	},
9	error::{
10		ContextKind,
11		ContextValue,
12		ErrorKind,
13	},
14	Arg,
15	Command,
16};
17
18use crate::Duration;
19
20#[derive(Clone, Debug)]
21pub struct DurationParser;
22
23impl ValueParserFactory for Duration {
24	type Parser = DurationParser;
25
26	fn value_parser() -> Self::Parser {
27		DurationParser
28	}
29}
30
31impl TypedValueParser for DurationParser {
32	type Value = Duration;
33
34	fn parse_ref(
35		&self,
36		cmd: &Command,
37		arg: Option<&Arg>,
38		value: &OsStr,
39	) -> Result<Self::Value, clap::Error> {
40		let s = StringValueParser::new().parse_ref(cmd, arg, value)?;
41		crate::parse(&s).map_err(move |e| {
42			let mut err = clap::Error::new(ErrorKind::ValueValidation).with_cmd(cmd);
43			if let Some(arg) = arg {
44				err.insert(
45					ContextKind::InvalidArg,
46					ContextValue::String(arg.to_string()),
47				);
48			}
49			err.insert(ContextKind::InvalidValue, ContextValue::String(s));
50			err.insert(ContextKind::Custom, ContextValue::String(e.to_string()));
51			err
52		})
53	}
54}