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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
pub mod argument;

use std::{borrow::BorrowMut, env, iter::Peekable};

use argument::{legacy_argument::Argument, parsable_argument::HandleableArgument};

///
/// Acumulates arguments into list which then can be fed to parse.
///
/// # Examples
/// ```
/// use trivial_argument_parser::{ArgumentList, argument::legacy_argument::*};
/// let mut args_list = ArgumentList::new();
/// args_list.append_arg(Argument::new(Some('d'), None, ArgType::Flag).unwrap());
/// args_list.append_arg(Argument::new(Some('p'), None, ArgType::Value).unwrap());
/// args_list.append_arg(Argument::new(Some('l'), Some("an-list"), ArgType::ValueList).unwrap());
/// ```
pub struct ArgumentList<'a> {
    pub dangling_values: Vec<String>,
    pub arguments: Vec<Argument>,
    pub parsable_arguments: Vec<&'a mut (dyn HandleableArgument<'a> + 'a)>,
}

impl<'a> ArgumentList<'a> {
    pub fn arguments(&self) -> &Vec<Argument> {
        &self.arguments
    }
    /**
    Create ArgumentList with empty vector of arguments.
    */
    pub fn new() -> ArgumentList<'a> {
        ArgumentList {
            dangling_values: Vec::new(),
            arguments: Vec::new(),
            parsable_arguments: Vec::new(),
        }
    }

    /**
    Append argument to the end of the list.
    */
    pub fn append_arg(&mut self, argument: Argument) {
        self.arguments.push(argument);
    }

    /**
    Append dangling values.
    */
    pub fn append_dangling_value(&mut self, value: &str) {
        self.dangling_values.push(String::from(value));
    }

    /**
    Search arguments by short name.
    */
    pub fn search_by_short_name(&self, name: char) -> Option<&Argument> {
        for x in &self.arguments {
            match x.short() {
                Some(symbol) => {
                    if symbol == &name {
                        return Some(x);
                    }
                }
                None => (),
            };
        }
        Option::None
    }

    /**
    Search arguments by short name.
    */
    pub fn search_by_short_name_mut(&mut self, name: char) -> Option<&mut Argument> {
        for x in &mut self.arguments {
            match x.short() {
                Some(symbol) => {
                    if symbol == &name {
                        return Some(x);
                    }
                }
                None => (),
            };
        }
        Option::None
    }

    fn handle_parsable_short_name(
        &mut self,
        name: char,
        input_iter: &mut Peekable<&mut std::slice::Iter<'_, String>>,
    ) -> Result<bool, String> {
        for x in &mut self.parsable_arguments {
            if x.is_by_short(name) {
                x.handle(input_iter)?;
                return Result::Ok(true);
            }
        }
        return Result::Ok(false);
    }

    fn handle_parsable_long_name(
        &mut self,
        name: &str,
        input_iter: &mut Peekable<&mut std::slice::Iter<'_, String>>,
    ) -> Result<bool, String> {
        for x in &mut self.parsable_arguments {
            if x.is_by_long(name) {
                x.handle(input_iter)?;
                return Result::Ok(true);
            }
        }
        return Result::Ok(false);
    }

    pub fn search_by_long_name(&self, name: &str) -> Option<&Argument> {
        for x in &self.arguments {
            match x.long() {
                Some(ref long_name) => {
                    if long_name == name {
                        return Option::Some(x);
                    }
                }
                None => (),
            }
        }
        Option::None
    }

    /**
    Search arguments by long name.
    */
    pub fn search_by_long_name_mut(&mut self, name: &str) -> Option<&mut Argument> {
        for x in &mut self.arguments {
            match x.long() {
                Some(ref long_name) => {
                    if long_name == name {
                        return Option::Some(x);
                    }
                }
                None => (),
            }
        }
        Option::None
    }

    /// Returns vector of all generated dangling values (values not attached to any argument)
    pub fn get_dangling_values(&self) -> &Vec<String> {
        &self.dangling_values
    }

    /// Function that does all the parsing. You need to feed user input as an argument. Handles both
    /// legacy type arguments and parsable value arguments. When used with mixed type arguments, parsable
    /// arguments cannot be accessed before all borrows to ArgumentList are released or it gets dropped.
    ///
    /// # Examples
    /// ```
    /// use trivial_argument_parser::{
    ///     ArgumentList, args_to_string_vector,
    ///     argument::{
    ///         legacy_argument::*,
    ///         parsable_argument::ParsableValueArgument,
    ///         ArgumentIdentification
    ///     }
    /// };
    ///
    /// let mut args_list = ArgumentList::new();
    /// args_list.append_arg(Argument::new(Some('d'), None, ArgType::Flag).unwrap());
    /// let mut argument_str = ParsableValueArgument::new_string(ArgumentIdentification::Long(String::from("hello")));
    /// args_list.register_parsable(&mut argument_str);
    /// args_list.parse_args(args_to_string_vector(std::env::args())).unwrap();
    /// // First read legacy arguments.
    /// args_list.search_by_short_name('n');
    /// // Then access parsable value arguments since last reference was used.
    /// argument_str.first_value();
    /// ```
    pub fn parse_args(&mut self, input: Vec<String>) -> Result<(), String> {
        let mut iter = input.iter();
        let mut input_iter = iter.borrow_mut().peekable();
        while let Some(word) = input_iter.next() {
            // Check if word is a short argument, long argument or dangling value
            let word_length = word.chars().count();
            if word_length == 2 {
                if word.chars().nth(0).expect("first letter") == '-'
                    && word
                        .chars()
                        .nth(1)
                        .expect(&format!("{}", word_length))
                        .is_alphabetic()
                {
                    // Add value to argument identified by short name
                    match self.search_by_short_name_mut(word.chars().nth(1).unwrap()) {
                        Some(argument) => {
                            argument.add_value(&mut input_iter)?;
                        }
                        None => {
                            if !self.handle_parsable_short_name(
                                word.chars().nth(1).unwrap(),
                                &mut input_iter,
                            )? {
                                return Err(format!(
                                    "Could not find argument identified by {}.",
                                    word
                                ));
                            }
                        }
                    };
                } else {
                    // Add as dangling value
                    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()
                {
                    // Add value to argument identified by long name
                    match self.search_by_long_name_mut(&word[2..word.len()]) {
                        Some(argument) => {
                            argument.add_value(&mut input_iter)?;
                        }
                        Option::None => {
                            if !self
                                .handle_parsable_long_name(&word[2..word.len()], &mut input_iter)?
                            {
                                return Err(format!(
                                    "Could not find argument identified by {}.",
                                    word
                                ));
                            }
                        }
                    };
                } else {
                    // Add as dangling value
                    self.append_dangling_value(word);
                }
            } else {
                // Add as dangling value
                self.append_dangling_value(word);
            }
        }

        // return arguments list with filled parsed values
        Ok(())
    }

    /**
     * Registers argument mutable borrow to be used while parsing.
     */
    pub fn register_parsable(&mut self, arg: &'a mut impl HandleableArgument<'a>) {
        self.parsable_arguments.push(arg);
    }
}

/**
Helper function to transform arguments given by user from Args to vector of String.
*/
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 crate::argument::{
        legacy_argument::{ArgResult, ArgType},
        parsable_argument::ParsableValueArgument,
    };

    use super::{argument::ArgumentIdentification, *};

    #[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")
            ]))
        );

        assert_eq!(
            args_list
                .search_by_short_name('d')
                .unwrap()
                .get_flag()
                .unwrap(),
            true
        );
        assert_eq!(
            args_list
                .search_by_long_name("an-list")
                .unwrap()
                .get_values()
                .unwrap(),
            &vec![String::from("Marcin"), String::from("Mazgaj")]
        );
    }

    #[test]
    fn get_dangling_values_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"),
            String::from("dangling"),
        ];

        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();

        let dangling = args_list.get_dangling_values();

        assert_eq!("dangling", dangling[0]);
    }

    #[test]
    fn values_with_spaces_work() {
        let args = vec![
            String::from("-n"),
            String::from("Marcin Mazgaj"),
            String::from("--hello"),
            String::from("Hello World!"),
            String::from("--hello"),
            String::from("Witaj Świecie!"),
        ];

        let mut args_list = ArgumentList::new();

        args_list.append_arg(Argument::new(Some('n'), None, ArgType::Value).unwrap());
        args_list.append_arg(Argument::new(None, Some("hello"), ArgType::ValueList).unwrap());

        args_list.parse_args(args).unwrap();

        assert_eq!(
            args_list
                .search_by_short_name('n')
                .unwrap()
                .get_value()
                .unwrap(),
            "Marcin Mazgaj"
        );
        assert_eq!(
            args_list
                .search_by_long_name("hello")
                .unwrap()
                .get_values()
                .unwrap(),
            &vec![String::from("Hello World!"), String::from("Witaj Świecie!")]
        );
    }

    #[test]
    fn parse_with_parsable_arguments_works() {
        let args = vec![
            String::from("-n"),
            String::from("5"),
            String::from("--hello"),
            String::from("Hello World!"),
            String::from("--hello"),
            String::from("Witaj Świecie!"),
        ];

        let mut args_list = ArgumentList::new();
        let mut argument_int =
            ParsableValueArgument::new_integer(ArgumentIdentification::Short('n'));
        let mut argument_str =
            ParsableValueArgument::new_string(ArgumentIdentification::Long(String::from("hello")));
        args_list.register_parsable(&mut argument_int);
        args_list.register_parsable(&mut argument_str);
        args_list
            .parse_args(args)
            .expect("Failed while parsing arguments");
        assert_eq!(argument_int.first_value().unwrap(), &5);
        assert_eq!(argument_str.first_value().unwrap(), "Hello World!");
        assert_eq!(argument_str.values().get(1).unwrap(), "Witaj Świecie!");
    }

    #[test]
    fn parse_drop_parser_works() {
        let args = vec![
            String::from("-n"),
            String::from("5"),
            String::from("--hello"),
            String::from("Hello World!"),
            String::from("--hello"),
            String::from("Witaj Świecie!"),
        ];
        let mut argument_int =
            ParsableValueArgument::new_integer(ArgumentIdentification::Short('n'));
        let mut argument_str =
            ParsableValueArgument::new_string(ArgumentIdentification::Long(String::from("hello")));
        {
            let mut args_list = ArgumentList::new();
            args_list.register_parsable(&mut argument_int);
            args_list.register_parsable(&mut argument_str);
            args_list
                .parse_args(args)
                .expect("Failed while parsing arguments");
        }
        assert_eq!(argument_int.first_value().unwrap(), &5);
        assert_eq!(argument_str.first_value().unwrap(), "Hello World!");
        assert_eq!(argument_str.values().get(1).unwrap(), "Witaj Świecie!");
    }

    #[test]
    fn parse_with_mixed_arguments_works() {
        let args = vec![
            String::from("-n"),
            String::from("5"),
            String::from("--hello"),
            String::from("Hello World!"),
            String::from("--hello"),
            String::from("Witaj Świecie!"),
        ];

        let mut args_list = ArgumentList::new();
        let mut argument_str =
            ParsableValueArgument::new_string(ArgumentIdentification::Long(String::from("hello")));
        args_list.register_parsable(&mut argument_str);
        args_list.append_arg(Argument::new(Some('n'), None, ArgType::Value).unwrap());
        args_list
            .parse_args(args)
            .expect("Failed while parsing arguments");
        assert_eq!(
            args_list
                .search_by_short_name('n')
                .unwrap()
                .get_value()
                .unwrap(),
            "5"
        );
        assert_eq!(argument_str.first_value().unwrap(), "Hello World!");
        assert_eq!(argument_str.values().get(1).unwrap(), "Witaj Świecie!");
    }
}