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
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
extern crate libc;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::env;
use std::path::Path;
use std::vec::IntoIter;
use std::borrow::ToOwned;
use args::{ ArgMatches, Arg, SubCommand };
use args::{FlagArg, FlagBuilder};
use args::{OptArg, OptBuilder};
use args::{PosArg, PosBuilder};
/// Used to create a representation of the program and all possible command line arguments
/// for parsing at runtime.
///
///
/// Stores a list of all posisble arguments, as well as information displayed to the user such as
/// help and versioning information.
///
/// # Example
///
/// ```no_run
/// # use clap::{App, Arg};
/// let myprog = App::new("myprog")
/// .author("Me, me@mail.com")
/// .version("1.0.2")
/// .about("Explains in brief what the program does")
/// .arg(
/// Arg::new("in_file").index(1)
/// // Add other possible command line argument options here...
/// )
/// .get_matches();
///
/// // Your pogram logic starts here...
/// ```
pub struct App<'a, 'v, 'ab, 'u, 'ar> {
// The name displayed to the user when showing version and help/usage information
name: String,
// A string of author(s) if desired. Displayed when showing help/usage information
author: Option<&'a str>,
// The version displayed to the user
version: Option<&'v str>,
// A brief explaination of the program that gets displayed to the user when shown help/usage information
about: Option<&'ab str>,
flags: HashMap<&'ar str, FlagBuilder<'ar>>,
opts: HashMap<&'ar str, OptBuilder<'ar>>,
positionals_idx: BTreeMap<u8, PosBuilder<'ar>>,
subcommands: HashMap<String, App<'a, 'v, 'ab, 'u, 'ar>>,
needs_long_help: bool,
needs_long_version: bool,
needs_short_help: bool,
needs_short_version: bool,
needs_subcmd_help: bool,
required: HashSet<&'ar str>,
arg_list: HashSet<&'ar str>,
short_list: HashSet<char>,
long_list: HashSet<&'ar str>,
blacklist: HashSet<&'ar str>,
usage_str: Option<&'u str>,
bin_name: Option<String>
}
impl<'a, 'v, 'ab, 'u, 'ar> App<'a, 'v, 'ab, 'u, 'ar>{
/// Creates a new instance of an application requiring a name (such as the binary). Will be displayed
/// to the user when they print version or help and usage information.
///
/// # Example
///
/// ```no_run
/// # use clap::{App, Arg};
/// let prog = App::new("myprog")
/// # .get_matches();
/// ```
pub fn new<'n>(n: &'n str) -> App<'a, 'v, 'ab, 'u, 'ar> {
App {
name: n.to_owned(),
author: None,
about: None,
version: None,
flags: HashMap::new(),
opts: HashMap::new(),
positionals_idx: BTreeMap::new(),
subcommands: HashMap::new(),
needs_long_version: true,
needs_long_help: true,
needs_short_help: true,
needs_subcmd_help: true,
needs_short_version: true,
required: HashSet::new(),
arg_list: HashSet::new(),
short_list: HashSet::new(),
long_list: HashSet::new(),
usage_str: None,
blacklist: HashSet::new(),
bin_name: None,
}
}
/// Sets a string of author(s)
///
/// # Example
///
/// ```no_run
/// # use clap::{App, Arg};
/// # let app = App::new("myprog")
/// .author("Kevin <kbknapp@gmail.com>")
/// # .get_matches();
/// ```
pub fn author(mut self, a: &'a str) -> App<'a, 'v, 'ab, 'u, 'ar> {
self.author = Some(a);
self
}
/// Sets a string briefly describing what the program does
///
/// # Example
///
/// ```no_run
/// # use clap::{App, Arg};
/// # let app = App::new("myprog")
/// .about("Does really amazing things to great people")
/// # .get_matches();
/// ```
pub fn about(mut self, a: &'ab str) -> App<'a, 'v, 'ab, 'u, 'ar> {
self.about = Some(a);
self
}
/// Sets a string of the version number
///
/// # Example
///
/// ```no_run
/// # use clap::{App, Arg};
/// # let app = App::new("myprog")
/// .version("v0.1.24")
/// # .get_matches();
/// ```
pub fn version(mut self, v: &'v str) -> App<'a, 'v, 'ab, 'u, 'ar> {
self.version = Some(v);
self
}
/// Sets a custom usage string to over-ride the one auto-generated by `clap`
///
/// *NOTE:* You do not need to specify the "USAGE: " portion, as that will
/// still be applied by `clap`, you only need to specify the portion starting
/// with the binary name.
///
/// *NOTE:* This will not replace the entire help message, only the portion
/// showing the usage.
///
/// # Example
///
/// ```no_run
/// # use clap::{App, Arg};
/// # let app = App::new("myprog")
/// .usage("myapp [-clDas] <some_file>")
/// # .get_matches();
/// ```
pub fn usage(mut self, u: &'u str) -> App<'a, 'v, 'ab, 'u, 'ar> {
self.usage_str = Some(u);
self
}
/// Adds an argument to the list of valid possibilties
///
/// # Example
///
/// ```no_run
/// # use clap::{App, Arg};
/// # let app = App::new("myprog")
/// .arg(Arg::new("config")
/// .short("c")
/// // Additional argument configuration goes here...
/// )
/// # .get_matches();
/// ```
pub fn arg<'l, 'h, 'b, 'r>(mut self, a: Arg<'ar, 'ar, 'ar, 'ar, 'ar, 'ar>) -> App<'a, 'v, 'ab, 'u, 'ar> {
if self.arg_list.contains(a.name) {
panic!("Argument name must be unique, \"{}\" is already in use", a.name);
} else {
self.arg_list.insert(a.name);
}
if let Some(ref s) = a.short {
if self.short_list.contains(s) {
panic!("Argument short must be unique, -{} is already in use", s);
} else {
self.short_list.insert(*s);
}
}
if let Some(ref l) = a.long {
if self.long_list.contains(l) {
panic!("Argument long must be unique, --{} is already in use", l);
} else {
self.long_list.insert(l);
}
}
if a.required {
self.required.insert(a.name);
}
if let Some(i) = a.index {
if a.short.is_some() || a.long.is_some() {
panic!("Argument \"{}\" has conflicting requirements, both index() and short(), or long(), were supplied", a.name);
}
if a.multiple {
panic!("Argument \"{}\" has conflicting requirements, both index() and multiple(true) were supplied",a.name);
}
if a.takes_value {
panic!("Argument \"{}\" has conflicting requirements, both index() and takes_value(true) were supplied", a.name);
}
// Create the Positional Arguemnt Builder with each HashSet = None to only allocate those that require it
let mut pb = PosBuilder {
name: a.name,
index: i,
required: a.required,
blacklist: None,
requires: None,
possible_vals: None,
help: a.help,
};
// Check if there is anything in the blacklist (mutually excludes list) and add any values
if let Some(ref bl) = a.blacklist {
let mut bhs = HashSet::new();
// without derefing n = &&str
for n in bl { bhs.insert(*n); }
pb.blacklist = Some(bhs);
}
// Check if there is anything in the requires list and add any values
if let Some(ref r) = a.requires {
let mut rhs = HashSet::new();
// without derefing n = &&str
for n in r { rhs.insert(*n); }
pb.requires = Some(rhs);
}
// Check if there is anything in the possible values and add those as well
if let Some(ref p) = a.possible_vals {
let mut phs = HashSet::new();
// without derefing n = &&str
for n in p { phs.insert(*n); }
pb.possible_vals = Some(phs);
}
self.positionals_idx.insert(i, pb);
} else if a.takes_value {
if a.short.is_none() && a.long.is_none() {
panic!("Argument \"{}\" has take_value(true), yet neither a short() or long() were supplied", a.name);
}
// No need to check for .index() as that is handled above
let mut ob = OptBuilder {
name: a.name,
short: a.short,
long: a.long,
multiple: a.multiple,
blacklist: None,
help: a.help,
possible_vals: None,
requires: None,
required: a.required,
};
// Check if there is anything in the blacklist (mutually excludes list) and add any values
if let Some(ref bl) = a.blacklist {
let mut bhs = HashSet::new();
// without derefing n = &&str
for n in bl { bhs.insert(*n); }
ob.blacklist = Some(bhs);
}
// Check if there is anything in the requires list and add any values
if let Some(ref r) = a.requires {
let mut rhs = HashSet::new();
// without derefing n = &&str
for n in r { rhs.insert(*n); }
ob.requires = Some(rhs);
}
// Check if there is anything in the possible values and add those as well
if let Some(ref p) = a.possible_vals {
let mut phs = HashSet::new();
// without derefing n = &&str
for n in p { phs.insert(*n); }
ob.possible_vals = Some(phs);
}
self.opts.insert(a.name, ob);
} else {
if let Some(ref l) = a.long {
if *l == "help" {
self.needs_long_help = false;
} else if *l == "version" {
self.needs_long_version = false;
}
}
if let Some(ref s) = a.short {
if *s == 'h' {
self.needs_short_help = false;
} else if *s == 'v' {
self.needs_short_version = false;
}
}
if a.short.is_none() && a.long.is_none() {
panic!("Argument \"{}\" must have either a short() and/or long() supplied since no index() or takes_value() were found", a.name);
}
if a.required {
panic!("Argument \"{}\" cannot be required(true) because it has no index() or takes_value(true)", a.name)
}
// No need to check for index() or takes_value() as that is handled above
// Flags can't be required
// This should be unreachable...
// if self.required.contains(a.name) {
// self.required.remove(a.name);
// }
let mut fb = FlagBuilder {
name: a.name,
short: a.short,
long: a.long,
help: a.help,
blacklist: None,
multiple: a.multiple,
requires: None,
};
// Check if there is anything in the blacklist (mutually excludes list) and add any values
if let Some(ref bl) = a.blacklist {
let mut bhs = HashSet::new();
// without derefing n = &&str
for n in bl { bhs.insert(*n); }
fb.blacklist = Some(bhs);
}
// Check if there is anything in the requires list and add any values
if let Some(ref r) = a.requires {
let mut rhs = HashSet::new();
// without derefing n = &&str
for n in r { rhs.insert(*n); }
fb.requires = Some(rhs);
}
self.flags.insert(a.name, fb);
}
self
}
/// Adds multiple arguments to the list of valid possibilties
///
/// # Example
///
/// ```no_run
/// # use clap::{App, Arg};
/// # let app = App::new("myprog")
/// .args( vec![Arg::new("config").short("c"),
/// Arg::new("debug").short("d")])
/// # .get_matches();
/// ```
pub fn args(mut self, args: Vec<Arg<'ar, 'ar, 'ar, 'ar, 'ar, 'ar>>) -> App<'a, 'v, 'ab, 'u, 'ar> {
for arg in args.into_iter() {
self = self.arg(arg);
}
self
}
/// Adds a subcommand to the list of valid possibilties. Subcommands
/// are effectively sub apps, because they can contain their own arguments
/// and subcommands. They also function just like apps, in that they get their
/// own auto generated help and version switches.
///
/// # Example
///
/// ```no_run
/// # use clap::{App, Arg, SubCommand};
/// # let app = App::new("myprog")
/// .subcommand(SubCommand::new("config")
/// .about("Controls configuration features")
/// .arg(Arg::new("config_file")
/// .index(1)
/// .help("Configuration file to use")))
/// // Additional subcommand configuration goes here, such as arguments...
/// # .get_matches();
/// ```
pub fn subcommand(mut self, subcmd: App<'a, 'v, 'ab, 'u, 'ar>) -> App<'a, 'v, 'ab, 'u, 'ar> {
if subcmd.name == "help" { self.needs_subcmd_help = false; }
self.subcommands.insert(subcmd.name.clone(), subcmd);
self
}
/// Adds multiple subcommands to the list of valid possibilties
///
/// # Example
///
/// ```no_run
/// # use clap::{App, Arg, SubCommand};
/// # let app = App::new("myprog")
/// .subcommands( vec![
/// SubCommand::new("config").about("Controls configuration functionality")
/// .arg(Arg::new("config_file").index(1)),
/// SubCommand::new("debug").about("Controls debug functionality")])
/// # .get_matches();
/// ```
pub fn subcommands(mut self, subcmds: Vec<App<'a, 'v, 'ab, 'u, 'ar>>) -> App<'a, 'v, 'ab, 'u, 'ar> {
for subcmd in subcmds.into_iter() {
self = self.subcommand(subcmd);
}
self
}
fn print_usage(&self, more_info: bool) {
println!("USAGE:");
if let Some(u) = self.usage_str {
println!("\t{}",u);
} else {
let flags = !self.flags.is_empty();
let pos = !self.positionals_idx.is_empty();
let opts = !self.opts.is_empty();
let subcmds = !self.subcommands.is_empty();
let req_pos = self.positionals_idx.values().filter_map(|ref x| if x.required || self.required.contains(x.name) { Some(x.name) } else {None})
.fold(String::new(), |acc, ref name| acc + &format!("<{}> ", name)[..]);
let req_opts = self.opts.values().filter(|ref x| x.required || self.required.contains(x.name))
.fold(String::new(), |acc, ref o| acc + &format!("-{}{} ",if let Some(s) = o.short {
format!("{} ", s)
} else {
format!("-{}=",o.long.unwrap())
},o.name));
print!("\t{} {} {} {} {}", if let Some(ref name) = self.bin_name { name.replace("-", " ") } else { self.name.clone() },
if flags {"[FLAGS]"} else {""},
if opts {
if req_opts.len() != self.opts.len() && !req_opts.is_empty() {
format!("[OPTIONS] {}", &req_opts[..])
} else if req_opts.is_empty() {
"[OPTIONS]".to_owned()
} else {
req_opts
}
} else { "".to_owned() },
if pos {
if req_pos.len() != self.positionals_idx.len() && !req_pos.is_empty() {
format!("[POSITIONAL] {}", &req_pos[..])
} else if req_pos.is_empty() {
"[POSITIONAL]".to_owned()
} else {
req_pos
}
} else {"".to_owned()},
if subcmds {"[SUBCOMMANDS]"} else {""});
}
if more_info {
println!("\nFor more information try --help");
}
}
fn print_help(&self) {
self.print_version(false);
let flags = !self.flags.is_empty();
let pos = !self.positionals_idx.is_empty();
let opts = !self.opts.is_empty();
let subcmds = !self.subcommands.is_empty();
if let Some(author) = self.author {
println!("{}", author);
}
if let Some(about) = self.about {
println!("{}", about);
}
println!("");
self.print_usage(false);
if flags || opts || pos || subcmds {
println!("");
}
if flags {
println!("");
println!("FLAGS:");
for v in self.flags.values() {
println!("\t{}{}\t{}",
if let Some(s) = v.short{format!("-{}",s)}else{" ".to_owned()},
if let Some(l) = v.long {format!(",--{}",l)}else {" \t".to_owned()},
v.help.unwrap_or(" ") );
}
}
if opts {
println!("");
println!("OPTIONS:");
for v in self.opts.values() {
let mut needs_tab = false;
println!("\t{}{}{}\t{}",
if let Some(s) = v.short{format!("-{} ",s)}else{" ".to_owned()},
if let Some(l) = v.long {format!(",--{}=",l)}else {needs_tab = true; " ".to_owned()},
format!("{}", v.name),
if let Some(h) = v.help {
format!("{}{}{}",
if needs_tab { "\t" } else { "" },
h,
if let Some(ref pv) = v.possible_vals {
format!(" [values:{}]", pv.iter().fold(String::new(), |acc, name| acc + &format!("{}",name)[..] ))
}else{"".to_owned()})
} else {
" ".to_owned()
} );
}
}
if pos {
println!("");
println!("POSITIONAL ARGUMENTS:");
for v in self.positionals_idx.values() {
println!("\t{}\t\t{}", v.name,
if let Some(h) = v.help {
format!("{}{}",
h,
if let Some(ref pv) = v.possible_vals {
format!(" [values:{}]", pv.iter().fold(String::new(), |acc, name| acc + &format!(" {}",name)[..] ))
}else{"".to_owned()})
} else {
" ".to_owned()
} );
}
}
if subcmds {
println!("");
println!("SUBCOMMANDS:");
for sc in self.subcommands.values() {
println!("\t{}\t\t{}", sc.name,
if let Some(a) = sc.about {a} else {" "} );
}
}
self.exit();
}
fn print_version(&self, quit: bool) {
println!("{} {}", self.bin_name.clone().unwrap_or(self.name.clone()), self.version.unwrap_or("") );
if quit { self.exit(); }
}
fn exit(&self) {
unsafe { libc::exit(0); }
}
fn report_error(&self, msg: String, usage: bool, quit: bool) {
println!("{}", msg);
if usage { self.print_usage(true); }
if quit { env::set_exit_status(1); self.exit(); }
}
pub fn get_matches(mut self) -> ArgMatches<'ar> {
let mut matches = ArgMatches::new();
let args = env::args().collect::<Vec<_>>();
let mut it = args.into_iter();
if let Some(name) = it.next() {
let p = Path::new(&name[..]);
if let Some(f) = p.file_name() {
if let Ok(s) = f.to_os_string().into_string() {
self.bin_name = Some(s);
}
}
}
self.get_matches_from(&mut matches, &mut it );
matches
}
fn get_matches_from(&mut self, matches: &mut ArgMatches<'ar>, it: &mut IntoIter<String>) {
self.create_help_and_version();
let mut pos_only = false;
let mut subcmd_name: Option<String> = None;
let mut needs_val_of: Option<&str> = None;
let mut pos_counter = 1;
while let Some(arg) = it.next() {
let arg_slice = &arg[..];
let mut skip = false;
if !pos_only {
if let Some(nvo) = needs_val_of {
if let Some(ref opt) = self.opts.get(nvo) {
if let Some(ref p_vals) = opt.possible_vals {
if !p_vals.is_empty() {
if !p_vals.contains(arg_slice) {
self.report_error(format!("\"{}\" isn't a valid value for {}{}",
arg_slice,
if opt.long.is_some() {
format!("--{}",opt.long.unwrap())
}else{
format!("-{}", opt.short.unwrap())
},
format!("\n\t[valid values:{}]", p_vals.iter().fold(String::new(), |acc, name| acc + &format!(" {}",name)[..] )) ), true, true);
}
}
}
if let Some(ref mut o) = matches.opts.get_mut(opt.name) {
o.values.push(arg.clone());
o.occurrences = if opt.multiple { o.occurrences + 1 } else { 1 };
}
skip = true;
}
}
}
if skip {
needs_val_of = None;
continue;
}
if arg_slice.starts_with("--") && !pos_only {
if arg_slice.len() == 2 {
pos_only = true;
continue;
}
// Single flag, or option long version
needs_val_of = self.parse_long_arg(matches, &arg);
} else if arg_slice.starts_with("-") && arg_slice.len() != 1 && ! pos_only {
needs_val_of = self.parse_short_arg(matches, &arg);
} else {
// Positional or Subcommand
if self.subcommands.contains_key(&arg) {
if arg_slice == "help" {
self.print_help();
}
subcmd_name = Some(arg.clone());
break;
}
if self.positionals_idx.is_empty() {
self.report_error(
format!("Found positional argument {}, but {} doesn't accept any", arg, self.name),
true, true);
}
if let Some(p) = self.positionals_idx.get(&pos_counter) {
if self.blacklist.contains(p.name) {
self.report_error(format!("The argument \"{}\" is mutually exclusive with one or more other arguments", arg),
true, true);
}
if let Some(ref p_vals) = p.possible_vals {
if !p_vals.is_empty() {
if !p_vals.contains(arg_slice) {
self.report_error(format!("\"{}\" isn't a valid value for {}{}",
arg_slice,
p.name,
format!("\n\t[valid values:{}]", p_vals.iter().fold(String::new(), |acc, name| acc + &format!(" {}",name)[..] )) ), true, true);
}
}
}
matches.positionals.insert(p.name, PosArg{
name: p.name.to_owned(),
value: arg.clone(),
});
if let Some(ref bl) = p.blacklist {
for name in bl {
self.blacklist.insert(name);
}
}
if self.required.contains(p.name) {
self.required.remove(p.name);
}
if let Some(ref reqs) = p.requires {
// Add all required args which aren't already found in matches to the
// final required list
for n in reqs {
if matches.positionals.contains_key(n) {continue;}
if matches.opts.contains_key(n) {continue;}
if matches.flags.contains_key(n) {continue;}
self.required.insert(n);
}
}
pos_counter += 1;
} else {
self.report_error(format!("Positional argument \"{}\" was found, but {} wasn't expecting any", arg, self.name), true, true);
}
}
}
match needs_val_of {
Some(ref a) => {
self.report_error(
format!("Argument \"{}\" requires a value but none was supplied", a),
true, true);
}
_ => {}
}
if !self.required.is_empty() {
self.report_error("One or more required arguments were not supplied".to_owned(),
true, true);
}
self.validate_blacklist(&matches);
if let Some(sc_name) = subcmd_name {
if let Some(ref mut sc) = self.subcommands.get_mut(&sc_name) {
let mut new_matches = ArgMatches::new();
sc.bin_name = Some(format!("{}{}{}", self.bin_name.clone().unwrap_or("".to_owned()),if self.bin_name.is_some() {"-"} else {""}, sc.name.clone()));
sc.get_matches_from(&mut new_matches, it);
matches.subcommand = Some(Box::new(SubCommand{
name: sc.name.clone(),
matches: new_matches}));
}
}
}
fn create_help_and_version(&mut self) {
if self.needs_long_help {
self.flags.insert("clap_help", FlagBuilder {
name: "clap_help",
short: if self.needs_short_help { Some('h') } else { None },
long: Some("help"),
help: Some("Prints this message"),
blacklist: None,
multiple: false,
requires: None,
});
}
if self.needs_long_version {
self.flags.insert("clap_version", FlagBuilder {
name: "clap_version",
short: if self.needs_short_help { Some('v') } else { None },
long: Some("version"),
help: Some("Prints version information"),
blacklist: None,
multiple: false,
requires: None,
});
}
if self.needs_subcmd_help && !self.subcommands.is_empty() {
self.subcommands.insert("help".to_owned(), App::new("help").about("Prints this message"));
}
}
fn check_for_help_and_version(&self, arg: char) {
if arg == 'h' && self.needs_short_help {
self.print_help();
} else if arg == 'v' && self.needs_short_version {
self.print_version(true);
}
}
fn parse_long_arg(&mut self, matches: &mut ArgMatches<'ar> ,full_arg: &String) -> Option<&'ar str> {
let mut arg = full_arg.trim_left_matches(|c| c == '-');
if arg == "help" && self.needs_long_help {
self.print_help();
} else if arg == "version" && self.needs_long_version {
self.print_version(true);
}
let mut arg_val: Option<String> = None;
if arg.contains("=") {
let arg_vec: Vec<&str> = arg.split("=").collect();
arg = arg_vec[0];
// prevents "--config= value" typo
if arg_vec[1].len() == 0 {
self.report_error(format!("Argument --{} requires a value, but none was supplied", arg), true, true);
}
arg_val = Some(arg_vec[1].to_owned());
}
if let Some(v) = self.opts.values().filter(|&v| v.long.is_some()).filter(|&v| v.long.unwrap() == arg).nth(0) {
// Ensure this option isn't on the master mutually excludes list
if self.blacklist.contains(v.name) {
self.report_error(format!("The argument --{} is mutually exclusive with one or more other arguments", arg),
true, true);
}
if matches.opts.contains_key(v.name) {
if !v.multiple {
self.report_error(format!("Argument --{} was supplied more than once, but does not support multiple values", arg), true, true);
}
if let Some(ref p_vals) = v.possible_vals {
if let Some(ref av) = arg_val {
if !p_vals.contains(&av[..]) {
self.report_error(format!("\"{}\" isn't a valid value for {}{}",
arg_val.clone().unwrap_or(arg.to_owned()),
if v.long.is_some() {
format!("--{}", v.long.unwrap())
}else{
format!("-{}", v.short.unwrap())
},
format!("\n\t[valid values:{}]", p_vals.iter().fold(String::new(), |acc, name| acc + &format!(" {}",name)[..] )) ), true, true);
}
}
}
if arg_val.is_some() {
if let Some(ref mut o) = matches.opts.get_mut(v.name) {
o.occurrences += 1;
o.values.push(arg_val.clone().unwrap());
}
}
} else {
matches.opts.insert(v.name, OptArg{
name: v.name.to_owned(),
// If arg_val is None occurrences will get incremented upon receiving a value
occurrences: if arg_val.is_some() { 1 } else { 0 },
values: if arg_val.is_some() { vec![arg_val.clone().unwrap()]} else {vec![]}
});
}
if let Some(ref bl) = v.blacklist {
for name in bl {
self.blacklist.insert(name);
}
}
if self.required.contains(v.name) {
self.required.remove(v.name);
}
if let Some(ref reqs) = v.requires {
// Add all required args which aren't already found in matches to the
// final required list
for n in reqs {
if matches.opts.contains_key(n) { continue; }
if matches.flags.contains_key(n) { continue; }
if matches.positionals.contains_key(n) { continue; }
self.required.insert(n);
}
}
match arg_val {
None => { return Some(v.name); },
_ => { return None; }
}
}
if let Some(v) = self.flags.values().filter(|&v| v.long.is_some()).filter(|&v| v.long.unwrap() == arg).nth(0) {
// Ensure this flag isn't on the mutually excludes list
if self.blacklist.contains(v.name) {
self.report_error(format!("The argument --{} is mutually exclusive with one or more other arguments", arg),
true, true);
}
// Make sure this isn't one being added multiple times if it doesn't suppor it
if matches.flags.contains_key(v.name) && !v.multiple {
self.report_error(format!("Argument --{} was supplied more than once, but does not support multiple values", arg), true, true);
}
let mut
done = false;
if let Some(ref mut f) = matches.flags.get_mut(v.name) {
done = true;
f.occurrences = if v.multiple { f.occurrences + 1 } else { 1 };
}
if !done {
matches.flags.insert(v.name, FlagArg{
name: v.name.to_owned(),
occurrences: 1
});
}
// If this flag was requierd, remove it
// .. even though Flags shouldn't be required
if self.required.contains(v.name) {
self.required.remove(v.name);
}
// Add all of this flags "mutually excludes" list to the master list
if let Some(ref bl) = v.blacklist {
for name in bl {
self.blacklist.insert(name);
}
}
// Add all required args which aren't already found in matches to the master list
if let Some(ref reqs) = v.requires {
for n in reqs {
if matches.flags.contains_key(n) { continue; }
if matches.opts.contains_key(n) { continue; }
if matches.positionals.contains_key(n) { continue; }
self.required.insert(n);
}
}
return None;
}
// Shouldn't reach here
self.report_error(format!("Argument --{} isn't valid", arg), true, true);
unreachable!();
}
fn parse_short_arg(&mut self, matches: &mut ArgMatches<'ar> ,full_arg: &String) -> Option<&'ar str> {
let arg = &full_arg[..].trim_left_matches(|c| c == '-');
if arg.len() > 1 {
// Multiple flags using short i.e. -bgHlS
for c in arg.chars() {
self.check_for_help_and_version(c);
if !self.parse_single_short_flag(matches, c) {
self.report_error(format!("Argument -{} isn't valid",arg), true, true);
}
}
return None;
}
// Short flag or opt
let arg_c = arg.chars().nth(0).unwrap();
// Ensure the arg in question isn't a help or version flag
self.check_for_help_and_version(arg_c);
// Check for a matching flag, and return none if found
if self.parse_single_short_flag(matches, arg_c) { return None; }
// Check for matching short in options, and return the name
// (only ones with shorts, of course)
if let Some(v) = self.opts.values().filter(|&v| v.short.is_some()).filter(|&v| v.short.unwrap() == arg_c).nth(0) {
// Ensure this option isn't on the master mutually excludes list
if self.blacklist.contains(v.name) {
self.report_error(format!("The argument --{} is mutually exclusive with one or more other arguments", arg),
true, true);
}
if matches.opts.contains_key(v.name) {
if !v.multiple {
self.report_error(format!("Argument -{} was supplied more than once, but does not support multiple values", arg), true, true);
}
} else {
matches.opts.insert(v.name, OptArg{
name: v.name.to_owned(),
// occurrences will get incremented upon receiving a value
occurrences: 0,
values: vec![]
});
}
if let Some(ref bl) = v.blacklist {
for name in bl {
self.blacklist.insert(name);
}
}
if self.required.contains(v.name) {
self.required.remove(v.name);
}
if let Some(ref reqs) = v.requires {
// Add all required args which aren't already found in matches to the
// final required list
for n in reqs {
if matches.opts.contains_key(n) { continue; }
if matches.flags.contains_key(n) { continue; }
if matches.positionals.contains_key(n) { continue; }
self.required.insert(n);
}
}
return Some(v.name)
}
// Didn't match a flag or option, must be invalid
self.report_error( format!("Argument -{} isn't valid",arg_c), true, true);
unreachable!();
}
fn parse_single_short_flag(&mut self, matches: &mut ArgMatches<'ar>, arg: char) -> bool {
for v in self.flags.values().filter(|&v| v.short.is_some()).filter(|&v| v.short.unwrap() == arg) {
// Ensure this flag isn't on the mutually excludes list
if self.blacklist.contains(v.name) {
self.report_error(format!("The argument -{} is mutually exclusive with one or more other arguments", arg),
true, true);
}
// Make sure this isn't one being added multiple times if it doesn't suppor it
if matches.flags.contains_key(v.name) && !v.multiple {
self.report_error(format!("Argument -{} was supplied more than once, but does not support multiple values", arg), true, true);
}
let mut done = false;
if let Some(ref mut f) = matches.flags.get_mut(v.name) {
done = true;
f.occurrences = if v.multiple { f.occurrences + 1 } else { 1 };
}
if !done {
matches.flags.insert(v.name, FlagArg{
name: v.name.to_owned(),
occurrences: 1
});
}
// If this flag was requierd, remove it
// .. even though Flags shouldn't be required
if self.required.contains(v.name) {
self.required.remove(v.name);
}
// Add all of this flags "mutually excludes" list to the master list
if let Some(ref bl) = v.blacklist {
for name in bl {
self.blacklist.insert(name);
}
}
// Add all required args which aren't already found in matches to the master list
if let Some(ref reqs) = v.requires {
for n in reqs {
if matches.flags.contains_key(n) { continue; }
if matches.opts.contains_key(n) { continue; }
if matches.positionals.contains_key(n) { continue; }
self.required.insert(n);
}
}
return true;
}
false
}
fn validate_blacklist(&self, matches: &ArgMatches<'ar>) {
for name in self.blacklist.iter() {
if matches.flags.contains_key(name) {
self.report_error(format!("The argument {} is mutually exclusive with one or more other arguments",
if let Some(s) = self.flags.get(name).unwrap().short {
format!("-{}", s)
} else if let Some(l) = self.flags.get(name).unwrap().long {
format!("--{}", l)
} else {
format!("\"{}\"", name)
}), true, true);
}
if matches.opts.contains_key(name) {
self.report_error(format!("The argument {} is mutually exclusive with one or more other arguments",
if let Some(s) = self.opts.get(name).unwrap().short {
format!("-{}", s)
} else if let Some(l) = self.opts.get(name).unwrap().long {
format!("--{}", l)
} else {
format!("\"{}\"", name)
}), true, true);
}
if matches.positionals.contains_key(name) {
self.report_error(format!("The argument \"{}\" is mutually exclusive with one or more other arguments",name),
false, true);
}
}
}
}