on 2158366 help sign in
53 lines 1.8 kB history raw
1use anyhow::{Error, Result};
2use std::path::PathBuf;
4#[derive(Default)]
5pub struct Args {
6 pub display_help: bool,
7 pub display_version: bool,
8 pub verbosity: u64,
9 pub files: Vec<PathBuf>,
12impl Args {
13 pub fn parse_args() -> Result<Args> {
14 let mut args = Args::default();
15 let argv: Vec<String> = std::env::args().collect();
16 let mut iter = argv.iter();
18 iter.next(); // skip the program, we don't care about that
20 for arg in &mut iter {
21 match arg.as_str() {
22 "--" => break, // stop parsing at this point treat the remaining as files
23 "--version" => args.display_version = true,
24 "--help" => args.display_help = true,
25 arg if arg.starts_with("--") => {
26 return Err(Error::msg(format!(
27 "unexpected double dash argument: {}",
28 arg
29 )))
30 }
31 arg if arg.starts_with('-') => {
32 let arg = arg.get(1..).unwrap().chars();
33 for chr in arg {
34 match chr {
35 'v' => args.verbosity += 1,
36 'V' => args.display_version = true,
37 'h' => args.display_help = true,
38 _ => return Err(Error::msg(format!("unexpected short arg {}", chr))),
39 }
40 }
41 }
42 arg => args.files.push(PathBuf::from(arg)),
43 }
44 }
46 // push the remaining args, if any to the files
47 for filename in iter {
48 args.files.push(PathBuf::from(filename));
49 }
51 Ok(args)
52 }