#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Timeout(pub std::time::Duration);
impl std::str::FromStr for Timeout {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(
humantime::parse_duration(s).map_err(anyhow::Error::new)?,
))
}
}
#[derive(Debug, clap::Parser, PartialEq, Eq)]
#[clap(about, author)]
pub struct Args {
#[clap(short, long, action)]
pub version: bool,
#[clap(short, long, action)]
pub config: Option<String>,
#[clap(subcommand)]
pub command: Option<Commands>,
#[clap(short, long, action)]
pub no_daemon: bool,
#[clap(long, action)]
pub stdout: bool,
#[clap(short, long, action)]
pub timeout: Option<Timeout>,
}
#[derive(Debug, clap::Subcommand, PartialEq, Eq)]
pub enum Commands {
ConfigShow,
ConfigDiff,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_arg() {
assert!(<Args as clap::Parser>::try_parse_from([""]).is_ok());
assert_eq!(
Args {
version: false,
command: None,
config: Some("path".to_string()),
no_daemon: false,
stdout: false,
timeout: None
},
<Args as clap::Parser>::try_parse_from(["", "-c", "path"]).unwrap()
);
assert_eq!(
Args {
version: false,
command: Some(Commands::ConfigShow),
config: Some("path".to_string()),
no_daemon: false,
stdout: false,
timeout: None
},
<Args as clap::Parser>::try_parse_from(["", "-c", "path", "config-show"]).unwrap()
);
assert_eq!(
Args {
version: false,
command: Some(Commands::ConfigDiff),
config: Some("path".to_string()),
no_daemon: false,
stdout: false,
timeout: None
},
<Args as clap::Parser>::try_parse_from(["", "-c", "path", "config-diff"]).unwrap()
);
assert_eq!(
Args {
version: true,
command: None,
config: None,
no_daemon: false,
stdout: false,
timeout: None
},
<Args as clap::Parser>::try_parse_from(["", "--version"]).unwrap()
);
assert_eq!(
Args {
version: false,
command: None,
config: Some("path".to_string()),
no_daemon: true,
stdout: false,
timeout: None
},
<Args as clap::Parser>::try_parse_from(["", "-c", "path", "--no-daemon"]).unwrap()
);
assert_eq!(
Args {
version: false,
command: None,
config: Some("path".to_string()),
no_daemon: true,
stdout: true,
timeout: Some(Timeout(std::time::Duration::from_secs(1)))
},
<Args as clap::Parser>::try_parse_from([
"",
"-c",
"path",
"--no-daemon",
"--stdout",
"--timeout",
"1s"
])
.unwrap()
);
}
}