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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
//! Clappers -  Command Line Argument Parsing Particularly Easy, Relatively Straightforward!
//!
//! `Clappers` aims to be the most user-friendly command line argument parser this side of the
//! Milky Way. You configure a `Clappers` parser with the command line arguments you care about
//! via chaining, with the last link in the chain being a call to `parse()`. Command line argument
//! values are then retrieved via getters on the `Clappers` parser.
//!
//! ## Example 1 - A Minimal Directory Listing
//!
//! ```
//! use clappers::Clappers;
//!
//! fn main() {
//!     let clappers = Clappers::build()
//!         .set_flags(vec![
//!             "h|help",
//!             "l",
//!             "R|recursive",
//!         ])
//!         .parse();
//!
//!     if clappers.get_flag("help") {
//!         println!("
//!             usage: ls [arguments] [FILE1]...
//!
//!             Arguments:
//!                 -h|--help        Print this help
//!                 -l               Use a long listing format
//!                 -R|--recursive   List subdirectories recursively
//!         ");
//!     }
//!
//!     if clappers.get_flag("l") {
//!         // Show more details than usual
//!     }
//!
//!     if clappers.get_flag("R") {
//!         // Recurse into subdirectories
//!     }
//!
//!     if clappers.get_flag("recursive") {
//!         // This will also recurse
//!     }
//!
//!     let filenames: Vec<String> = clappers.get_leftovers();
//!
//!     // ...
//! }
//! ```
//!
//! ## Example 2 - A Minimal Compiler
//!
//! ```
//! use clappers::Clappers;
//!
//! fn main() {
//!     let clappers = Clappers::build()
//!         .set_flags(vec![
//!             "h|help",
//!             "v|verbose",
//!         ])
//!         .set_singles(vec![
//!             "o|output",
//!         ])
//!         .set_multiples(vec![
//!             "i|input",
//!             "I",
//!             "L",
//!         ])
//!         .parse();
//!
//!     if clappers.get_flag("help") {
//!         println!("
//!             usage: compile [arguments]
//!
//!             Arguments:
//!                 -h|--help                        Print this help
//!                 -v|--verbose                     Enable verbose mode
//!                 -I <dir1> ... <dirN>             Include directories
//!                 -L <dir1> ... <dirN>             Library directories
//!                 -i|--input <file1> ... <fileN>   Input filenames
//!                 -o|--output filename             Output filename
//!         ");
//!     }
//!
//!     let output_filename = clappers.get_single("output");
//!     let input_filenames: Vec<String> = clappers.get_multiple("input");
//!
//!     // ...
//! }
//! ```
//!
//! # Argument Types
//!
//! There are four types of arguments:
//!
//! 1. Flags
//! 2. Single value
//! 3. Multiple value
//! 4. Leftovers
//!
//! ## 1. Flag Arguments
//!
//! Flag arguments are `true` if they were supplied on the command line, and `false` otherwise e.g:
//!
//!```ignore
//! -h
//! --help
//! -v
//! --verbose
//!```
//!
//! *Note:* flag arguments do not take values
//!
//! ## 2. Single Value Arguments
//!
//! Single value arguments contain a single `String` value if they were supplied on the command
//! line, and empty `String` otherwise e.g:
//!
//!```ignore
//! -o filename.txt
//! --output filename.txt
//! -u Zelensky
//! --username Zelensky
//!```
//!
//! ## 3. Multiple Value Arguments
//!
//! Multiple value arguments contain at least a single `String` value if they were supplied on the
//! command line, and empty `String` otherwise e.g:
//!
//!```ignore
//! -i file1.txt
//! --input file1.txt
//! --host host1
//!```
//!
//! They can also contain multiple values, by repetition on the command line e.g:
//!
//!```ignore
//! -i file1.txt -i file2.txt ... -i fileN.txt
//! --host host1 --host host2 ... --host hostN
//!```
//!
//! The following format also works, reading from the first value until either the next argument is
//! reached, or until the end of the entire command line arguments e.g:
//!
//!```ignore
//! -i file1.txt file2.txt ... fileN.txt -n next_argument
//! --host host1 host2 hostN
//!```
//!
//! ## 4. Leftover Arguments
//!
//! Leftover argument values are values supplied on the command line that are not associated with
//! any argument. These includes:
//!
//! - any values when no other argument types have been supplied e.g:
//!
//!```ignore
//! ls file1 file2... fileN
//!```
//!
//! - any values after the double-dash argument e.g:
//!
//!```ignore
//! ls -l -R  -- file1 file2... fileN`
//!```
//!
//! - any value supplied to flags, because flags do not accept values
//!
//! - any remaining values supplied to singles value arguments, because these only take a one value
//!
//! # Caveats
//!
//! - Combining flags is currently unsupported i.e the following does not work:
//!
//!```ignore
//! tar -zcf filename.tar.gz *
//!```
//!
//! - Equals-Value is currently unsupported i.e the following does not work:
//!
//!```ignore
//! tar -zc --file=filename.tar.gz
//!```
//!
//! - Commands with their own separate `Clappers` parser is currently unsupported i.e the following
//! does not work:
//!
//!```ignore
//! apt-get -y install -f cargo
//! apt-get update -f
//!```
//!
//! - Command line argument values are always `String` types. This was by design, and no convenience
//! functions are planned. To convert a `String` to something else, use `String`'s build-in
//! `parse()` function instead:
//!
//!```
//! use clappers::Clappers;
//!
//! fn main() {
//!     let clappers = Clappers::build()
//!         .set_singles(vec!["number"])
//!         .parse();
//!
//!     let number: i32 = clappers.get_single("number").parse().unwrap_or(0);
//!
//!     println!("Double {number} is {}", number * 2);
//! }
//!```
//!

use std::collections::HashMap;
use std::collections::HashSet;
use std::env;

impl Clappers {
    /// Build a `Clappers` parser
    ///
    /// # Parameters
    ///
    /// None.
    ///
    /// # Return value
    ///
    /// An empty `Clappers` parser, which is ready to be configured by chaining:
    ///
    /// - `set_flags()`
    /// - `set_singles()`
    /// - `set_multiples()`
    ///
    /// Once configured, `parse()` is chained last to parse the actual command line arguments
    ///
    /// # Example
    ///
    /// ```
    /// use clappers::Clappers;
    ///
    /// fn main() {
    ///     let clappers = Clappers::build()
    ///         .set_flags(vec!["h|help", "v|verbose"])
    ///         .set_singles(vec!["o|output", "u|username"])
    ///         .set_multiples(vec!["i|input", "host"])
    ///         .parse();
    ///
    ///     // ...
    /// }
    /// ```
    ///
    pub fn build() -> Self {
        Self {
            config: Config {
                flags: ConfigType::new(),
                singles: ConfigType::new(),
                multiples: ConfigType::new(),
            },
            values: Values {
                flags: HashSet::new(),
                singles: HashMap::new(),
                multiples: HashMap::new(),
            },
        }
    }

    /// Add flag argument parsing to the `Clappers` config
    ///
    /// Flag arguments are `true` if they were supplied on the command line, and `false` otherwise
    /// e.g:
    ///
    ///```ignore
    /// -h
    /// --help
    /// -v
    /// --verbose
    ///```
    ///
    /// *Note:* flag arguments do not take values
    ///
    /// # Parameters
    ///
    /// `arg_specs` specifies which flag arguments on the command line to care about.
    ///
    /// Each `arg_spec` contains "|" separated flag argument alias names e.g:
    ///
    ///```ignore
    /// clappers.set_flags(vec!["h|help", "v|verbose"]);
    ///```
    ///
    /// # Return value
    ///
    /// The `Clappers` parser so that it can be chained
    ///
    /// # Example
    ///
    /// ```
    /// use clappers::Clappers;
    ///
    /// fn main() {
    ///     let clappers = Clappers::build()
    ///         .set_flags(vec!["h|help", "v|verbose"])
    ///         .set_singles(vec!["o|output", "u|username"])
    ///         .set_multiples(vec!["i|input", "host"])
    ///         .parse();
    ///
    ///     // ...
    /// }
    /// ```
    ///
    pub fn set_flags(mut self, arg_specs: Vec<&str>) -> Self {
        self.config.flags.add_to_config(arg_specs);
        self
    }

    /// Add single value argument parsing to the `Clappers` config
    ///
    /// Single value arguments contain a single `String` value if they were supplied on the command
    /// line, and empty `String` otherwise e.g:
    ///
    ///```ignore
    /// -o filename.txt
    /// --output filename.txt
    /// -u Zelensky
    /// --username Zelensky
    ///```
    ///
    /// # Parameters
    ///
    /// `arg_specs` specifies which single value arguments on the command line to care about.
    ///
    /// Each `arg_spec` contains "|" separated single value argument alias names e.g:
    ///
    ///```ignore
    /// clappers.set_singles(vec!["o|output", "u|username"]);
    ///```
    ///
    /// # Return value
    ///
    /// The `Clappers` parser so that it can be chained
    ///
    /// # Example
    ///
    /// ```
    /// use clappers::Clappers;
    ///
    /// fn main() {
    ///     let clappers = Clappers::build()
    ///         .set_flags(vec!["h|help", "v|verbose"])
    ///         .set_singles(vec!["o|output", "u|username"])
    ///         .set_multiples(vec!["i|input", "host"])
    ///         .parse();
    ///
    ///     // ...
    /// }
    /// ```
    ///
    pub fn set_singles(mut self, arg_specs: Vec<&str>) -> Self {
        self.config.singles.add_to_config(arg_specs);
        self
    }

    /// Add multiple value argument parsing to the `Clappers` config
    ///
    /// Multiple value arguments contain at least a singly populated `Vec<String>` value if they
    /// were supplied on the command line, and empty `Vec<String>` otherwise e.g:
    ///
    ///```ignore
    /// -i file1.txt
    /// --input file1.txt
    /// --host host1
    ///```
    ///
    /// They can also contain multiple values, by repetition on the command line e.g:
    ///
    ///```ignore
    /// -i file1.txt -i file2.txt ... -i fileN.txt
    /// --host host1 --host host2 ... --host hostN
    ///```
    ///
    /// The following format also works, reading from the first value until either the next
    /// argument is reached, or until the end of the entire command line arguments e.g:
    ///
    ///```ignore
    /// -i file1.txt file2.txt ... fileN.txt -n next_argument
    /// --host host1 host2 hostN
    ///```
    ///
    /// # Parameters
    ///
    /// `arg_specs` specifies which multiple value arguments on the command line to care about.
    ///
    /// Each `arg_spec` contains "|" separated multiple value argument alias names e.g:
    ///
    ///```ignore
    /// clappers.set_multiples(vec!["i|input", "host"]);
    ///```
    ///
    /// # Return value
    ///
    /// The `Clappers` parser so that it can be chained
    ///
    /// # Example
    ///
    /// ```
    /// use clappers::Clappers;
    ///
    /// fn main() {
    ///     let clappers = Clappers::build()
    ///         .set_flags(vec!["h|help", "v|verbose"])
    ///         .set_singles(vec!["o|output", "u|username"])
    ///         .set_multiples(vec!["i|input", "host"])
    ///         .parse();
    ///
    ///     // ...
    /// }
    /// ```
    ///
    pub fn set_multiples(mut self, arg_specs: Vec<&str>) -> Self {
        self.config.multiples.add_to_config(arg_specs);
        self
    }

    /// Parse the command line arguments with the current `Clappers` config
    ///
    /// # Parameters
    ///
    /// None
    ///
    /// # Return value
    ///
    /// The `Clappers` parser containing the parsed command line arguments values, accessed with:
    ///
    /// - `get_flags()`
    /// - `get_singles()`
    /// - `get_multiples()`
    /// - `get_leftovers()`
    ///
    /// # Example
    ///
    /// ```
    /// use clappers::Clappers;
    ///
    /// fn main() {
    ///     let clappers = Clappers::build()
    ///         .set_flags(vec!["h|help", "v|verbose"])
    ///         .set_singles(vec!["o|output", "u|username"])
    ///         .set_multiples(vec!["i|input", "host"])
    ///         .parse();
    ///
    ///     if clappers.get_flag("help") {
    ///         // Show help text
    ///     }
    ///
    ///     // ...
    /// }
    /// ```
    ///
    pub fn parse(mut self) -> Self {
        // setup "leftovers" before parsing
        self.config.multiples.name.insert("".to_string());
        self.config
            .multiples
            .aliases
            .insert("".to_string(), "".to_string());

        let mut args = env::args().peekable();

        // discard argv[0]
        args.next();

        while let Some(mut next) = args.next() {
            if next.starts_with('-') {
                next = next.split_off(1);

                if next.starts_with('-') {
                    next = next.split_off(1);
                }

                if let Some(name) = self.config.flags.aliases.get(&next) {
                    self.values.flags.insert(name.to_string());
                } else if let Some(name) = self.config.singles.aliases.get(&next) {
                    if let Some(v) = args.peek() {
                        if v.starts_with('-') {
                            continue;
                        } else {
                            self.values
                                .singles
                                .insert(name.to_string(), args.next().unwrap());
                        }
                    }
                } else if let Some(name) = self.config.multiples.aliases.get(&next) {
                    if self.values.multiples.get_mut(name).is_none() {
                        self.values.multiples.insert(name.clone(), vec![]);
                    }

                    while let Some(value) = args.peek() {
                        if value.starts_with('-') {
                            break;
                        } else {
                            self.values
                                .multiples
                                .get_mut(name)
                                .unwrap()
                                .push(args.next().unwrap());
                        }
                    }
                }
            } else {
                if self.values.multiples.get_mut("").is_none() {
                    self.values.multiples.insert("".to_string(), vec![]);
                }

                self.values.multiples.get_mut("").unwrap().push(next);
            }
        }

        self
    }

    /// Check if the flag was supplied on the command line for the specified argument
    ///
    /// # Parameters
    ///
    /// `argument` is any alias of the specified argument
    ///
    /// # Return value
    ///
    /// `true` if the flag was supplied on the command line, and `false` otherwise
    ///
    /// # Example
    ///
    /// ```
    /// use clappers::Clappers;
    ///
    /// fn main() {
    ///     let clappers = Clappers::build()
    ///         .set_flags(vec!["h|help"])
    ///         .parse();
    ///
    ///     if clappers.get_flag("help") {
    ///         // Show help text
    ///     }
    ///
    ///     if clappers.get_flag("h") {
    ///         // This will also show the help text
    ///     }
    ///
    ///     // ...
    /// }
    /// ```
    ///
    pub fn get_flag(&self, argument: &str) -> bool {
        self.config
            .flags
            .aliases
            .get(argument)
            .map_or(false, |f| self.values.flags.contains(f))
    }

    /// Get the single value supplied on the command line for the specified argument
    ///
    /// # Parameters
    ///
    /// `argument` is any alias of the specified argument
    ///
    /// # Return value
    ///
    /// The single `String` value if they were supplied on the command line, and empty `String`
    /// otherwise
    ///
    /// # Example
    ///
    /// ```
    /// use clappers::Clappers;
    ///
    /// fn main() {
    ///     let clappers = Clappers::build()
    ///         .set_singles(vec!["output"])
    ///         .parse();
    ///
    ///     println!("Output filename is {}", clappers.get_single("output"));
    ///
    ///     // ...
    /// }
    /// ```
    ///
    pub fn get_single(&self, argument: &str) -> String {
        self.config
            .singles
            .aliases
            .get(argument)
            .map_or("".to_string(), |s| {
                self.values
                    .singles
                    .get(s)
                    .unwrap_or(&"".to_string())
                    .to_string()
            })
    }

    /// Get multiple values supplied on the command line for the specified argument
    ///
    /// # Parameters
    ///
    /// `argument` is any alias of the specified argument
    ///
    /// # Return value
    ///
    /// Multiple `String` values if they were supplied on the command line, and empty `Vec<String>`
    /// otherwise
    ///
    /// # Example
    ///
    /// ```
    /// use clappers::Clappers;
    ///
    /// fn main() {
    ///     let clappers = Clappers::build()
    ///         .set_multiples(vec!["input"])
    ///         .parse();
    ///
    ///     println!("Input filenames are {:#?}", clappers.get_multiple("input"));
    ///
    ///     // ...
    /// }
    /// ```
    ///
    pub fn get_multiple(&self, argument: &str) -> Vec<String> {
        self.config
            .multiples
            .aliases
            .get(argument)
            .map_or(vec![], |m| {
                self.values.multiples.get(m).unwrap_or(&vec![]).to_vec()
            })
    }

    /// Get all values supplied on the command line that are not associated with any argument
    ///
    /// # Parameters
    ///
    /// None
    ///
    /// # Return value
    ///
    /// All `String` values supplied on the command line that are not associated with any argument,
    /// and empty `Vec<String>` otherwise
    ///
    /// # Example
    ///
    /// ```
    /// use clappers::Clappers;
    ///
    /// fn main() {
    ///     let clappers = Clappers::build()
    ///         .parse();
    ///
    ///     println!("`ls *` returned the following filenames: {:#?}", clappers.get_leftovers());
    ///
    ///     // ...
    /// }
    /// ```
    ///
    pub fn get_leftovers(&self) -> Vec<String> {
        self.get_multiple("")
    }
}

#[derive(Clone, Debug)]
pub struct Clappers {
    config: Config,
    values: Values,
}

#[derive(Clone, Debug)]
struct Config {
    flags: ConfigType,
    singles: ConfigType,
    multiples: ConfigType,
}

#[derive(Clone, Debug)]
struct Values {
    flags: HashSet<String>,
    singles: HashMap<String, String>,
    multiples: HashMap<String, Vec<String>>,
}

impl ConfigType {
    fn new() -> Self {
        Self {
            name: HashSet::new(),
            aliases: HashMap::new(),
        }
    }

    fn add_to_config(&mut self, arg_specs: Vec<&str>) {
        for arg_spec in arg_specs {
            let arguments: Vec<&str> = arg_spec.split('|').collect();

            if arguments.is_empty() {
                continue;
            }

            self.name.insert(arguments[0].to_string());

            for argument in &arguments {
                self.aliases
                    .insert(argument.to_string(), arguments[0].to_string());
            }
        }
    }
}

#[derive(Clone, Debug)]
struct ConfigType {
    name: HashSet<String>,
    aliases: HashMap<String, String>,
}