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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
pub mod errors;
pub mod matches;
mod opts;
use std::env::Args;
pub use errors::ErrorKind;
pub use matches::Matches;
use opts::Opts;
pub fn parse(mut args: Args, options: &[&'static str]) -> Result<Matches, errors::ErrorKind> {
let mut matches: Matches = Matches::new();
let mut opts: Opts = opts(options);
args.next();
let mut next_arg = args.next();
while next_arg.is_some() {
let mut current_arg = next_arg.unwrap();
let arg: String;
if ¤t_arg[..1] == "-" {
if current_arg.len() == 2 {
arg = String::from(¤t_arg[1..]);
} else {
arg = String::from(¤t_arg[2..]);
}
if opts.contains_opt(&arg) {
let has_arg: bool = *opts.get_opt(&arg).unwrap();
if has_arg {
current_arg = match args.next() {
None => {
return Err(ErrorKind::MissingArgument);
},
Some(a) => a
};
matches.insert(&arg, ¤t_arg);
} else {
matches.insert(&arg, "");
}
} else {
return Err(ErrorKind::InvalidOption);
}
} else {
let arg_name: String = opts.get_arg().unwrap();
matches.insert(&arg_name, ¤t_arg);
}
next_arg = args.next();
}
Ok(matches)
}
fn opts(opts: &[&'static str]) -> Opts {
let mut options = Opts::new();
for opt in opts.iter() {
let is_arg: bool = match &opt[..1] {
":" => true,
_ => false
};
let has_arg: bool = match &opt[(opt.len() - 1)..] {
":" => true,
_ => false
};
if is_arg {
options.insert_arg(&opt[1..]);
} else {
let option: &str;
if has_arg {
option = &opt[..(opt.len() - 1)];
} else {
option = *opt;
}
for form in option.split("/") {
options.insert_opt(form, has_arg);
}
}
}
options.insert_opt("h", false);
options.insert_opt("help", false);
options
}