-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
parser.rs
1941 lines (1795 loc) · 79.2 KB
/
parser.rs
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
// Std
use std::ffi::{OsStr, OsString};
use std::fmt::Display;
use std::fs::File;
use std::io::{self, BufWriter, Write};
#[cfg(feature = "debug")]
use std::os::unix::ffi::OsStrExt;
use std::path::PathBuf;
use std::slice::Iter;
use std::iter::Peekable;
// Internal
use INTERNAL_ERROR_MSG;
use INVALID_UTF8;
use SubCommand;
use app::App;
use app::help::Help;
use app::meta::AppMeta;
use app::settings::AppFlags;
use args::{AnyArg, ArgMatcher, Base, Switched, Arg, ArgGroup, FlagBuilder, OptBuilder, PosBuilder};
use args::settings::ArgSettings;
use completions::ComplGen;
use errors::{Error, ErrorKind};
use errors::Result as ClapResult;
use fmt::ColorWhen;
use osstringext::OsStrExt2;
use completions::Shell;
use suggestions;
use app::settings::AppSettings as AS;
use app::validator::Validator;
use app::usage;
use map::{self, VecMap};
#[derive(Debug, PartialEq, Copy, Clone)]
#[doc(hidden)]
pub enum ParseResult<'a> {
Flag,
Opt(&'a str),
Pos(&'a str),
MaybeHyphenValue,
MaybeNegNum,
NotFound,
ValuesDone,
}
#[allow(missing_debug_implementations)]
#[doc(hidden)]
#[derive(Clone, Default)]
pub struct Parser<'a, 'b>
where 'a: 'b
{
pub meta: AppMeta<'b>,
settings: AppFlags,
pub g_settings: AppFlags,
pub flags: Vec<FlagBuilder<'a, 'b>>,
pub opts: Vec<OptBuilder<'a, 'b>>,
pub positionals: VecMap<PosBuilder<'a, 'b>>,
pub subcommands: Vec<App<'a, 'b>>,
pub groups: Vec<ArgGroup<'a>>,
pub global_args: Vec<Arg<'a, 'b>>,
pub required: Vec<&'a str>,
pub r_ifs: Vec<(&'a str, &'b str, &'a str)>,
pub blacklist: Vec<&'b str>,
pub overrides: Vec<&'b str>,
help_short: Option<char>,
version_short: Option<char>,
cache: Option<&'a str>,
pub help_message: Option<&'a str>,
pub version_message: Option<&'a str>,
}
impl<'a, 'b> Parser<'a, 'b>
where 'a: 'b
{
pub fn with_name(n: String) -> Self {
Parser {
meta: AppMeta::with_name(n),
..Default::default()
}
}
pub fn help_short(&mut self, s: &str) {
let c = s.trim_left_matches(|c| c == '-')
.chars()
.nth(0)
.unwrap_or('h');
self.help_short = Some(c);
}
pub fn version_short(&mut self, s: &str) {
let c = s.trim_left_matches(|c| c == '-')
.chars()
.nth(0)
.unwrap_or('V');
self.version_short = Some(c);
}
pub fn gen_completions_to<W: Write>(&mut self, for_shell: Shell, buf: &mut W) {
if !self.is_set(AS::Propagated) {
self.propagate_help_version();
self.build_bin_names();
self.propagate_globals();
self.propagate_settings();
self.set(AS::Propagated);
}
ComplGen::new(self).generate(for_shell, buf)
}
pub fn gen_completions(&mut self, for_shell: Shell, od: OsString) {
use std::error::Error;
let out_dir = PathBuf::from(od);
let name = &*self.meta.bin_name.as_ref().unwrap().clone();
let file_name = match for_shell {
Shell::Bash => format!("{}.bash-completion", name),
Shell::Fish => format!("{}.fish", name),
Shell::Zsh => format!("_{}", name),
Shell::PowerShell => format!("_{}.ps1", name),
};
let mut file = match File::create(out_dir.join(file_name)) {
Err(why) => panic!("couldn't create completion file: {}", why.description()),
Ok(file) => file,
};
self.gen_completions_to(for_shell, &mut file)
}
#[inline]
fn app_debug_asserts(&mut self) -> bool {
assert!(self.verify_positionals());
let should_err = self.groups
.iter()
.all(|g| {
g.args
.iter()
.all(|arg| {
(self.flags.iter().any(|f| &f.b.name == arg) ||
self.opts.iter().any(|o| &o.b.name == arg) ||
self.positionals.values().any(|p| &p.b.name == arg) ||
self.groups.iter().any(|g| &g.name == arg))
})
});
let g = self.groups
.iter()
.find(|g| {
g.args
.iter()
.any(|arg| {
!(self.flags.iter().any(|f| &f.b.name == arg) ||
self.opts.iter().any(|o| &o.b.name == arg) ||
self.positionals.values().any(|p| &p.b.name == arg) ||
self.groups.iter().any(|g| &g.name == arg))
})
});
assert!(should_err,
"The group '{}' contains the arg '{}' that doesn't actually exist.",
g.unwrap().name,
g.unwrap()
.args
.iter()
.find(|arg| {
!(self.flags.iter().any(|f| &&f.b.name == arg) ||
self.opts.iter().any(|o| &&o.b.name == arg) ||
self.positionals.values().any(|p| &&p.b.name == arg) ||
self.groups.iter().any(|g| &&g.name == arg))
})
.unwrap());
true
}
#[inline]
fn debug_asserts(&self, a: &Arg) -> bool {
assert!(!arg_names!(self).any(|name| name == a.b.name),
format!("Non-unique argument name: {} is already in use", a.b.name));
if let Some(l) = a.s.long {
assert!(!self.contains_long(l),
"Argument long must be unique\n\n\t--{} is already in use",
l);
}
if let Some(s) = a.s.short {
assert!(!self.contains_short(s),
"Argument short must be unique\n\n\t-{} is already in use",
s);
}
let i = if a.index.is_none() {
(self.positionals.len() + 1)
} else {
a.index.unwrap() as usize
};
assert!(!self.positionals.contains_key(i),
"Argument \"{}\" has the same index as another positional \
argument\n\n\tPerhaps try .multiple(true) to allow one positional argument \
to take multiple values",
a.b.name);
assert!(!(a.is_set(ArgSettings::Required) && a.is_set(ArgSettings::Global)),
"Global arguments cannot be required.\n\n\t'{}' is marked as \
global and required",
a.b.name);
if a.b.is_set(ArgSettings::Last) {
assert!(!self.positionals
.values()
.any(|p| p.b.is_set(ArgSettings::Last)),
"Only one positional argument may have last(true) set. Found two.");
assert!(a.s.long.is_none(),
"Flags or Options may not have last(true) set. {} has both a long and last(true) set.",
a.b.name);
assert!(a.s.short.is_none(),
"Flags or Options may not have last(true) set. {} has both a short and last(true) set.",
a.b.name);
}
true
}
#[inline]
fn add_conditional_reqs(&mut self, a: &Arg<'a, 'b>) {
if let Some(ref r_ifs) = a.r_ifs {
for &(arg, val) in r_ifs {
self.r_ifs.push((arg, val, a.b.name));
}
}
}
#[inline]
fn add_arg_groups(&mut self, a: &Arg<'a, 'b>) {
if let Some(ref grps) = a.b.groups {
for g in grps {
let mut found = false;
if let Some(ref mut ag) = self.groups.iter_mut().find(|grp| &grp.name == g) {
ag.args.push(a.b.name);
found = true;
}
if !found {
let mut ag = ArgGroup::with_name(g);
ag.args.push(a.b.name);
self.groups.push(ag);
}
}
}
}
#[inline]
fn add_reqs(&mut self, a: &Arg<'a, 'b>) {
if a.is_set(ArgSettings::Required) {
// If the arg is required, add all it's requirements to master required list
if let Some(ref areqs) = a.b.requires {
for name in areqs
.iter()
.filter(|&&(val, _)| val.is_none())
.map(|&(_, name)| name) {
self.required.push(name);
}
}
self.required.push(a.b.name);
}
}
#[inline]
fn implied_settings(&mut self, a: &Arg<'a, 'b>) {
if a.is_set(ArgSettings::Last) {
// if an arg has `Last` set, we need to imply DontCollapseArgsInUsage so that args
// in the usage string don't get confused or left out.
self.set(AS::DontCollapseArgsInUsage);
self.set(AS::ContainsLast);
}
if let Some(l) = a.s.long {
if l == "version" {
self.unset(AS::NeedsLongVersion);
} else if l == "help" {
self.unset(AS::NeedsLongHelp);
}
}
}
// actually adds the arguments
pub fn add_arg(&mut self, a: Arg<'a, 'b>) {
// if it's global we have to clone anyways
if a.is_set(ArgSettings::Global) {
return self.add_arg_ref(&a);
}
debug_assert!(self.debug_asserts(&a));
self.add_conditional_reqs(&a);
self.add_arg_groups(&a);
self.add_reqs(&a);
self.implied_settings(&a);
if a.index.is_some() || (a.s.short.is_none() && a.s.long.is_none()) {
let i = if a.index.is_none() {
(self.positionals.len() + 1)
} else {
a.index.unwrap() as usize
};
self.positionals
.insert(i, PosBuilder::from_arg(a, i as u64));
} else if a.is_set(ArgSettings::TakesValue) {
let mut ob = OptBuilder::from(a);
ob.s.unified_ord = self.flags.len() + self.opts.len();
self.opts.push(ob);
} else {
let mut fb = FlagBuilder::from(a);
fb.s.unified_ord = self.flags.len() + self.opts.len();
self.flags.push(fb);
}
}
// actually adds the arguments but from a borrow (which means we have to do some clonine)
pub fn add_arg_ref(&mut self, a: &Arg<'a, 'b>) {
debug_assert!(self.debug_asserts(a));
self.add_conditional_reqs(a);
self.add_arg_groups(a);
self.add_reqs(a);
self.implied_settings(a);
if a.index.is_some() || (a.s.short.is_none() && a.s.long.is_none()) {
let i = if a.index.is_none() {
(self.positionals.len() + 1)
} else {
a.index.unwrap() as usize
};
let pb = PosBuilder::from_arg_ref(a, i as u64);
self.positionals.insert(i, pb);
} else if a.is_set(ArgSettings::TakesValue) {
let mut ob = OptBuilder::from(a);
ob.s.unified_ord = self.flags.len() + self.opts.len();
self.opts.push(ob);
} else {
let mut fb = FlagBuilder::from(a);
fb.s.unified_ord = self.flags.len() + self.opts.len();
self.flags.push(fb);
}
if a.is_set(ArgSettings::Global) {
self.global_args.push(a.into());
}
}
pub fn add_group(&mut self, group: ArgGroup<'a>) {
if group.required {
self.required.push(group.name);
if let Some(ref reqs) = group.requires {
self.required.extend_from_slice(reqs);
}
if let Some(ref bl) = group.conflicts {
self.blacklist.extend_from_slice(bl);
}
}
if self.groups.iter().any(|g| g.name == group.name) {
let grp = self.groups
.iter_mut()
.find(|g| g.name == group.name)
.expect(INTERNAL_ERROR_MSG);
grp.args.extend_from_slice(&group.args);
grp.requires = group.requires.clone();
grp.conflicts = group.conflicts.clone();
grp.required = group.required;
} else {
self.groups.push(group);
}
}
pub fn add_subcommand(&mut self, mut subcmd: App<'a, 'b>) {
debugln!("Parser::add_subcommand: term_w={:?}, name={}",
self.meta.term_w,
subcmd.p.meta.name);
subcmd.p.meta.term_w = self.meta.term_w;
if subcmd.p.meta.name == "help" {
self.unset(AS::NeedsSubcommandHelp);
}
self.subcommands.push(subcmd);
}
pub fn propagate_settings(&mut self) {
debugln!("Parser::propagate_settings: self={}, g_settings={:#?}",
self.meta.name,
self.g_settings);
for sc in &mut self.subcommands {
debugln!("Parser::propagate_settings: sc={}, settings={:#?}, g_settings={:#?}",
sc.p.meta.name,
sc.p.settings,
sc.p.g_settings);
// We have to create a new scope in order to tell rustc the borrow of `sc` is
// done and to recursively call this method
{
let vsc = self.settings.is_set(AS::VersionlessSubcommands);
let gv = self.settings.is_set(AS::GlobalVersion);
if vsc {
sc.p.set(AS::DisableVersion);
}
if gv && sc.p.meta.version.is_none() && self.meta.version.is_some() {
sc.p.set(AS::GlobalVersion);
sc.p.meta.version = Some(self.meta.version.unwrap());
}
sc.p.settings = sc.p.settings | self.g_settings;
sc.p.g_settings = sc.p.g_settings | self.g_settings;
sc.p.meta.term_w = self.meta.term_w;
sc.p.meta.max_w = self.meta.max_w;
}
sc.p.propagate_settings();
}
}
#[cfg_attr(feature = "lints", allow(needless_borrow))]
pub fn derive_display_order(&mut self) {
if self.is_set(AS::DeriveDisplayOrder) {
let unified = self.is_set(AS::UnifiedHelpMessage);
for (i, o) in self.opts
.iter_mut()
.enumerate()
.filter(|&(_, ref o)| o.s.disp_ord == 999) {
o.s.disp_ord = if unified { o.s.unified_ord } else { i };
}
for (i, f) in self.flags
.iter_mut()
.enumerate()
.filter(|&(_, ref f)| f.s.disp_ord == 999) {
f.s.disp_ord = if unified { f.s.unified_ord } else { i };
}
for (i, sc) in &mut self.subcommands
.iter_mut()
.enumerate()
.filter(|&(_, ref sc)| sc.p.meta.disp_ord == 999) {
sc.p.meta.disp_ord = i;
}
}
for sc in &mut self.subcommands {
sc.p.derive_display_order();
}
}
pub fn required(&self) -> Iter<&str> { self.required.iter() }
#[cfg_attr(feature = "lints", allow(needless_borrow))]
#[inline]
pub fn has_args(&self) -> bool {
!(self.flags.is_empty() && self.opts.is_empty() && self.positionals.is_empty())
}
#[inline]
pub fn has_opts(&self) -> bool { !self.opts.is_empty() }
#[inline]
pub fn has_flags(&self) -> bool { !self.flags.is_empty() }
#[inline]
pub fn has_positionals(&self) -> bool { !self.positionals.is_empty() }
#[inline]
pub fn has_subcommands(&self) -> bool { !self.subcommands.is_empty() }
#[inline]
pub fn has_visible_opts(&self) -> bool {
if self.opts.is_empty() {
return false;
}
self.opts.iter().any(|o| !o.is_set(ArgSettings::Hidden))
}
#[inline]
pub fn has_visible_flags(&self) -> bool {
if self.flags.is_empty() {
return false;
}
self.flags.iter().any(|f| !f.is_set(ArgSettings::Hidden))
}
#[inline]
pub fn has_visible_positionals(&self) -> bool {
if self.positionals.is_empty() {
return false;
}
self.positionals
.values()
.any(|p| !p.is_set(ArgSettings::Hidden))
}
#[inline]
pub fn has_visible_subcommands(&self) -> bool {
self.has_subcommands() && self.subcommands.iter().filter(|sc| sc.p.meta.name != "help").any(|sc| !sc.p.is_set(AS::Hidden))
}
#[inline]
pub fn is_set(&self, s: AS) -> bool { self.settings.is_set(s) }
#[inline]
pub fn set(&mut self, s: AS) { self.settings.set(s) }
#[inline]
pub fn unset(&mut self, s: AS) { self.settings.unset(s) }
#[cfg_attr(feature = "lints", allow(block_in_if_condition_stmt))]
pub fn verify_positionals(&mut self) -> bool {
// Because you must wait until all arguments have been supplied, this is the first chance
// to make assertions on positional argument indexes
//
// Firt we verify that the index highest supplied index, is equal to the number of
// positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3
// but no 2)
if let Some((idx, p)) = self.positionals.iter().rev().next() {
assert!(!(idx != self.positionals.len()),
"Found positional argument \"{}\" whose index is {} but there \
are only {} positional arguments defined",
p.b.name,
idx,
self.positionals.len());
}
// Next we verify that only the highest index has a .multiple(true) (if any)
if self.positionals
.values()
.any(|a| {
a.b.is_set(ArgSettings::Multiple) &&
(a.index as usize != self.positionals.len())
}) {
let mut it = self.positionals.values().rev();
let last = it.next().unwrap();
let second_to_last = it.next().unwrap();
// Either the final positional is required
// Or the second to last has a terminator or .last(true) set
let ok = last.is_set(ArgSettings::Required) ||
(second_to_last.v.terminator.is_some() ||
second_to_last.b.is_set(ArgSettings::Last)) ||
last.is_set(ArgSettings::Last);
assert!(ok,
"When using a positional argument with .multiple(true) that is *not the \
last* positional argument, the last positional argument (i.e the one \
with the highest index) *must* have .required(true) or .last(true) set.");
let ok = second_to_last.is_set(ArgSettings::Multiple) || last.is_set(ArgSettings::Last);
assert!(ok,
"Only the last positional argument, or second to last positional \
argument may be set to .multiple(true)");
let count = self.positionals
.values()
.filter(|p| p.b.settings.is_set(ArgSettings::Multiple) && p.v.num_vals.is_none())
.count();
let ok = count <= 1 ||
(last.is_set(ArgSettings::Last) && last.is_set(ArgSettings::Multiple) &&
second_to_last.is_set(ArgSettings::Multiple) &&
count == 2);
assert!(ok,
"Only one positional argument with .multiple(true) set is allowed per \
command, unless the second one also has .last(true) set");
}
if self.is_set(AS::AllowMissingPositional) {
// Check that if a required positional argument is found, all positions with a lower
// index are also required.
let mut found = false;
let mut foundx2 = false;
for p in self.positionals.values().rev() {
if foundx2 && !p.b.settings.is_set(ArgSettings::Required) {
assert!(p.b.is_set(ArgSettings::Required),
"Found positional argument which is not required with a lower \
index than a required positional argument by two or more: {:?} \
index {}",
p.b.name,
p.index);
} else if p.b.is_set(ArgSettings::Required) && !p.b.is_set(ArgSettings::Last) {
// Args that .last(true) don't count since they can be required and have
// positionals with a lower index that aren't required
// Imagine: prog <req1> [opt1] -- <req2>
// Both of these are valid invocations:
// $ prog r1 -- r2
// $ prog r1 o1 -- r2
if found {
foundx2 = true;
continue;
}
found = true;
continue;
} else {
found = false;
}
}
} else {
// Check that if a required positional argument is found, all positions with a lower
// index are also required
let mut found = false;
for p in self.positionals.values().rev() {
if found {
assert!(p.b.is_set(ArgSettings::Required),
"Found positional argument which is not required with a lower \
index than a required positional argument: {:?} index {}",
p.b.name,
p.index);
} else if p.b.is_set(ArgSettings::Required) && !p.b.is_set(ArgSettings::Last) {
// Args that .last(true) don't count since they can be required and have
// positionals with a lower index that aren't required
// Imagine: prog <req1> [opt1] -- <req2>
// Both of these are valid invocations:
// $ prog r1 -- r2
// $ prog r1 o1 -- r2
found = true;
continue;
}
}
}
if self.positionals
.values()
.any(|p| {
p.b.is_set(ArgSettings::Last) && p.b.is_set(ArgSettings::Required)
}) && self.has_subcommands() &&
!self.is_set(AS::SubcommandsNegateReqs) {
panic!("Having a required positional argument with .last(true) set *and* child \
subcommands without setting SubcommandsNegateReqs isn't compatible.");
}
true
}
pub fn propagate_globals(&mut self) {
for sc in &mut self.subcommands {
// We have to create a new scope in order to tell rustc the borrow of `sc` is
// done and to recursively call this method
{
for a in &self.global_args {
sc.p.add_arg_ref(a);
}
}
sc.p.propagate_globals();
}
}
// Checks if the arg matches a subcommand name, or any of it's aliases (if defined)
fn possible_subcommand(&self, arg_os: &OsStr) -> (bool, Option<&str>) {
debugln!("Parser::possible_subcommand: arg={:?}", arg_os);
fn starts(h: &str, n: &OsStr) -> bool {
#[cfg(not(target_os = "windows"))]
use std::os::unix::ffi::OsStrExt;
#[cfg(target_os = "windows")]
use osstringext::OsStrExt3;
let n_bytes = n.as_bytes();
let h_bytes = OsStr::new(h).as_bytes();
h_bytes.starts_with(n_bytes)
}
if self.is_set(AS::ArgsNegateSubcommands) && self.is_set(AS::ValidArgFound) {
return (false, None);
}
if !self.is_set(AS::InferSubcommands) {
if let Some(sc) = find_subcmd!(self, arg_os) {
return (true, Some(&sc.p.meta.name));
}
} else {
let v = self.subcommands
.iter()
.filter(|s| {
starts(&s.p.meta.name[..], &*arg_os) ||
(s.p.meta.aliases.is_some() &&
s.p
.meta
.aliases
.as_ref()
.unwrap()
.iter()
.filter(|&&(a, _)| starts(a, &*arg_os))
.count() == 1)
})
.map(|sc| &sc.p.meta.name)
.collect::<Vec<_>>();
if v.len() == 1 {
return (true, Some(v[0]));
}
}
(false, None)
}
fn parse_help_subcommand<I, T>(&self, it: &mut I) -> ClapResult<ParseResult<'a>>
where I: Iterator<Item = T>,
T: Into<OsString>
{
debugln!("Parser::parse_help_subcommand;");
let cmds: Vec<OsString> = it.map(|c| c.into()).collect();
let mut help_help = false;
let mut bin_name = self.meta
.bin_name
.as_ref()
.unwrap_or(&self.meta.name)
.clone();
let mut sc = {
let mut sc: &Parser = self;
for (i, cmd) in cmds.iter().enumerate() {
if &*cmd.to_string_lossy() == "help" {
// cmd help help
help_help = true;
}
if let Some(c) = sc.subcommands
.iter()
.find(|s| &*s.p.meta.name == cmd)
.map(|sc| &sc.p) {
sc = c;
if i == cmds.len() - 1 {
break;
}
} else if let Some(c) = sc.subcommands
.iter()
.find(|s| if let Some(ref als) = s.p.meta.aliases {
als.iter().any(|&(a, _)| a == &*cmd.to_string_lossy())
} else {
false
})
.map(|sc| &sc.p) {
sc = c;
if i == cmds.len() - 1 {
break;
}
} else {
return Err(Error::unrecognized_subcommand(cmd.to_string_lossy().into_owned(),
self.meta
.bin_name
.as_ref()
.unwrap_or(&self.meta.name),
self.color()));
}
bin_name = format!("{} {}", bin_name, &*sc.meta.name);
}
sc.clone()
};
if help_help {
let mut pb = PosBuilder::new("subcommand", 1);
pb.b.help = Some("The subcommand whose help message to display");
pb.set(ArgSettings::Multiple);
sc.positionals.insert(1, pb);
sc.settings = sc.settings | self.g_settings;
} else {
sc.create_help_and_version();
}
if sc.meta.bin_name != self.meta.bin_name {
sc.meta.bin_name = Some(format!("{} {}", bin_name, sc.meta.name));
}
Err(sc._help(false))
}
// allow wrong self convention due to self.valid_neg_num = true and it's a private method
#[cfg_attr(feature = "lints", allow(wrong_self_convention))]
fn is_new_arg(&mut self, arg_os: &OsStr, needs_val_of: ParseResult<'a>) -> bool {
debugln!("Parser::is_new_arg: arg={:?}, Needs Val of={:?}",
arg_os,
needs_val_of);
let app_wide_settings = if self.is_set(AS::AllowLeadingHyphen) {
true
} else if self.is_set(AS::AllowNegativeNumbers) {
let a = arg_os.to_string_lossy();
if a.parse::<i64>().is_ok() || a.parse::<f64>().is_ok() {
self.set(AS::ValidNegNumFound);
true
} else {
false
}
} else {
false
};
let arg_allows_tac = match needs_val_of {
ParseResult::Opt(name) => {
let o = self.opts
.iter()
.find(|o| o.b.name == name)
.expect(INTERNAL_ERROR_MSG);
(o.is_set(ArgSettings::AllowLeadingHyphen) || app_wide_settings)
}
ParseResult::Pos(name) => {
let p = self.positionals
.values()
.find(|p| p.b.name == name)
.expect(INTERNAL_ERROR_MSG);
(p.is_set(ArgSettings::AllowLeadingHyphen) || app_wide_settings)
}
_ => false,
};
debugln!("Parser::is_new_arg: Arg::allow_leading_hyphen({:?})",
arg_allows_tac);
// Is this a new argument, or values from a previous option?
let mut ret = if arg_os.starts_with(b"--") {
debugln!("Parser::is_new_arg: -- found");
if arg_os.len_() == 2 && !arg_allows_tac {
return true; // We have to return true so override everything else
} else if arg_allows_tac {
return false;
}
true
} else if arg_os.starts_with(b"-") {
debugln!("Parser::is_new_arg: - found");
// a singe '-' by itself is a value and typically means "stdin" on unix systems
!(arg_os.len_() == 1)
} else {
debugln!("Parser::is_new_arg: probably value");
false
};
ret = ret && !arg_allows_tac;
debugln!("Parser::is_new_arg: starts_new_arg={:?}", ret);
ret
}
// The actual parsing function
#[cfg_attr(feature = "lints", allow(while_let_on_iterator, collapsible_if))]
pub fn get_matches_with<I, T>(&mut self,
matcher: &mut ArgMatcher<'a>,
it: &mut Peekable<I>)
-> ClapResult<()>
where I: Iterator<Item = T>,
T: Into<OsString> + Clone
{
debugln!("Parser::get_matches_with;");
// Verify all positional assertions pass
debug_assert!(self.app_debug_asserts());
if self.positionals
.values()
.any(|a| {
a.b.is_set(ArgSettings::Multiple) &&
(a.index as usize != self.positionals.len())
}) &&
self.positionals
.values()
.last()
.map_or(false, |p| !p.is_set(ArgSettings::Last)) {
self.settings.set(AS::LowIndexMultiplePositional);
}
let has_args = self.has_args();
// Next we create the `--help` and `--version` arguments and add them if
// necessary
self.create_help_and_version();
let mut subcmd_name: Option<String> = None;
let mut needs_val_of: ParseResult<'a> = ParseResult::NotFound;
let mut pos_counter = 1;
while let Some(arg) = it.next() {
let arg_os = arg.into();
debugln!("Parser::get_matches_with: Begin parsing '{:?}' ({:?})",
arg_os,
&*arg_os.as_bytes());
self.unset(AS::ValidNegNumFound);
// Is this a new argument, or values from a previous option?
let starts_new_arg = self.is_new_arg(&arg_os, needs_val_of);
if arg_os.starts_with(b"--") && arg_os.len_() == 2 && starts_new_arg {
debugln!("Parser::get_matches_with: setting TrailingVals=true");
self.set(AS::TrailingValues);
continue;
}
// Has the user already passed '--'? Meaning only positional args follow
if !self.is_set(AS::TrailingValues) {
// Does the arg match a subcommand name, or any of it's aliases (if defined)
{
match needs_val_of {
ParseResult::Opt(_) | ParseResult::Pos(_) =>(),
_ => {
let (is_match, sc_name) = self.possible_subcommand(&arg_os);
debugln!("Parser::get_matches_with: possible_sc={:?}, sc={:?}",
is_match,
sc_name);
if is_match {
let sc_name = sc_name.expect(INTERNAL_ERROR_MSG);
if sc_name == "help" && self.is_set(AS::NeedsSubcommandHelp) {
self.parse_help_subcommand(it)?;
}
subcmd_name = Some(sc_name.to_owned());
break;
}
}
}
}
if !starts_new_arg {
if let ParseResult::Opt(name) = needs_val_of {
// Check to see if parsing a value from a previous arg
let arg = self.opts
.iter()
.find(|o| o.b.name == name)
.expect(INTERNAL_ERROR_MSG);
// get the OptBuilder so we can check the settings
needs_val_of = self.add_val_to_arg(arg, &arg_os, matcher)?;
// get the next value from the iterator
continue;
}
} else if arg_os.starts_with(b"--") {
needs_val_of = self.parse_long_arg(matcher, &arg_os)?;
debugln!("Parser:get_matches_with: After parse_long_arg {:?}",
needs_val_of);
match needs_val_of {
ParseResult::Flag |
ParseResult::Opt(..) |
ParseResult::ValuesDone => continue,
_ => (),
}
} else if arg_os.starts_with(b"-") && arg_os.len_() != 1 {
// Try to parse short args like normal, if AllowLeadingHyphen or
// AllowNegativeNumbers is set, parse_short_arg will *not* throw
// an error, and instead return Ok(None)
needs_val_of = self.parse_short_arg(matcher, &arg_os)?;
// If it's None, we then check if one of those two AppSettings was set
debugln!("Parser:get_matches_with: After parse_short_arg {:?}",
needs_val_of);
match needs_val_of {
ParseResult::MaybeNegNum => {
if !(arg_os.to_string_lossy().parse::<i64>().is_ok() ||
arg_os.to_string_lossy().parse::<f64>().is_ok()) {
return Err(Error::unknown_argument(&*arg_os.to_string_lossy(),
"",
&*usage::create_error_usage(self, matcher, None),
self.color()));
}
}
ParseResult::Opt(..) |
ParseResult::Flag |
ParseResult::ValuesDone => continue,
_ => (),
}
}
if !(self.is_set(AS::ArgsNegateSubcommands) && self.is_set(AS::ValidArgFound)) &&
!self.is_set(AS::InferSubcommands) {
if let Some(cdate) = suggestions::did_you_mean(&*arg_os.to_string_lossy(),
sc_names!(self)) {
return Err(Error::invalid_subcommand(arg_os
.to_string_lossy()
.into_owned(),
cdate,
self.meta
.bin_name
.as_ref()
.unwrap_or(&self.meta.name),
&*usage::create_error_usage(self,
matcher,
None),
self.color()));
}
}
}
let low_index_mults = self.is_set(AS::LowIndexMultiplePositional) &&
pos_counter == (self.positionals.len() - 1);
let missing_pos = self.is_set(AS::AllowMissingPositional) &&
pos_counter == (self.positionals.len() - 1);
debugln!("Parser::get_matches_with: Positional counter...{}",
pos_counter);
debugln!("Parser::get_matches_with: Low index multiples...{:?}",
low_index_mults);
if low_index_mults || missing_pos {
if let Some(na) = it.peek() {
let n = (*na).clone().into();
needs_val_of = if needs_val_of != ParseResult::ValuesDone {
if let Some(p) = self.positionals.get(pos_counter) {
ParseResult::Pos(p.b.name)
} else {
ParseResult::ValuesDone
}
} else {
ParseResult::ValuesDone
};
let sc_match = {
self.possible_subcommand(&n).0
};
if self.is_new_arg(&n, needs_val_of) || sc_match ||
suggestions::did_you_mean(&n.to_string_lossy(), sc_names!(self)).is_some() {
debugln!("Parser::get_matches_with: Bumping the positional counter...");
pos_counter += 1;
}
} else {
debugln!("Parser::get_matches_with: Bumping the positional counter...");
pos_counter += 1;
}
} else if self.is_set(AS::ContainsLast) && self.is_set(AS::TrailingValues) {
// Came to -- and one postional has .last(true) set, so we go immediately
// to the last (highest index) positional
debugln!("Parser::get_matches_with: .last(true) and --, setting last pos");
pos_counter = self.positionals.len();
}
if let Some(p) = self.positionals.get(pos_counter) {
if p.is_set(ArgSettings::Last) && !self.is_set(AS::TrailingValues) {
return Err(Error::unknown_argument(&*arg_os.to_string_lossy(),
"",
&*usage::create_error_usage(self,
matcher,
None),
self.color()));
}
parse_positional!(self, p, arg_os, pos_counter, matcher);
self.settings.set(AS::ValidArgFound);
} else if self.is_set(AS::AllowExternalSubcommands) {
// Get external subcommand name
let sc_name = match arg_os.to_str() {
Some(s) => s.to_string(),
None => {
if !self.is_set(AS::StrictUtf8) {
return Err(Error::invalid_utf8(&*usage::create_error_usage(self,
matcher,
None),
self.color()));
}
arg_os.to_string_lossy().into_owned()
}
};