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
use std::env;

pub fn collect() -> Vec<String> {
    env::args().collect()
}

pub fn fix(unfixed: &str) -> Option<String> {
    if unfixed.len() < 1 {
        None
    } else if unfixed.len() == 1 {
        Some(format!("-{}", unfixed))
    } else {
        Some(format!("--{}", unfixed))
    }
}

pub fn get(unfixed: &str, argv: &Vec<String>) -> Result<String, ParseError> {
    let collected = argv;
    let fixed = match fix(unfixed) {
        Some(some) => some,
        None => return Err(ParseError::new(format!("unable to fix `{}`", unfixed))),
    };

    let mut res: Option<String> = None;

    for (i, arg) in collected.iter().enumerate() {
        if arg == &fixed {
            res = Some(match collected.get(i + 1) {
                Some(some) => some.clone(),
                None => return Err(ParseError::new(format!("no value for `{}`", unfixed))),
            });
        }
    }

    match res {
        Some(some) => Ok(some),
        None => Err(ParseError::new("no such argument")),
    }
}

pub fn contains(unfixed: &str, argv: &Vec<String>) -> bool {
    let collected = argv;
    let fixed = match fix(unfixed) {
        Some(some) => some,
        None => return false,
    };

    for arg in collected.iter() {
        if arg == &fixed {
            return true;
        }
    }

    false
}

pub type ParseError = mtk::Error;

#[cfg(test)]
mod tests;