use anyhow::{bail, Error};
use tracing::warn;
pub fn load_command_line<T: argh::FromArgs>() -> Result<T, Error> {
load_from_strings(std::env::args().collect::<Vec<_>>())
}
fn load_from_strings<T: argh::FromArgs>(arg_strings: Vec<String>) -> Result<T, Error> {
let arg_strs: Vec<&str> = arg_strings.iter().map(|s| s.as_str()).collect();
match T::from_args(&[arg_strs[0]], &arg_strs[1..]) {
Ok(args) => Ok(args),
Err(output) => {
for line in output.output.split("\n") {
warn!("CmdLine: {}", line);
}
match output.status {
Ok(()) => bail!("Exited as requested by command line args"),
Err(()) => bail!("Exited due to bad command line args"),
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
use argh::FromArgs;
#[derive(FromArgs, PartialEq, Debug)]
struct OuterArgs {
#[argh(subcommand)]
sub: SubChoices,
}
#[derive(FromArgs, PartialEq, Debug)]
#[argh(subcommand)]
enum SubChoices {
Child(CreateChildArgs),
}
#[derive(FromArgs, PartialEq, Debug)]
#[argh(subcommand, name = "child")]
struct CreateChildArgs {
#[argh(option)]
option: u32,
}
#[fuchsia::test]
fn args_work() -> Result<(), Error> {
let arg_strings = vec![
"program_name".to_string(),
"child".to_string(),
"--option".to_string(),
"42".to_string(),
];
let args = load_from_strings::<OuterArgs>(arg_strings)?;
let SubChoices::Child(child_args) = args.sub;
assert_eq!(child_args.option, 42);
Ok(())
}
}