forked from clap-rs/clap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.rs
3016 lines (2819 loc) · 109 KB
/
mod.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
#[cfg(debug_assertions)]
mod debug_asserts;
mod settings;
#[cfg(test)]
mod tests;
pub use self::settings::{AppFlags, AppSettings};
// Std
use std::{
collections::HashMap,
env,
ffi::OsString,
fmt,
io::{self, BufRead, Write},
ops::Index,
path::Path,
};
// Third Party
use os_str_bytes::RawOsStr;
#[cfg(feature = "yaml")]
use yaml_rust::Yaml;
// Internal
use crate::{
build::{arg::ArgProvider, Arg, ArgGroup, ArgSettings},
mkeymap::MKeyMap,
output::{fmt::Colorizer, Help, HelpWriter, Usage},
parse::{ArgMatcher, ArgMatches, Input, Parser},
util::{safe_exit, termcolor::ColorChoice, Id, Key, USAGE_CODE},
Result as ClapResult, INTERNAL_ERROR_MSG,
};
/// Represents a command line interface which is made up of all possible
/// command line arguments and subcommands. Interface arguments and settings are
/// configured using the "builder pattern." Once all configuration is complete,
/// the [`App::get_matches`] family of methods starts the runtime-parsing
/// process. These methods then return information about the user supplied
/// arguments (or lack thereof).
///
/// **NOTE:** There aren't any mandatory "options" that one must set. The "options" may
/// also appear in any order (so long as one of the [`App::get_matches`] methods is the last method
/// called).
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg};
/// let m = App::new("My Program")
/// .author("Me, me@mail.com")
/// .version("1.0.2")
/// .about("Explains in brief what the program does")
/// .arg(
/// Arg::new("in_file").index(1)
/// )
/// .after_help("Longer explanation to appear after the options when \
/// displaying the help information from --help or -h")
/// .get_matches();
///
/// // Your program logic starts here...
/// ```
/// [`App::get_matches`]: App::get_matches()
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct App<'help> {
pub(crate) id: Id,
pub(crate) name: String,
pub(crate) long_flag: Option<&'help str>,
pub(crate) short_flag: Option<char>,
pub(crate) bin_name: Option<String>,
pub(crate) author: Option<&'help str>,
pub(crate) version: Option<&'help str>,
pub(crate) long_version: Option<&'help str>,
pub(crate) license: Option<&'help str>,
pub(crate) about: Option<&'help str>,
pub(crate) long_about: Option<&'help str>,
pub(crate) before_help: Option<&'help str>,
pub(crate) before_long_help: Option<&'help str>,
pub(crate) after_help: Option<&'help str>,
pub(crate) after_long_help: Option<&'help str>,
pub(crate) aliases: Vec<(&'help str, bool)>, // (name, visible)
pub(crate) short_flag_aliases: Vec<(char, bool)>, // (name, visible)
pub(crate) long_flag_aliases: Vec<(&'help str, bool)>, // (name, visible)
pub(crate) usage_str: Option<&'help str>,
pub(crate) usage: Option<String>,
pub(crate) help_str: Option<&'help str>,
pub(crate) disp_ord: usize,
pub(crate) term_w: Option<usize>,
pub(crate) max_w: Option<usize>,
pub(crate) template: Option<&'help str>,
pub(crate) settings: AppFlags,
pub(crate) g_settings: AppFlags,
pub(crate) args: MKeyMap<'help>,
pub(crate) subcommands: Vec<App<'help>>,
pub(crate) replacers: HashMap<&'help str, &'help [&'help str]>,
pub(crate) groups: Vec<ArgGroup<'help>>,
pub(crate) current_help_heading: Option<&'help str>,
pub(crate) subcommand_placeholder: Option<&'help str>,
pub(crate) subcommand_header: Option<&'help str>,
}
impl<'help> App<'help> {
/// Get the name of the app.
#[inline]
pub fn get_name(&self) -> &str {
&self.name
}
/// Get the short flag of the subcommand.
#[inline]
pub fn get_short_flag(&self) -> Option<char> {
self.short_flag
}
/// Get the long flag of the subcommand.
#[inline]
pub fn get_long_flag(&self) -> Option<&str> {
self.long_flag
}
/// Get the name of the binary.
#[inline]
pub fn get_bin_name(&self) -> Option<&str> {
self.bin_name.as_deref()
}
/// Set binary name. Uses `&mut self` instead of `self`.
pub fn set_bin_name<S: Into<String>>(&mut self, name: S) {
self.bin_name = Some(name.into());
}
/// Get the help message specified via [`App::about`].
///
/// [`App::about`]: App::about()
#[inline]
pub fn get_about(&self) -> Option<&str> {
self.about
}
/// Get the help message specified via [`App::long_about`].
///
/// [`App::long_about`]: App::long_about()
#[inline]
pub fn get_long_about(&self) -> Option<&str> {
self.long_about
}
/// Iterate through the *visible* aliases for this subcommand.
#[inline]
pub fn get_visible_aliases(&self) -> impl Iterator<Item = &str> {
self.aliases.iter().filter(|(_, vis)| *vis).map(|a| a.0)
}
/// Iterate through the *visible* short aliases for this subcommand.
#[inline]
pub fn get_visible_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ {
self.short_flag_aliases
.iter()
.filter(|(_, vis)| *vis)
.map(|a| a.0)
}
/// Iterate through the *visible* long aliases for this subcommand.
#[inline]
pub fn get_visible_long_flag_aliases(&self) -> impl Iterator<Item = &'help str> + '_ {
self.long_flag_aliases
.iter()
.filter(|(_, vis)| *vis)
.map(|a| a.0)
}
/// Iterate through the set of *all* the aliases for this subcommand, both visible and hidden.
#[inline]
pub fn get_all_aliases(&self) -> impl Iterator<Item = &str> {
self.aliases.iter().map(|a| a.0)
}
/// Iterate through the set of *all* the short aliases for this subcommand, both visible and hidden.
#[inline]
pub fn get_all_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ {
self.short_flag_aliases.iter().map(|a| a.0)
}
/// Iterate through the set of *all* the long aliases for this subcommand, both visible and hidden.
#[inline]
pub fn get_all_long_flag_aliases(&self) -> impl Iterator<Item = &'help str> + '_ {
self.long_flag_aliases.iter().map(|a| a.0)
}
/// Iterate through the set of subcommands, getting a reference to each.
#[inline]
pub fn get_subcommands(&self) -> impl Iterator<Item = &App<'help>> {
self.subcommands.iter()
}
/// Iterate through the set of subcommands, getting a mutable reference to each.
#[inline]
pub fn get_subcommands_mut(&mut self) -> impl Iterator<Item = &mut App<'help>> {
self.subcommands.iter_mut()
}
/// Iterate through the set of arguments.
#[inline]
pub fn get_arguments(&self) -> impl Iterator<Item = &Arg<'help>> {
self.args.args()
}
/// Iterate through the *positionals*.
#[inline]
pub fn get_positionals(&self) -> impl Iterator<Item = &Arg<'help>> {
self.get_arguments().filter(|a| a.is_positional())
}
/// Iterate through the *flags*.
pub fn get_flags(&self) -> impl Iterator<Item = &Arg<'help>> {
self.get_arguments()
.filter(|a| !a.is_set(ArgSettings::TakesValue) && a.get_index().is_none())
}
/// Iterate through the *options*.
pub fn get_opts(&self) -> impl Iterator<Item = &Arg<'help>> {
self.get_arguments()
.filter(|a| a.is_set(ArgSettings::TakesValue) && a.get_index().is_none())
}
/// Iterate through the *positionals* that don't have custom heading.
pub fn get_positionals_with_no_heading(&self) -> impl Iterator<Item = &Arg<'help>> {
self.get_positionals()
.filter(|a| a.get_help_heading().is_none())
}
/// Iterate through the *flags* that don't have custom heading.
pub fn get_flags_with_no_heading(&self) -> impl Iterator<Item = &Arg<'help>> {
self.get_flags().filter(|a| a.get_help_heading().is_none())
}
/// Iterate through the *options* that don't have custom heading.
pub fn get_opts_with_no_heading(&self) -> impl Iterator<Item = &Arg<'help>> {
self.get_opts().filter(|a| a.get_help_heading().is_none())
}
// Get a list of subcommands which contain the provided Argument
//
// This command will only include subcommands in its list for which the subcommands
// parent also contains the Argument.
//
// This search follows the propagation rules of global arguments.
// It is useful to finding subcommands, that have inherited a global argument.
//
// **NOTE:** In this case only Sucommand_1 will be included
// Subcommand_1 (contains Arg)
// Subcommand_1.1 (doesn't contain Arg)
// Subcommand_1.1.1 (contains Arg)
//
fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&App<'help>> {
let mut vec = std::vec::Vec::new();
for idx in 0..self.subcommands.len() {
if self.subcommands[idx].args.args().any(|ar| ar.id == arg.id) {
vec.push(&self.subcommands[idx]);
vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg));
}
}
vec
}
// Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with.
//
// This behavior follows the propagation rules of global arguments.
// It is useful for finding conflicts for arguments declared as global.
//
// ### Panics
//
// If the given arg contains a conflict with an argument that is unknown to
// this `App`.
fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg<'help>> // FIXME: This could probably have been an iterator
{
arg.blacklist
.iter()
.map(|id| {
self.args
.args()
.chain(
self.get_subcommands_containing(arg)
.iter()
.flat_map(|x| x.args.args()),
)
.find(|arg| arg.id == *id)
.expect(
"App::get_arg_conflicts_with: \
The passed arg conflicts with an arg unknown to the app",
)
})
.collect()
}
/// Get a list of all arguments the given argument conflicts with.
///
/// If the provided argument is declared as global, the conflicts will be determined
/// based on the propagation rules of global arguments.
///
/// ### Panics
///
/// If the given arg contains a conflict with an argument that is unknown to
/// this `App`.
pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg<'help>> // FIXME: This could probably have been an iterator
{
if arg.global {
self.get_global_arg_conflicts_with(arg)
} else {
arg.blacklist
.iter()
.map(|id| {
self.args.args().find(|arg| arg.id == *id).expect(
"App::get_arg_conflicts_with: \
The passed arg conflicts with an arg unknown to the app",
)
})
.collect()
}
}
/// Returns `true` if the given [`AppSettings`] variant is currently set in
/// this `App` (checks both [local] and [global settings]).
///
/// [local]: App::setting()
/// [global settings]: App::global_setting()
#[inline]
pub fn is_set(&self, s: AppSettings) -> bool {
self.settings.is_set(s) || self.g_settings.is_set(s)
}
/// Returns `true` if this `App` has subcommands.
#[inline]
pub fn has_subcommands(&self) -> bool {
!self.subcommands.is_empty()
}
/// Find subcommand such that its name or one of aliases equals `name`.
///
/// This does not recurse through subcommands of subcommands.
#[inline]
pub fn find_subcommand<T>(&self, name: &T) -> Option<&App<'help>>
where
T: PartialEq<str> + ?Sized,
{
self.get_subcommands().find(|s| s.aliases_to(name))
}
}
impl<'help> App<'help> {
/// Creates a new instance of an `App` requiring a `name`.
///
/// It is common, but not required, to use binary name as the `name`. This
/// name will only be displayed to the user when they request to print
/// version or help and usage information.
///
/// An `App` represents a command line interface (CLI) which is made up of
/// all possible command line arguments and subcommands. "Subcommands" are
/// sub-CLIs with their own arguments, settings, and even subcommands
/// forming a sort of hierarchy.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("My Program")
/// # ;
/// ```
pub fn new<S: Into<String>>(name: S) -> Self {
let name = name.into();
App {
id: Id::from(&*name),
name,
disp_ord: 999,
..Default::default()
}
.arg(
Arg::new("help")
.long("help")
.about("Print help information")
.global(true)
.generated(),
)
.arg(
Arg::new("version")
.long("version")
.about("Print version information")
.global(true)
.generated(),
)
}
/// Sets a string of author(s) that will be displayed to the user when they
/// request the help message.
///
/// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to
/// automatically set your application's author(s) to the same thing as your
/// crate at compile time.
///
/// See the [`examples/`] directory for more information.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .author("Me, me@mymain.com")
/// # ;
/// ```
/// [`crate_authors!`]: ./macro.crate_authors!.html
/// [`examples/`]: https://github.com/clap-rs/clap/tree/master/examples
pub fn author<S: Into<&'help str>>(mut self, author: S) -> Self {
self.author = Some(author.into());
self
}
/// Overrides the runtime-determined name of the binary. This should only be
/// used when absolutely necessary, such as when the binary name for your
/// application is misleading, or perhaps *not* how the user should invoke
/// your program.
///
/// Normally, the binary name is used in help and error messages. `clap`
/// automatically determines the binary name at runtime, however by manually
/// setting the binary name, one can effectively override what will be
/// displayed in the help or error messages.
///
/// **Pro-tip:** When building things such as third party `cargo`
/// subcommands, this setting **should** be used!
///
/// **NOTE:** This *does not* change or set the name of the binary file on
/// disk. It only changes what clap thinks the name is for the purposes of
/// error or help messages.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("My Program")
/// .bin_name("my_binary")
/// # ;
/// ```
pub fn bin_name<S: Into<String>>(mut self, name: S) -> Self {
self.bin_name = Some(name.into());
self
}
/// Sets a string describing what the program does. This will be displayed
/// when the user requests the short format help message (`-h`).
///
/// `clap` can display two different help messages, a [long format] and a
/// [short format] depending on whether the user used `-h` (short) or
/// `--help` (long). This method sets the message during the short format
/// (`-h`) message. However, if no long format message is configured, this
/// message will be displayed for *both* the long format, or short format
/// help message.
///
/// **NOTE:** Only [`App::about`] (short format) is used in completion
/// script generation in order to be concise.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .about("Does really amazing things for great people")
/// # ;
/// ```
/// [long format]: App::long_about()
/// [short format]: App::about()
/// [`App::about`]: App::about()
pub fn about<S: Into<&'help str>>(mut self, about: S) -> Self {
self.about = Some(about.into());
self
}
/// Sets a long format string describing what the program does. This will be
/// displayed when the user requests the long format help message (`--help`).
///
/// ## Advanced
///
/// `clap` can display two different help messages, a [long format] and a
/// [short format] depending on whether the user used `-h` (short) or
/// `--help` (long). This method sets the message during the long format
/// (`--help`) message. However, if no short format message is configured,
/// this message will be displayed for *both* the long format, or short
/// format help message.
///
/// **NOTE:** Only [`App::about`] (short format) is used in completion
/// script generation in order to be concise.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .long_about(
/// "Does really amazing things to great people. Now let's talk a little
/// more in depth about how this subcommand really works. It may take about
/// a few lines of text, but that's ok!")
/// # ;
/// ```
/// [long format]: App::long_about()
/// [short format]: App::about()
/// [`App::about`]: App::about()
pub fn long_about<S: Into<&'help str>>(mut self, about: S) -> Self {
self.long_about = Some(about.into());
self
}
/// (Re)Sets the program's name. This will be displayed when displaying help
/// or version messages.
///
/// **Pro-tip:** This function is particularly useful when configuring a
/// program via `App::from(yaml)` in conjunction with the [`crate_name!`]
/// macro to derive the program's name from its `Cargo.toml`.
///
/// # Examples
///
/// ```ignore
/// # use clap::{App, load_yaml};
/// let yaml = load_yaml!("app.yaml");
/// let app = App::from(yaml)
/// .name(crate_name!());
///
/// // continued logic goes here, such as `app.get_matches()` etc.
/// ```
///
pub fn name<S: Into<String>>(mut self, name: S) -> Self {
self.name = name.into();
self
}
/// Adds additional help information to be displayed at the end of the
/// auto-generated help. This is often used to describe how to use the
/// arguments, caveats to be noted, or license and contact information.
///
/// **NOTE:** If only `after_long_help` is provided, and not [`App::after_help`] but the user requests
/// `-h` clap will still display the contents of `after_help` appropriately.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .after_help("Does really amazing things for great people... but be careful with -R!")
/// # ;
/// ```
///
/// [`App::after_help`]: App::after_help()
pub fn after_help<S: Into<&'help str>>(mut self, help: S) -> Self {
self.after_help = Some(help.into());
self
}
/// Adds additional help information to be displayed in addition to auto-generated help. This
/// information is displayed **after** the auto-generated help information and is meant to be
/// more verbose than `after_help`. This is often used to describe how to use the arguments, or
/// caveats to be noted in man pages.
///
/// **NOTE:** If only `after_help` is provided, and not [`App::after_long_help`] but the user
/// requests `--help`, clap will still display the contents of `after_help` appropriately.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .after_long_help("Does really amazing things to great people... but be careful with -R, \
/// like, for real, be careful with this!")
/// # ;
/// ```
/// [`App::after_long_help`]: App::after_long_help()
pub fn after_long_help<S: Into<&'help str>>(mut self, help: S) -> Self {
self.after_long_help = Some(help.into());
self
}
/// Adds additional help information to be displayed prior to the
/// auto-generated help. This is often used for header, copyright, or
/// license information.
///
/// **NOTE:** If only `before_long_help` is provided, and not [`App::before_help`] but the user
/// requests `-h` clap will still display the contents of `before_long_help` appropriately.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .before_help("Some info I'd like to appear before the help info")
/// # ;
/// ```
/// [`App::before_help`]: App::before_help()
pub fn before_help<S: Into<&'help str>>(mut self, help: S) -> Self {
self.before_help = Some(help.into());
self
}
/// Adds additional help information to be displayed prior to the
/// auto-generated help. This is often used for header, copyright, or
/// license information.
///
/// **NOTE:** If only `before_help` is provided, and not [`App::before_long_help`] but the user
/// requests `--help`, clap will still display the contents of `before_help` appropriately.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .before_long_help("Some verbose and long info I'd like to appear before the help info")
/// # ;
/// ```
/// [`App::before_long_help`]: App::before_long_help()
pub fn before_long_help<S: Into<&'help str>>(mut self, help: S) -> Self {
self.before_long_help = Some(help.into());
self
}
/// Allows the subcommand to be used as if it were an [`Arg::short`].
///
/// Sets the short version of the subcommand flag without the preceding `-`.
///
/// # Examples
///
/// ```
/// # use clap::{App, Arg};
/// let matches = App::new("pacman")
/// .subcommand(
/// App::new("sync").short_flag('S').arg(
/// Arg::new("search")
/// .short('s')
/// .long("search")
/// .about("search remote repositories for matching strings"),
/// ),
/// )
/// .get_matches_from(vec!["pacman", "-Ss"]);
///
/// assert_eq!(matches.subcommand_name().unwrap(), "sync");
/// let sync_matches = matches.subcommand_matches("sync").unwrap();
/// assert!(sync_matches.is_present("search"));
/// ```
/// [`Arg::short`]: Arg::short()
pub fn short_flag(mut self, short: char) -> Self {
self.short_flag = Some(short);
self
}
/// Allows the subcommand to be used as if it were an [`Arg::long`].
///
/// Sets the long version of the subcommand flag without the preceding `--`.
///
/// **NOTE:** Any leading `-` characters will be stripped.
///
/// # Examples
///
/// To set `long_flag` use a word containing valid UTF-8 codepoints. If you supply a double leading
/// `--` such as `--sync` they will be stripped. Hyphens in the middle of the word; however,
/// will *not* be stripped (i.e. `sync-file` is allowed).
///
/// ```
/// # use clap::{App, Arg};
/// let matches = App::new("pacman")
/// .subcommand(
/// App::new("sync").long_flag("sync").arg(
/// Arg::new("search")
/// .short('s')
/// .long("search")
/// .about("search remote repositories for matching strings"),
/// ),
/// )
/// .get_matches_from(vec!["pacman", "--sync", "--search"]);
///
/// assert_eq!(matches.subcommand_name().unwrap(), "sync");
/// let sync_matches = matches.subcommand_matches("sync").unwrap();
/// assert!(sync_matches.is_present("search"));
/// ```
///
/// [`Arg::long`]: Arg::long()
pub fn long_flag(mut self, long: &'help str) -> Self {
self.long_flag = Some(long.trim_start_matches(|c| c == '-'));
self
}
/// Sets a string of the version number to be displayed when displaying the
/// short format version message (`-V`) or the help message.
///
/// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to
/// automatically set your application's version to the same thing as your
/// crate at compile time. See the [`examples/`] directory for more
/// information.
///
/// `clap` can display two different version messages, a [long format] and a
/// [short format] depending on whether the user used `-V` (short) or
/// `--version` (long). This method sets the message during the short format
/// (`-V`). However, if no long format message is configured, this
/// message will be displayed for *both* the long format, or short format
/// version message.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .version("v0.1.24")
/// # ;
/// ```
/// [`crate_version!`]: ./macro.crate_version!.html
/// [`examples/`]: https://github.com/clap-rs/clap/tree/master/examples
/// [`App::long_version`]: App::long_version()
pub fn version<S: Into<&'help str>>(mut self, ver: S) -> Self {
self.version = Some(ver.into());
self
}
/// Sets a string of the version number to be displayed when the user
/// requests the long format version message (`--version`) or the help
/// message.
///
/// This is often used to display things such as commit ID, or compile time
/// configured options.
///
/// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to
/// automatically set your application's version to the same thing as your
/// crate at compile time. See the [`examples/`] directory for more
/// information.
///
/// `clap` can display two different version messages, a [long format] and a
/// [short format] depending on whether the user used `-V` (short) or
/// `--version` (long). This method sets the message during the long format
/// (`--version`). However, if no short format message is configured, this
/// message will be displayed for *both* the long format, or short format
/// version message.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .long_version(
/// "v0.1.24
/// commit: abcdef89726d
/// revision: 123
/// release: 2
/// binary: myprog")
/// # ;
/// ```
/// [`crate_version!`]: ./macro.crate_version!.html
/// [`examples/`]: https://github.com/kbknapp/clap-rs/tree/master/examples
/// [`App::version`]: App::version()
pub fn long_version<S: Into<&'help str>>(mut self, ver: S) -> Self {
self.long_version = Some(ver.into());
self
}
/// Sets a string of the license to be displayed when displaying help information.
///
/// **Pro-tip:** Use `clap`s convenience macro [`crate_license!`] to automatically set your
/// application's license to the same thing as your crate at compile time. See the
/// [`examples/`] directory for more information
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg};
/// App::new("myprog")
/// .license("MIT OR Apache-2.0")
/// # ;
/// ```
/// [`crate_license!`]: ./macro.crate_license!.html
/// [`examples/`]: https://github.com/clap-rs/clap/tree/master/examples
pub fn license<S: Into<&'help str>>(mut self, license: S) -> Self {
self.license = Some(license.into());
self
}
/// Overrides the `clap` generated usage string.
///
/// This will be displayed to the user when errors are found in argument parsing.
///
/// **CAUTION:** Using this setting disables `clap`s "context-aware" usage
/// strings. After this setting is set, this will be *the only* usage string
/// displayed to the user!
///
/// **NOTE:** This will not replace the entire help message, *only* the portion
/// showing the usage.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg};
/// App::new("myprog")
/// .override_usage("myapp [-clDas] <some_file>")
/// # ;
/// ```
/// [`ArgMatches::usage`]: ArgMatches::usage()
pub fn override_usage<S: Into<&'help str>>(mut self, usage: S) -> Self {
self.usage_str = Some(usage.into());
self
}
/// Overrides the `clap` generated help message. This should only be used
/// when the auto-generated message does not suffice.
///
/// This will be displayed to the user when they use `--help` or `-h`.
///
/// **NOTE:** This replaces the **entire** help message, so nothing will be
/// auto-generated.
///
/// **NOTE:** This **only** replaces the help message for the current
/// command, meaning if you are using subcommands, those help messages will
/// still be auto-generated unless you specify a [`App::override_help`] for
/// them as well.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg};
/// App::new("myapp")
/// .override_help("myapp v1.0\n\
/// Does awesome things\n\
/// (C) me@mail.com\n\n\
///
/// USAGE: myapp <opts> <comamnd>\n\n\
///
/// Options:\n\
/// -h, --help Display this message\n\
/// -V, --version Display version info\n\
/// -s <stuff> Do something with stuff\n\
/// -v Be verbose\n\n\
///
/// Commmands:\n\
/// help Print this message\n\
/// work Do some work")
/// # ;
/// ```
pub fn override_help<S: Into<&'help str>>(mut self, help: S) -> Self {
self.help_str = Some(help.into());
self
}
/// Sets the help template to be used, overriding the default format.
///
/// **NOTE:** The template system is by design very simple. Therefore, the
/// tags have to be written in the lowercase and without spacing.
///
/// Tags are given inside curly brackets.
///
/// Valid tags are:
///
/// * `{bin}` - Binary name.
/// * `{version}` - Version number.
/// * `{author}` - Author information.
/// * `{author-with-newline}` - Author followed by `\n`.
/// * `{author-section}` - Author preceded and followed by `\n`.
/// * `{about}` - General description (from [`App::about`] or
/// [`App::long_about`]).
/// * `{about-with-newline}` - About followed by `\n`.
/// * `{about-section}` - About preceded and followed by '\n'.
/// * `{usage-heading}` - Automatically generated usage heading.
/// * `{usage}` - Automatically generated or given usage string.
/// * `{all-args}` - Help for all arguments (options, flags, positional
/// arguments, and subcommands) including titles.
/// * `{unified}` - Unified help for options and flags. Note, you must *also*
/// set [`AppSettings::UnifiedHelpMessage`] to fully merge both
/// options and flags, otherwise the ordering is "best effort".
/// * `{flags}` - Help for flags.
/// * `{options}` - Help for options.
/// * `{positionals}` - Help for positional arguments.
/// * `{subcommands}` - Help for subcommands.
/// * `{after-help}` - Help from [`App::after_help`] or [`App::after_long_help`].
/// * `{before-help}` - Help from [`App::before_help`] or [`App::before_long_help`].
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .version("1.0")
/// .help_template("{bin} ({version}) - {usage}")
/// # ;
/// ```
/// [`App::about`]: App::about()
/// [`App::long_about`]: App::long_about()
/// [`App::after_help`]: App::after_help()
/// [`App::after_long_help`]: App::after_long_help()
/// [`App::before_help`]: App::before_help()
/// [`App::before_long_help`]: App::before_long_help()
pub fn help_template<S: Into<&'help str>>(mut self, s: S) -> Self {
self.template = Some(s.into());
self
}
/// Enables a single settings for the current (this `App` instance) command or subcommand.
///
/// See [`AppSettings`] for a full list of possibilities and examples.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, AppSettings};
/// App::new("myprog")
/// .setting(AppSettings::SubcommandRequired)
/// .setting(AppSettings::WaitOnError)
/// # ;
/// ```
///
/// ```no_run
/// # use clap::{App, AppSettings};
/// App::new("myprog")
/// .setting(AppSettings::SubcommandRequired | AppSettings::WaitOnError)
/// # ;
/// ```
#[inline]
pub fn setting<F>(mut self, setting: F) -> Self
where
F: Into<AppFlags>,
{
self.settings.insert(setting.into());
self
}
/// Disables a single setting for the current (this `App` instance) command or subcommand.
///
/// See [`AppSettings`] for a full list of possibilities and examples.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, AppSettings};
/// App::new("myprog")
/// .unset_setting(AppSettings::SubcommandRequired)
/// .unset_setting(AppSettings::WaitOnError)
/// # ;
/// ```
///
/// ```no_run
/// # use clap::{App, AppSettings};
/// App::new("myprog")
/// .unset_setting(AppSettings::SubcommandRequired | AppSettings::WaitOnError)
/// # ;
/// ```
#[inline]
pub fn unset_setting<F>(mut self, setting: F) -> Self
where
F: Into<AppFlags>,
{
self.settings.remove(setting.into());
self
}
/// Enables a single setting that is propagated **down** through all child
/// subcommands.
///
/// See [`AppSettings`] for a full list of possibilities and examples.
///
/// **NOTE**: The setting is *only* propagated *down* and not up through parent commands.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, AppSettings};
/// App::new("myprog")
/// .global_setting(AppSettings::SubcommandRequired)
/// # ;
/// ```
#[inline]
pub fn global_setting(mut self, setting: AppSettings) -> Self {
self.settings.set(setting);
self.g_settings.set(setting);
self
}
/// Disables a global setting, and stops propagating down to child
/// subcommands.
///
/// See [`AppSettings`] for a full list of possibilities and examples.
///
/// **NOTE:** The setting being unset will be unset from both local and
/// [global] settings.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, AppSettings};
/// App::new("myprog")
/// .unset_global_setting(AppSettings::ColorAuto)
/// # ;
/// ```
/// [global]: App::global_setting()
#[inline]
pub fn unset_global_setting(mut self, setting: AppSettings) -> Self {
self.settings.unset(setting);
self.g_settings.unset(setting);
self
}
/// Sets the terminal width at which to wrap help messages. Defaults to
/// `100`. Using `0` will ignore terminal widths and use source formatting.