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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
use std::env;
#[derive(Debug)]
pub enum ArgType
{
Flag,
Value,
ValueList,
}
#[derive(Debug, PartialEq)]
pub enum ArgResult
{
Flag,
Value(String),
ValueList(Vec<String>),
}
#[derive(Debug)]
pub struct Argument
{
short: Option<char>,
long: Option<String>,
arg_type: ArgType,
pub arg_result: Option<ArgResult>,
}
impl Argument
{
pub fn new(short: Option<char>, long: Option<& str>, arg_type: ArgType) -> Result<Argument, String>
{
match & short
{
None =>
{
match & long
{
None =>
{
return Err(String::from("At least one name of argument must be specified (short or long or both)"))
}
_ => ()
}
}
_ => (),
};
let long_owned: Option<String> = match long
{
Some(text) => Some(String::from(text)),
None => None,
};
Ok(Argument{short, long: long_owned, arg_type, arg_result: None})
}
pub fn add_value(& mut self, input_iter: & mut std::slice::Iter<'_, String>) -> Result<(), String>
{
match self.arg_type
{
ArgType::Flag =>
{
match self.arg_result
{
Some(_) => return Err(String::from("Flag already set")),
_ => (),
}
self.arg_result = Some(ArgResult::Flag);
}
ArgType::Value =>
{
match self.arg_result
{
Some(_) => return Err(String::from("Value already assigned")),
_ => (),
}
match input_iter.next()
{
Some(word) => self.arg_result = Some(ArgResult::Value(String::from(word))),
None => return Err(String::from("Expected value")),
}
}
ArgType::ValueList =>
{
let mut new_result = false;
match self.arg_result
{
Some(_) => (),
None => new_result = true,
}
if new_result
{
self.arg_result = Some(ArgResult::ValueList(Vec::new()));
}
match input_iter.next()
{
Some(word) =>
{
match self.arg_result.as_mut().expect("as mut")
{
ArgResult::ValueList(ref mut values) => values.push(String::from(word)),
_ => return Err(String::from("WTF")),
}
}
None => return Err(String::from("Expected value")),
}
}
}
Ok(())
}
}
#[derive(Debug)]
pub struct ArgumentList
{
pub dangling_values: Vec<String>,
pub arguments: Vec<Argument>,
}
impl ArgumentList
{
pub fn new() -> ArgumentList
{
ArgumentList{dangling_values: Vec::new(), arguments: Vec::new()}
}
pub fn append_arg(& mut self, argument: Argument)
{
self.arguments.push(argument);
}
pub fn append_dangling_value(& mut self, value: & str)
{
self.dangling_values.push(String::from(value));
}
pub fn search_by_short_name(& mut self, name: char) -> Result<& mut Argument, String>
{
for x in & mut self.arguments
{
match x.short
{
Some(symbol) =>
{
if symbol == name
{
return Ok(x)
}
}
None => (),
};
}
Err(String::from("Argument not found"))
}
pub fn search_by_long_name(& mut self, name: & str) -> Result<& mut Argument, String>
{
for x in & mut self.arguments
{
match x.long
{
Some(ref long_name) =>
{
if long_name == name
{
return Ok(x)
}
}
None => (),
}
}
Err(String::from("Argument not found"))
}
pub fn parse_args(& mut self, input: Vec<String>) -> Result<(), String>
{
let mut input_iter = input.iter();
while let Some(word) = input_iter.next()
{
let word_length = word.chars().count();
let mut chars = word.chars();
if word_length == 2
{
if word.chars().nth(0).expect("first letter") == '-' && word.chars().nth(1).expect(& format!("{}", word_length)).is_alphabetic()
{
match self.search_by_short_name(word.chars().nth(1).unwrap())
{
Ok(ref mut argument) =>
{
argument.add_value(& mut input_iter);
}
Err(msg) =>
{
return Err(format!("Error while parsing arguments: {}", msg))
}
};
}
else
{
self.append_dangling_value(word);
}
}
else if word_length > 2
{
if word.chars().nth(0).unwrap() == '-' && word.chars().nth(1).unwrap() == '-' && word.chars().nth(2).unwrap().is_alphabetic()
{
match self.search_by_long_name(& word[2..word.len()])
{
Ok(ref mut argument) =>
{
argument.add_value(& mut input_iter);
}
Err(msg) =>
{
return Err(format!("Error while parsing arguments: {}", msg))
}
};
}
else
{
self.append_dangling_value(word);
}
}
else
{
self.append_dangling_value(word);
}
}
Ok(())
}
}
pub fn args_to_string_vector(args: env::Args) -> Vec<String>
{
let mut arguments = Vec::new();
for x in args
{
arguments.push(String::from(x));
}
arguments
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_works()
{
let args = vec![String::from("-d"), String::from("-p"), String::from("/file"), String::from("--an-list"), String::from("Marcin"), String::from("-l"), String::from("Mazgaj")];
let mut args_list = ArgumentList::new();
args_list.append_arg(Argument::new(Some('d'), None, ArgType::Flag).expect("append 1"));
args_list.append_arg(Argument::new(Some('p'), None, ArgType::Value).expect("append 2"));
args_list.append_arg(Argument::new(Some('l'), Some("an-list"), ArgType::ValueList).expect("append 3"));
args_list.parse_args(args).unwrap();
assert_eq!(args_list.arguments[0].arg_result, Some(ArgResult::Flag));
assert_eq!(args_list.arguments[1].arg_result, Some(ArgResult::Value(String::from("/file"))));
assert_eq!(args_list.arguments[2].arg_result, Some(ArgResult::ValueList(vec![String::from("Marcin"), String::from("Mazgaj")])));
}
}