Skip to content

Commit 6b1a944

Browse files
committed
optimize the config parsing
1 parent 07e8354 commit 6b1a944

File tree

2 files changed

+21
-14
lines changed

2 files changed

+21
-14
lines changed

src/tools/jsondocck/src/config.rs

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
use std::cell::LazyCell;
2+
use std::env::Args;
3+
14
use getopts::Options;
25

36
#[derive(Debug)]
@@ -8,30 +11,32 @@ pub struct Config {
811
pub template: String,
912
}
1013

11-
/// Create [`Config`] from a vector of command-line arguments.
12-
pub fn parse_config(args: Vec<String>) -> Config {
14+
/// Create [`Config`] from an iterator of command-line arguments.
15+
pub fn parse_config(mut args: Args) -> Option<Config> {
1316
let mut opts = Options::new();
1417
opts.reqopt("", "doc-dir", "Path to the documentation output directory.", "PATH")
1518
.reqopt("", "template", "Path to the input template file.", "PATH")
1619
.optflag("h", "help", "Show this message.");
1720

18-
let (argv0, args_) = args.split_first().unwrap();
19-
if args.len() == 1 {
20-
let message = format!("Usage: {} <doc-dir> <template>", argv0);
21-
println!("{}", opts.usage(&message));
22-
std::process::exit(1);
21+
let argv0 = args.next().unwrap();
22+
let usage = &*LazyCell::new(|| opts.usage(&format!("Usage: {argv0} <doc-dir> <template>")));
23+
24+
if args.len() == 0 {
25+
print!("{usage}");
26+
27+
return None;
2328
}
2429

25-
let matches = opts.parse(args_).unwrap();
30+
let matches = opts.parse(args).unwrap();
2631

2732
if matches.opt_present("h") || matches.opt_present("help") {
28-
let message = format!("Usage: {} <doc-dir> <template>", argv0);
29-
println!("{}", opts.usage(&message));
30-
std::process::exit(1);
33+
print!("{usage}");
34+
35+
return None;
3136
}
3237

33-
Config {
38+
Some(Config {
3439
doc_dir: matches.opt_str("doc-dir").unwrap(),
3540
template: matches.opt_str("template").unwrap(),
36-
}
41+
})
3742
}

src/tools/jsondocck/src/main.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@ use directive::{Directive, DirectiveKind};
1515
use error::CkError;
1616

1717
fn main() -> ExitCode {
18-
let config = parse_config(env::args().collect());
18+
let Some(config) = parse_config(env::args()) else {
19+
return ExitCode::FAILURE;
20+
};
1921

2022
let mut failed = Vec::new();
2123
let mut cache = Cache::new(&config);

0 commit comments

Comments
 (0)