clapi 0.1.2

A framework for create command-line applications
Documentation
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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
use crate::args::ArgumentList;
use crate::command::Command;
use crate::option::OptionList;
use crate::Argument;
use std::fmt::Display;
use std::slice::Iter;
use std::str::FromStr;

/// Represents the result of a parse operation
/// and provides a set of methods to query over the values.
#[derive(Debug, Clone)]
pub struct ParseResult {
    command: Command,
    options: OptionList,
    args: ArgumentList,
}

impl ParseResult {
    /// Constructs a new `ParseResult`.
    pub fn new(command: Command, options: OptionList, args: ArgumentList) -> Self {
        ParseResult {
            command,
            options,
            args,
        }
    }

    // Returns the executing command.
    #[doc(hidden)]
    pub fn executing_command(&self) -> &Command {
        &self.command
    }

    /// Returns the name of the executing command.
    pub fn command_name(&self) -> &str {
        self.command.get_name()
    }

    /// Returns the version of the executing command or `None`.
    pub fn command_version(&self) -> Option<&str> {
        self.command.get_version()
    }

    /// Returns the help message of the executing command or `None`.
    pub fn command_help(&self) -> Option<&str> {
        self.command.get_help()
    }

    /// Returns the usage message of the executing command or `None`.
    pub fn command_usage(&self) -> Option<&str> {
        self.command.get_usage()
    }

    /// Returns the `Options` passed to the executing command.
    pub fn options(&self) -> &OptionList {
        &self.options
    }

    /// Returns the `Argument` passed to the executing command or `None` is there is more than 1 argument.
    pub fn arg(&self) -> Option<&Argument> {
        if self.args.len() == 1 {
            Some(&self.args[0])
        } else {
            None
        }
    }

    /// Returns the `Argument`s passed to the executing command.
    pub fn args(&self) -> &ArgumentList {
        &self.args
    }

    /// Gets the value of the argument with the given name.
    pub fn value_of(&self, arg_name: &str) -> Option<&str> {
        self.args
            .get(arg_name)
            .map(|arg| arg.get_values())
            .filter(|values| values.len() == 1)
            .map(|values| values[0].as_str())
    }

    /// Gets an iterator over the values of the argument with the given name.
    pub fn values_of(&self, arg_name: &str) -> Option<Values<'_>> {
        if let Some(arg) = self.args.get(arg_name) {
            Some(Values {
                values: arg.get_values(),
            })
        } else {
            None
        }
    }

    /// Gets the value of the argument of the given option.
    pub fn value_of_option(&self, option_name: &str) -> Option<&str> {
        self.options
            .get(option_name)
            .map(|opt| opt.get_arg())
            .flatten()
            .map(|arg| arg.get_values())
            .filter(|values| values.len() == 1)
            .map(|values| values[0].as_str())
    }

    /// Gets an iterator over the values of the arguments of the given option.
    pub fn values_of_option(&self, option_name: &str) -> Option<Values<'_>> {
        if let Some(option) = self.options.get(option_name) {
            let arg = option.get_arg()?;
            Some(Values {
                values: arg.get_values(),
            })
        } else {
            None
        }
    }

    /// Gets the value of the argument with the given name as a type `T`.
    pub fn value_of_as<T>(&self, arg_name: &str) -> Option<T>
    where
        T: FromStr + 'static,
        <T as FromStr>::Err: Display,
    {
        self.args().convert::<T>(arg_name).ok()
    }

    /// Gets the values of the argument as a `Vec<T>`.
    pub fn values_of_as<T>(&self, arg_name: &str) -> Option<Vec<T>>
    where
        T: FromStr + 'static,
        <T as FromStr>::Err: Display,
    {
        self.args().convert_all(arg_name).ok()
    }

    /// Gets the value of the argument of the given option as a type `T`.
    pub fn value_of_option_as<T>(&self, option_name: &str) -> Option<T>
    where
        T: FromStr + 'static,
        <T as FromStr>::Err: Display,
    {
        self.options().convert::<T>(option_name).ok()
    }

    /// Gets the values of the given option as a type `T`.
    pub fn values_of_option_as<T>(&self, option_name: &str) -> Option<Vec<T>>
    where
        T: FromStr + 'static,
        <T as FromStr>::Err: Display,
    {
        self.options().convert_all(option_name).ok()
    }
}

/// An iterator over the values of an argument or option.
#[derive(Debug, Clone)]
pub struct Values<'a> {
    values: &'a [String],
}

impl<'a> Values<'a> {
    /// Returns an iterator over the argument valeus.
    pub fn iter(&self) -> Iter<'_, String> {
        self.values.iter()
    }

    /// Returns the number of values.
    #[inline]
    pub fn len(&self) -> usize {
        self.values.len()
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// Returns `true` if contains the value.
    #[inline]
    pub fn contains<S: AsRef<str>>(&self, value: S) -> bool {
        self.values.iter().any(|s| s == value.as_ref())
    }

    /// Returns an slice to the inner values.
    #[inline]
    pub fn inner(&self) -> &'a [String] {
        self.values
    }
}

impl<'a> IntoIterator for Values<'a> {
    type Item = &'a String;
    type IntoIter = Iter<'a, String>;

    fn into_iter(self) -> Self::IntoIter {
        self.values.into_iter()
    }
}

impl<'a> IntoIterator for &'a Values<'a> {
    type Item = &'a String;
    type IntoIter = Iter<'a, String>;

    fn into_iter(self) -> Self::IntoIter {
        self.values.into_iter()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::validator::validate_type;
    use crate::{split_into_args, CommandOption, Context, ErrorKind, Parser};

    fn parse_with(value: &str, command: Command) -> crate::Result<ParseResult> {
        let context = Context::new(command);
        Parser::new(&context).parse(split_into_args(value))
    }

    #[test]
    fn parse_result_command_test() {
        let command = Command::new("MyApp")
            .arg(Argument::one_or_more("values"))
            .option(
                CommandOption::new("repeat").alias("r").arg(
                    Argument::with_name("times")
                        .validator(validate_type::<u64>())
                        .default(1),
                ),
            )
            .option(
                CommandOption::new("color")
                    .alias("c")
                    .arg(Argument::with_name("color").valid_values(&["red", "blue", "green"])),
            );

        let result = parse_with("--repeat 2 -c red hello world!", command.clone()).unwrap();
        assert!(result.options().contains("repeat"));
        assert!(result.options().contains("r"));
        assert!(result.options().contains("color"));
        assert!(result.options().contains("c"));
        assert_eq!(
            result
                .options()
                .get("repeat")
                .unwrap()
                .get_arg()
                .unwrap()
                .convert::<u64>()
                .ok(),
            Some(2)
        );
        assert!(result
            .options()
            .get("color")
            .unwrap()
            .get_arg()
            .unwrap()
            .contains("red"));
        assert_eq!(result.arg().unwrap().get_values(), &["hello", "world!"]);

        // Whitespace test
        assert!(parse_with("\" \"", command.clone())
            .unwrap()
            .arg()
            .unwrap()
            .contains(" "));

        // Ok
        assert!(parse_with("Hola Mundo!", command.clone()).is_ok());
        assert!(parse_with("--repeat 10 Hola Mundo!", command.clone()).is_ok());
        assert!(parse_with("--color green Hola Mundo!", command.clone()).is_ok());
        assert!(parse_with("-c blue -- Hola Mundo!", command.clone()).is_ok());
        assert!(parse_with("\" \"", command.clone()).is_ok());

        // Err
        assert!(parse_with("--repeat -2 Hola Mundo!", command.clone()).is_err());
        assert!(parse_with("", command.clone()).is_err());
        assert!(parse_with("--repeat 2 -c:red", command.clone()).is_err());
        assert!(parse_with("-r a Hello World", command.clone()).is_err());
        assert!(parse_with("-c yellow Hello World", command.clone()).is_err());
    }

    #[test]
    fn parse_result_subcommand_test() {
        let command = Command::new("MyApp")
            .subcommand(Command::new("version"))
            .subcommand(
                Command::new("set")
                    .arg(Argument::one_or_more("value"))
                    .option(CommandOption::new("repeat").arg(Argument::with_name("count"))),
            )
            .subcommand(Command::new("get"));

        let result = parse_with("set --repeat 1 1 2 3 4", command.clone()).unwrap();
        assert_eq!(result.executing_command().get_name(), "set");
        assert!(result
            .options()
            .get("repeat")
            .unwrap()
            .get_arg()
            .unwrap()
            .contains("1"));
        assert_eq!(
            result.arg().unwrap().get_values(),
            &[
                "1".to_owned(),
                "2".to_owned(),
                "3".to_owned(),
                "4".to_owned()
            ]
        );

        // Ok
        assert!(parse_with("version", command.clone()).is_ok());
        assert!(parse_with("set 1 2 3", command.clone()).is_ok());
        assert!(parse_with("get", command.clone()).is_ok());
        assert!(parse_with("", command.clone()).is_ok());

        // Err
        assert!(parse_with("Hello", command.clone()).is_err());
        assert!(parse_with("version hello", command.clone()).is_err());
        assert!(parse_with("version set 1 2 3", command.clone()).is_err());
        assert!(parse_with("version hello", command.clone()).is_err());
    }

    #[test]
    fn parse_result_required_option_test() {
        let command = Command::new("MyApp")
            .option(CommandOption::new("enable"))
            .option(
                CommandOption::new("times")
                    .alias("t")
                    .required(true)
                    .arg(Argument::with_name("times").validator(validate_type::<u64>())),
            )
            .arg(Argument::zero_or_more("values"));

        let result = parse_with("--times 1 -- one two three", command.clone()).unwrap();
        assert!(result.options().contains("times"));
        assert!(result
            .options()
            .get("times")
            .unwrap()
            .get_arg()
            .unwrap()
            .contains("1"));
        assert!(result.arg().unwrap().contains("one"));
        assert!(result.arg().unwrap().contains("two"));
        assert!(result.arg().unwrap().contains("three"));

        // Ok
        assert!(parse_with("--times 1", command.clone()).is_ok());
        assert!(parse_with("--times 1 1 2 3", command.clone()).is_ok());
        assert!(parse_with("--times 1 --enable", command.clone()).is_ok());

        // This is `Ok` because `--enable` takes not arguments
        // so the value `false` is passed as command argument
        assert!(parse_with("--times 1 --enable false", command.clone()).is_ok());

        // Err

        // Unlike above here is an error due `false` is being passed to `--enable` as argument
        // but it takes not arguments
        // Any tokens before `--` are considered arguments to the previous option
        // and the values following `--` are considered arguments to the command
        assert!(parse_with("--times 1 --enable false --", command.clone()).is_err());

        assert!(parse_with(" ", command.clone()).is_err());
        assert!(parse_with("--times", command.clone()).is_err());
    }

    #[test]
    fn parse_result_options_test() {
        let command = Command::new("MyApp")
            .option(CommandOption::new("hour").alias("h"))
            .option(CommandOption::new("minute").alias("m"))
            .option(CommandOption::new("second").alias("s"))
            .option(
                CommandOption::new("enable").arg(
                    Argument::with_name("value")
                        .validator(validate_type::<bool>())
                        .values_count(0..=1),
                ),
            );

        let result = parse_with("--hour -m -s --enable false", command.clone()).unwrap();
        assert_eq!(result.args().len(), 0);
        assert!(result.options().contains("hour"));
        assert!(result.options().contains("minute"));
        assert!(result.options().contains("second"));
        assert!(result
            .options()
            .get("enable")
            .unwrap()
            .get_arg()
            .unwrap()
            .contains("false"));
    }

    #[test]
    fn parse_result_multiple_args_test() {
        let command = Command::new("MyApp")
            .arg(Argument::with_name("min").validator(validate_type::<i64>()))
            .arg(Argument::with_name("max").validator(validate_type::<i64>()))
            .option(
                CommandOption::new("replace")
                    .alias("r")
                    .arg(Argument::with_name("from"))
                    .arg(Argument::with_name("to")),
            );

        let result = parse_with("--replace a A -- 2 10", command.clone()).unwrap();
        assert!(result
            .options()
            .get("replace")
            .unwrap()
            .get_args()
            .get("from")
            .unwrap()
            .contains("a"));
        assert!(result
            .options()
            .get("replace")
            .unwrap()
            .get_args()
            .get("to")
            .unwrap()
            .contains("A"));
        assert_eq!(
            result.args().get("min").unwrap().convert::<i64>().ok(),
            Some(2)
        );
        assert_eq!(
            result.args().get("max").unwrap().convert::<i64>().ok(),
            Some(10)
        );

        // Ok
        assert!(parse_with("2 10", command.clone()).is_ok());

        // Err
        assert!(parse_with("--replace hello HELLO", command.clone()).is_err());
        assert!(parse_with("25", command.clone()).is_err());
    }

    #[test]
    fn parse_result_eoa_test() {
        let command = Command::new("MyApp")
            .arg(Argument::one_or_more("args"))
            .option(CommandOption::new("A").alias("a"))
            .option(CommandOption::new("B").alias("b"))
            .option(CommandOption::new("C").alias("c"))
            .option(
                CommandOption::new("D")
                    .alias("d")
                    .arg(Argument::one_or_more("d")),
            );

        let result1 = parse_with("--A --B -- --C", command.clone()).unwrap();
        assert_eq!(result1.options().len(), 2);
        assert_eq!(result1.arg().unwrap().get_values().len(), 1);
        assert!(result1.options().contains("A"));
        assert!(result1.options().contains("B"));
        assert!(result1.arg().unwrap().contains("--C"));

        let result2 = parse_with("-- --A -b --C", command.clone()).unwrap();
        assert_eq!(result2.options().len(), 0);
        assert_eq!(result2.arg().unwrap().get_values().len(), 3);
        assert!(result2.arg().unwrap().contains("--A"));
        assert!(result2.arg().unwrap().contains("-b"));
        assert!(result2.arg().unwrap().contains("--C"));

        let result3 = parse_with("-- -- -a -b -c", command.clone()).unwrap();
        assert_eq!(result3.options().len(), 0);
        assert_eq!(result3.arg().unwrap().get_values().len(), 4);
        assert!(result3.arg().unwrap().contains("--"));
        assert!(result3.arg().unwrap().contains("-a"));
        assert!(result3.arg().unwrap().contains("-b"));
        assert!(result3.arg().unwrap().contains("-c"));

        let result4 = parse_with("--D 1 2 3 -- hello world", command.clone()).unwrap();
        assert_eq!(result4.options().len(), 1);
        assert!(result4.options().get_arg("D").unwrap().contains("1"));
        assert!(result4.options().get_arg("D").unwrap().contains("2"));
        assert!(result4.options().get_arg("D").unwrap().contains("3"));
        assert!(result4.arg().unwrap().contains("hello"));
        assert!(result4.arg().unwrap().contains("world"));

        let result5 = parse_with("1 2 3 -- hello world", command.clone());
        assert!(result5.is_err());
    }

    #[test]
    fn parse_result_variable_arg_count_test1() {
        let command = Command::new("MyApp")
            .arg(Argument::with_name("values").values_count(0..=3))
            .option(
                CommandOption::new("letters").arg(
                    Argument::with_name("letters")
                        .values_count(1..)
                        .validator(validate_type::<char>()),
                ),
            )
            .option(
                CommandOption::new("numbers").arg(
                    Argument::with_name("numbers")
                        .values_count(1..=2)
                        .validator(validate_type::<i64>()),
                ),
            );

        let result = parse_with(
            "--letters a b c d e --numbers 1 -- one two three",
            command.clone(),
        )
        .unwrap();

        assert_eq!(
            result
                .options()
                .get("letters")
                .unwrap()
                .get_arg()
                .unwrap()
                .get_values()
                .len(),
            5
        );
        assert!(result
            .options()
            .get("letters")
            .unwrap()
            .get_arg()
            .unwrap()
            .contains("a"));
        assert!(result
            .options()
            .get("letters")
            .unwrap()
            .get_arg()
            .unwrap()
            .contains("b"));
        assert!(result
            .options()
            .get("letters")
            .unwrap()
            .get_arg()
            .unwrap()
            .contains("c"));
        assert!(result
            .options()
            .get("letters")
            .unwrap()
            .get_arg()
            .unwrap()
            .contains("d"));
        assert!(result
            .options()
            .get("letters")
            .unwrap()
            .get_arg()
            .unwrap()
            .contains("e"));
        assert!(result
            .options()
            .get("numbers")
            .unwrap()
            .get_arg()
            .unwrap()
            .contains("1"));
        assert!(result.arg().unwrap().contains("one"));
        assert!(result.arg().unwrap().contains("two"));
        assert!(result.arg().unwrap().contains("three"));

        // --numbers only accepts 2 arguments but was 3
        assert_eq!(
            parse_with(
                "--letters a b c d e --numbers 1 2 3 -- one two three",
                command.clone()
            )
            .err()
            .unwrap()
            .kind(),
            &ErrorKind::InvalidArgumentCount
        );
    }

    #[test]
    fn parse_result_error_kind_test() {
        let command = Command::new("MyApp")
            .arg(Argument::with_name("values").values_count(0..5))
            .subcommand(Command::new("version"))
            .option(
                CommandOption::new("range")
                    .alias("r")
                    .arg(Argument::with_name("min").validator(validate_type::<i64>()))
                    .arg(Argument::with_name("max").validator(validate_type::<i64>())),
            )
            .option(CommandOption::new("A").alias("a"))
            .option(CommandOption::new("B").alias("b"))
            .subcommand(
                Command::new("read").option(
                    CommandOption::new("mode")
                        .required(true)
                        .arg(Argument::with_name("mode").valid_values(&["low", "mid", "high"])),
                ),
            )
            .subcommand(
                Command::new("data")
                    .subcommand(Command::new("set").arg(Argument::with_name("value")))
                    .subcommand(Command::new("get")),
            );

        let err_kind = move |value: &str| -> ErrorKind {
            parse_with(value, command.clone())
                .err()
                .unwrap_or_else(|| panic!("{}", value))
                .kind()
                .clone()
        };

        assert!(matches!(
            err_kind("version 1 2 3"),
            ErrorKind::InvalidArgumentCount
        ));
        assert!(matches!(
            err_kind("-- 1 2 3 4 5"),
            ErrorKind::InvalidArgumentCount
        ));
        assert!(matches!(
            err_kind("--range 0"),
            ErrorKind::InvalidArgumentCount
        ));
        assert!(matches!(
            err_kind("--range 1 2 3 -- "),
            ErrorKind::InvalidArgumentCount
        ));
        assert!(matches!(err_kind("-r=0=1"), ErrorKind::InvalidExpression));
        assert!(
            matches!(err_kind("--range 10 b"), ErrorKind::InvalidArgument(arg) if arg == "max")
        );
        assert!(matches!(err_kind("--C"), ErrorKind::UnexpectedOption(o) if o == "--C"));
        assert!(matches!(err_kind("data write"), ErrorKind::UnexpectedCommand(x) if x == "write"));
        assert!(matches!(err_kind("read"), ErrorKind::MissingOption(x) if x == "mode"));
        assert!(
            matches!(err_kind("read --mode lo"), ErrorKind::InvalidArgument(arg) if arg == "mode")
        );
        assert!(matches!(
            err_kind("read --mode low mid"),
            ErrorKind::InvalidArgumentCount
        ));
        assert!(matches!(err_kind("data clear"), ErrorKind::UnexpectedCommand(x) if x == "clear"));
        assert!(matches!(
            err_kind("data get 0"),
            ErrorKind::InvalidArgumentCount
        ));
        assert!(matches!(
            err_kind("data set \"Hello World\" Bye"),
            ErrorKind::InvalidArgumentCount
        ));
    }

    #[test]
    fn parse_result_option_bool_flag_test() {
        let command = Command::new("MyApp").option(
            CommandOption::new("enable").arg(
                Argument::with_name("enable")
                    .values_count(0..=1)
                    .validator(validate_type::<bool>()),
            ),
        );

        let res1 = parse_with("--enable true", command.clone()).unwrap();
        assert_eq!(
            res1.options()
                .get("enable")
                .unwrap()
                .get_arg()
                .unwrap()
                .get_values()[0],
            "true".to_owned()
        );

        let res2 = parse_with("--enable false", command.clone()).unwrap();
        assert_eq!(
            res2.options()
                .get("enable")
                .unwrap()
                .get_arg()
                .unwrap()
                .get_values()[0],
            "false".to_owned()
        );

        let res3 = parse_with("--enable", command.clone()).unwrap();
        assert!(res3.options().contains("enable"));

        let res4 = parse_with("", command.clone()).unwrap();
        assert!(!res4.options().contains("enable"));
    }

    #[test]
    fn parse_result_arg_default_values_test1() {
        let command = Command::new("MyApp")
            .arg(Argument::with_name("min").default(1))
            .arg(Argument::with_name("max"));

        let result1 = parse_with("10", command.clone()).unwrap();
        assert!(result1.args.get("min").unwrap().contains("1"));
        assert!(result1.args.get("max").unwrap().contains("10"));

        let result2 = parse_with("5 12", command.clone()).unwrap();
        assert!(result2.args.get("min").unwrap().contains("5"));
        assert!(result2.args.get("max").unwrap().contains("12"));
    }

    #[test]
    #[should_panic]
    fn parse_result_arg_default_values_test2() {
        let _command = Command::new("MyApp")
            .arg(Argument::with_name("min").default(1))
            .arg(Argument::with_name("max").default(10));
    }

    #[test]
    fn parse_result_option_default_values_test1() {
        let command = Command::new("MyApp").option(
            CommandOption::new("range")
                .arg(Argument::with_name("start").default(1))
                .arg(Argument::with_name("end")),
        );

        let result1 = parse_with("--range 22", command.clone()).unwrap();
        assert!(result1
            .options()
            .get_args("range")
            .unwrap()
            .get("start")
            .unwrap()
            .contains("1"));
        assert!(result1
            .options()
            .get_args("range")
            .unwrap()
            .get("end")
            .unwrap()
            .contains("22"));

        let result2 = parse_with("--range 10 25", command.clone()).unwrap();
        assert!(result2
            .options()
            .get_args("range")
            .unwrap()
            .get("start")
            .unwrap()
            .contains("10"));
        assert!(result2
            .options()
            .get_args("range")
            .unwrap()
            .get("end")
            .unwrap()
            .contains("25"));
    }

    #[test]
    #[should_panic]
    fn parse_result_option_default_values_test2() {
        let _command = Command::new("MyApp").option(
            CommandOption::new("range")
                .arg(Argument::with_name("start").default(1))
                .arg(Argument::with_name("end").default(20)),
        );
    }

    #[test]
    fn parse_result_allow_multiple_test() {
        let command = Command::new("MyApp").option(
            CommandOption::new("values")
                .multiple(true)
                .arg(Argument::one_or_more("values")),
        );

        let result1 = parse_with("--values 5 6", command.clone()).unwrap();
        assert!(result1.options().get_arg("values").unwrap().contains("5"));
        assert!(result1.options().get_arg("values").unwrap().contains("6"));

        let result2 = parse_with("--values 1 2 --values 3 4", command.clone()).unwrap();
        assert!(result2.options().get_arg("values").unwrap().contains("1"));
        assert!(result2.options().get_arg("values").unwrap().contains("2"));
        assert!(result2.options().get_arg("values").unwrap().contains("3"));
        assert!(result2.options().get_arg("values").unwrap().contains("4"));
    }

    #[test]
    fn parse_global_option_test() {
        let command = Command::new("MyApp")
            .option(
                CommandOption::new("color")
                    .global(true)
                    .arg(Argument::new().valid_values(vec!["red", "green", "blue"])),
            )
            .subcommand(Command::new("echo").arg(Argument::one_or_more("values")));

        let result = parse_with("echo --color red -- hello world", command.clone()).unwrap();
        assert_eq!(result.command_name(), "echo");
        assert!(result.options().get_arg("color").unwrap().contains("red"));
        assert!(result.args().get("values").unwrap().contains("hello"));
        assert!(result.args().get("values").unwrap().contains("world"));
    }

    #[test]
    fn parse_required_global_option_test() {
        let command = Command::new("MyApp")
            .option(CommandOption::new("flag").required(true).global(true))
            .subcommand(Command::new("echo").arg(Argument::one_or_more("values")));

        let result = parse_with("echo hello world", command.clone());
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().kind(),
            &ErrorKind::MissingOption("flag".to_owned())
        );

        assert!(parse_with("echo --flag hello world", command.clone()).is_ok())
    }

    #[test]
    fn value_of_test() {
        let command = Command::new("MyApp").arg(Argument::with_name("color"));

        let result = parse_with("red", command.clone()).unwrap();
        assert_eq!("red", result.value_of("color").unwrap());
    }

    #[test]
    fn values_of_test() {
        let command = Command::new("MyApp").arg(Argument::one_or_more("colors"));

        let result = parse_with("red blue green", command.clone()).unwrap();
        assert_eq!(
            vec!["red".to_owned(), "blue".to_owned(), "green".to_owned()],
            result
                .values_of("colors")
                .unwrap()
                .iter()
                .cloned()
                .collect::<Vec<String>>()
        );
    }

    #[test]
    fn value_of_option_test() {
        let command = Command::new("MyApp")
            .option(CommandOption::new("size").arg(Argument::with_name("size")));

        let result = parse_with("--size sm", command.clone()).unwrap();
        assert_eq!("sm", result.value_of_option("size").unwrap());
    }

    #[test]
    fn values_of_option_test() {
        let command = Command::new("MyApp")
            .option(CommandOption::new("sizes").arg(Argument::one_or_more("sizes")));

        let result = parse_with("--sizes sm md lg", command.clone()).unwrap();
        assert_eq!(
            vec!["sm".to_owned(), "md".to_owned(), "lg".to_owned()],
            result
                .values_of_option("sizes")
                .unwrap()
                .iter()
                .cloned()
                .collect::<Vec<String>>()
        );
    }

    #[test]
    fn value_of_as_test() {
        let command = Command::new("MyApp").arg(Argument::with_name("numbers"));
        let result = parse_with("65", command.clone()).unwrap();

        assert_eq!(65, result.value_of_as::<i32>("numbers").unwrap());
    }

    #[test]
    fn values_of_as_test() {
        let command = Command::new("MyApp").arg(Argument::one_or_more("numbers"));
        let result = parse_with("2 4 6", command.clone()).unwrap();

        assert_eq!(
            vec![2_i32, 4_i32, 6_i32],
            result
                .values_of_as::<i32>("numbers")
                .unwrap()
                .iter()
                .cloned()
                .collect::<Vec<i32>>()
        );
    }

    #[test]
    fn value_of_option_as_test() {
        let command = Command::new("MyApp")
            .option(CommandOption::new("size").arg(Argument::with_name("size")));
        let result = parse_with("--size 202", command.clone()).unwrap();

        assert_eq!(202_i64, result.value_of_option_as::<i64>("size").unwrap());
    }

    #[test]
    fn values_of_option_as_test() {
        let command = Command::new("MyApp")
            .option(CommandOption::new("sizes").arg(Argument::one_or_more("sizes")));
        let result = parse_with("--sizes 202 304", command.clone()).unwrap();

        assert_eq!(
            vec![202_i64, 304_i64],
            result
                .values_of_option_as::<i64>("sizes")
                .unwrap()
                .iter()
                .cloned()
                .collect::<Vec<i64>>()
        );
    }
}