summaryrefslogtreecommitdiff
path: root/helix-term/src/args.rs
blob: f0ef09eb012e7ceba5f5e4013ee4616f36a0c100 (plain) (blame)
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
use anyhow::{Error, Result};
use std::path::PathBuf;

#[derive(Default)]
pub struct Args {
    pub display_help: bool,
    pub display_version: bool,
    pub verbosity: u64,
    pub files: Vec<PathBuf>,
}

impl Args {
    pub fn parse_args() -> Result<Args> {
        let mut args = Args::default();
        let argv: Vec<String> = std::env::args().collect();
        let mut iter = argv.iter();

        iter.next(); // skip the program, we don't care about that

        for arg in &mut iter {
            match arg.as_str() {
                "--" => break, // stop parsing at this point treat the remaining as files
                "--version" => args.display_version = true,
                "--help" => args.display_help = true,
                arg if arg.starts_with("--") => {
                    return Err(Error::msg(format!(
                        "unexpected double dash argument: {}",
                        arg
                    )))
                }
                arg if arg.starts_with('-') => {
                    let arg = arg.get(1..).unwrap().chars();
                    for chr in arg {
                        match chr {
                            'v' => args.verbosity += 1,
                            'V' => args.display_version = true,
                            'h' => args.display_help = true,
                            _ => return Err(Error::msg(format!("unexpected short arg {}", chr))),
                        }
                    }
                }
                arg => args.files.push(PathBuf::from(arg)),
            }
        }

        // push the remaining args, if any to the files
        for filename in iter {
            args.files.push(PathBuf::from(filename));
        }

        Ok(args)
    }
}