forked from assert-rs/libtest2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhello-error.rs
More file actions
80 lines (75 loc) · 2.36 KB
/
hello-error.rs
File metadata and controls
80 lines (75 loc) · 2.36 KB
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
78
79
80
use lexarg_error::ErrorContext;
use lexarg_error::Result;
struct Args {
thing: String,
number: u32,
shout: bool,
}
fn parse_args() -> Result<Args> {
#![allow(clippy::enum_glob_use)]
use lexarg::Arg::*;
let mut thing = None;
let mut number = 1;
let mut shout = false;
let raw = std::env::args_os().collect::<Vec<_>>();
let mut parser = lexarg::Parser::new(&raw);
let bin_name = parser
.next_raw()
.expect("nothing parsed yet so no attached lingering")
.expect("always at least one");
while let Some(arg) = parser.next_arg() {
match arg {
Short("n") | Long("number") => {
let value = parser
.next_flag_value()
.ok_or_else(|| ErrorContext::msg("missing required value").within(arg))?;
number = value
.to_str()
.ok_or_else(|| {
ErrorContext::msg("invalid number")
.unexpected(Value(value))
.within(arg)
})?
.parse()
.map_err(|e| ErrorContext::msg(e).unexpected(Value(value)).within(arg))?;
}
Long("shout") => {
shout = true;
}
Value(val) if thing.is_none() => {
thing = Some(
val.to_str()
.ok_or_else(|| ErrorContext::msg("invalid string").unexpected(arg))?,
);
}
Short("h") | Long("help") => {
println!("Usage: hello [-n|--number=NUM] [--shout] THING");
std::process::exit(0);
}
_ => {
return Err(ErrorContext::msg("unexpected argument")
.unexpected(arg)
.within(Value(bin_name))
.into());
}
}
}
Ok(Args {
thing: thing
.ok_or_else(|| ErrorContext::msg("missing argument THING").within(Value(bin_name)))?
.to_owned(),
number,
shout,
})
}
fn main() -> Result<()> {
let args = parse_args()?;
let mut message = format!("Hello {}", args.thing);
if args.shout {
message = message.to_uppercase();
}
for _ in 0..args.number {
println!("{message}");
}
Ok(())
}