Skip to content

Commit 5127748

Browse files
iximeowjclulow
andauthored
tools: accept "help" top-level command, show usage on errors (#174)
Co-authored-by: Joshua M. Clulow <[email protected]>
1 parent 5957f05 commit 5127748

File tree

1 file changed

+36
-7
lines changed

1 file changed

+36
-7
lines changed

tools/helios-build/src/main.rs

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ fn baseopts() -> getopts::Options {
6666
/*
6767
* We should always have a --help flag everywhere.
6868
*/
69-
opts.optflag("", "help", "usage information");
69+
opts.optflag("", "help", "display usage information");
7070

7171
opts
7272
}
@@ -2417,8 +2417,19 @@ fn main() -> Result<()> {
24172417
hide: true,
24182418
blank: false,
24192419
});
2420+
handlers.push(CommandInfo {
2421+
name: "help".into(),
2422+
desc: "display usage information".into(),
2423+
/*
2424+
* No behaviour is required here. The "help" command is a special case
2425+
* in the argument processing below.
2426+
*/
2427+
func: |_: &CommandArg| Ok(()),
2428+
hide: false,
2429+
blank: true,
2430+
});
24202431

2421-
let usage = || {
2432+
let usage = |failure: bool| {
24222433
let mut out = String::new();
24232434
out += "Usage: helios [OPTIONS] COMMAND [OPTIONS] [ARGS...]\n\n";
24242435
for ci in handlers.iter() {
@@ -2432,25 +2443,42 @@ fn main() -> Result<()> {
24322443

24332444
out += &format!(" {:<16} {}\n", ci.name, ci.desc);
24342445
}
2435-
println!("{}", opts.usage(&out));
2446+
let msg = opts.usage(&out);
2447+
if failure {
2448+
eprintln!("{msg}");
2449+
} else {
2450+
println!("{msg}");
2451+
}
2452+
};
2453+
2454+
let res = match opts.parse(std::env::args_os().skip(1)) {
2455+
Ok(res) => res,
2456+
Err(e) => {
2457+
usage(true);
2458+
bail!("{e}");
2459+
}
24362460
};
24372461

2438-
let res = opts.parse(std::env::args().skip(1))?;
24392462
if res.opt_present("help") {
2440-
usage();
2463+
usage(false);
24412464
return Ok(());
24422465
}
24432466

24442467
if res.free.is_empty() {
2445-
usage();
2468+
usage(true);
24462469
bail!("choose a command");
24472470
}
24482471

2472+
if res.free[0] == "help" {
2473+
usage(false);
2474+
return Ok(());
2475+
}
2476+
24492477
let args = res.free[1..].iter().map(|s| s.as_str()).collect::<Vec<_>>();
24502478

24512479
let log = init_log();
24522480

2453-
for ci in handlers {
2481+
for ci in handlers.iter() {
24542482
if ci.name != res.free[0] {
24552483
continue;
24562484
}
@@ -2460,6 +2488,7 @@ fn main() -> Result<()> {
24602488
return (ci.func)(&ca);
24612489
}
24622490

2491+
usage(true);
24632492
bail!("command \"{}\" not understood", res.free[0]);
24642493
}
24652494

0 commit comments

Comments
 (0)