1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use {
anyhow::{bail, Error},
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(())
}
}