-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
command.rs
5164 lines (4826 loc) · 178 KB
/
command.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
#![allow(deprecated)]
// Std
use std::collections::HashMap;
use std::env;
use std::ffi::OsString;
use std::fmt;
use std::io;
use std::ops::Index;
use std::path::Path;
// Third Party
#[cfg(feature = "yaml")]
use yaml_rust::Yaml;
// Internal
use crate::builder::app_settings::{AppFlags, AppSettings};
use crate::builder::arg_settings::ArgSettings;
use crate::builder::{arg::ArgProvider, Arg, ArgGroup, ArgPredicate};
use crate::error::ErrorKind;
use crate::error::Result as ClapResult;
use crate::mkeymap::MKeyMap;
use crate::output::fmt::Stream;
use crate::output::{fmt::Colorizer, Help, HelpWriter, Usage};
use crate::parser::{ArgMatcher, ArgMatches, Parser};
use crate::util::ChildGraph;
use crate::util::{color::ColorChoice, Id, Key};
use crate::PossibleValue;
use crate::{Error, INTERNAL_ERROR_MSG};
#[cfg(debug_assertions)]
use crate::builder::debug_asserts::assert_app;
/// Build a command-line interface.
///
/// This includes defining arguments, subcommands, parser behavior, and help output.
/// Once all configuration is complete,
/// the [`Command::get_matches`] family of methods starts the runtime-parsing
/// process. These methods then return information about the user supplied
/// arguments (or lack thereof).
///
/// When deriving a [`Parser`][crate::Parser], you can use
/// [`CommandFactory::command`][crate::CommandFactory::command] to access the
/// `Command`.
///
/// - [Basic API][crate::App#basic-api]
/// - [Application-wide Settings][crate::App#application-wide-settings]
/// - [Command-specific Settings][crate::App#command-specific-settings]
/// - [Subcommand-specific Settings][crate::App#subcommand-specific-settings]
/// - [Reflection][crate::App#reflection]
///
/// # Examples
///
/// ```no_run
/// # use clap::{Command, Arg};
/// let m = Command::new("My Program")
/// .author("Me, [email protected]")
/// .version("1.0.2")
/// .about("Explains in brief what the program does")
/// .arg(
/// Arg::new("in_file")
/// )
/// .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`]: Command::get_matches()
pub type Command<'help> = App<'help>;
/// Deprecated, replaced with [`Command`]
#[cfg_attr(
feature = "deprecated",
deprecated(since = "3.1.0", note = "Replaced with `Command`")
)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct App<'help> {
id: Id,
name: String,
long_flag: Option<&'help str>,
short_flag: Option<char>,
display_name: Option<String>,
bin_name: Option<String>,
author: Option<&'help str>,
version: Option<&'help str>,
long_version: Option<&'help str>,
about: Option<&'help str>,
long_about: Option<&'help str>,
before_help: Option<&'help str>,
before_long_help: Option<&'help str>,
after_help: Option<&'help str>,
after_long_help: Option<&'help str>,
aliases: Vec<(&'help str, bool)>, // (name, visible)
short_flag_aliases: Vec<(char, bool)>, // (name, visible)
long_flag_aliases: Vec<(&'help str, bool)>, // (name, visible)
usage_str: Option<&'help str>,
usage_name: Option<String>,
help_str: Option<&'help str>,
disp_ord: Option<usize>,
term_w: Option<usize>,
max_w: Option<usize>,
template: Option<&'help str>,
settings: AppFlags,
g_settings: AppFlags,
args: MKeyMap<'help>,
subcommands: Vec<App<'help>>,
replacers: HashMap<&'help str, &'help [&'help str]>,
groups: Vec<ArgGroup<'help>>,
current_help_heading: Option<&'help str>,
current_disp_ord: Option<usize>,
subcommand_value_name: Option<&'help str>,
subcommand_heading: Option<&'help str>,
}
/// # Basic API
impl<'help> App<'help> {
/// Creates a new instance of an `Command`.
///
/// 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.
///
/// See also [`command!`](crate::command!) and [`crate_name!`](crate::crate_name!).
///
/// # Examples
///
/// ```no_run
/// # use clap::Command;
/// Command::new("My Program")
/// # ;
/// ```
pub fn new<S: Into<String>>(name: S) -> Self {
/// The actual implementation of `new`, non-generic to save code size.
///
/// If we don't do this rustc will unnecessarily generate multiple versions
/// of this code.
fn new_inner<'help>(name: String) -> App<'help> {
App {
id: Id::from(&*name),
name,
..Default::default()
}
.arg(
Arg::new("help")
.long("help")
.help("Print help information")
.global(true)
.generated(),
)
.arg(
Arg::new("version")
.long("version")
.help("Print version information")
.global(true)
.generated(),
)
}
new_inner(name.into())
}
/// Adds an [argument] to the list of valid possibilities.
///
/// # Examples
///
/// ```no_run
/// # use clap::{Command, arg, Arg};
/// Command::new("myprog")
/// // Adding a single "flag" argument with a short and help text, using Arg::new()
/// .arg(
/// Arg::new("debug")
/// .short('d')
/// .help("turns on debugging mode")
/// )
/// // Adding a single "option" argument with a short, a long, and help text using the less
/// // verbose Arg::from()
/// .arg(
/// arg!(-c --config <CONFIG> "Optionally sets a config file to use")
/// )
/// # ;
/// ```
/// [argument]: Arg
#[must_use]
pub fn arg<A: Into<Arg<'help>>>(mut self, a: A) -> Self {
let mut arg = a.into();
if let Some(current_disp_ord) = self.current_disp_ord.as_mut() {
if !arg.is_positional() && arg.provider != ArgProvider::Generated {
let current = *current_disp_ord;
arg.disp_ord.set_implicit(current);
*current_disp_ord = current + 1;
}
}
arg.help_heading.get_or_insert(self.current_help_heading);
self.args.push(arg);
self
}
/// Adds multiple [arguments] to the list of valid possibilities.
///
/// # Examples
///
/// ```no_run
/// # use clap::{Command, arg, Arg};
/// Command::new("myprog")
/// .args(&[
/// arg!("[debug] -d 'turns on debugging info'"),
/// Arg::new("input").help("the input file to use")
/// ])
/// # ;
/// ```
/// [arguments]: Arg
#[must_use]
pub fn args<I, T>(mut self, args: I) -> Self
where
I: IntoIterator<Item = T>,
T: Into<Arg<'help>>,
{
let args = args.into_iter();
let (lower, _) = args.size_hint();
self.args.reserve(lower);
for arg in args {
self = self.arg(arg);
}
self
}
/// Allows one to mutate an [`Arg`] after it's been added to a [`Command`].
///
/// This can be useful for modifying the auto-generated help or version arguments.
///
/// # Examples
///
/// ```rust
/// # use clap::{Command, Arg};
///
/// let mut cmd = Command::new("foo")
/// .arg(Arg::new("bar")
/// .short('b'))
/// .mut_arg("bar", |a| a.short('B'));
///
/// let res = cmd.try_get_matches_from_mut(vec!["foo", "-b"]);
///
/// // Since we changed `bar`'s short to "B" this should err as there
/// // is no `-b` anymore, only `-B`
///
/// assert!(res.is_err());
///
/// let res = cmd.try_get_matches_from_mut(vec!["foo", "-B"]);
/// assert!(res.is_ok());
/// ```
#[must_use]
pub fn mut_arg<T, F>(mut self, arg_id: T, f: F) -> Self
where
F: FnOnce(Arg<'help>) -> Arg<'help>,
T: Key + Into<&'help str>,
{
let arg_id: &str = arg_id.into();
let id = Id::from(arg_id);
let mut a = self.args.remove_by_name(&id).unwrap_or_else(|| Arg {
id,
name: arg_id,
..Arg::default()
});
if a.provider == ArgProvider::Generated {
a.provider = ArgProvider::GeneratedMutated;
}
self.args.push(f(a));
self
}
/// Allows one to mutate a [`Command`] after it's been added as a subcommand.
///
/// This can be useful for modifying auto-generated arguments of nested subcommands with
/// [`Command::mut_arg`].
///
/// # Examples
///
/// ```rust
/// # use clap::Command;
///
/// let mut cmd = Command::new("foo")
/// .subcommand(Command::new("bar"))
/// .mut_subcommand("bar", |subcmd| subcmd.disable_help_flag(true));
///
/// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar", "--help"]);
///
/// // Since we disabled the help flag on the "bar" subcommand, this should err.
///
/// assert!(res.is_err());
///
/// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar"]);
/// assert!(res.is_ok());
/// ```
#[must_use]
pub fn mut_subcommand<'a, T, F>(mut self, subcmd_id: T, f: F) -> Self
where
F: FnOnce(App<'help>) -> App<'help>,
T: Into<&'a str>,
{
let subcmd_id: &str = subcmd_id.into();
let id = Id::from(subcmd_id);
let pos = self.subcommands.iter().position(|s| s.id == id);
let subcmd = if let Some(idx) = pos {
self.subcommands.remove(idx)
} else {
App::new(subcmd_id)
};
self.subcommands.push(f(subcmd));
self
}
/// Adds an [`ArgGroup`] to the application.
///
/// [`ArgGroup`]s are a family of related arguments.
/// By placing them in a logical group, you can build easier requirement and exclusion rules.
///
/// Example use cases:
/// - Make an entire [`ArgGroup`] required, meaning that one (and *only*
/// one) argument from that group must be present at runtime.
/// - Name an [`ArgGroup`] as a conflict to another argument.
/// Meaning any of the arguments that belong to that group will cause a failure if present with
/// the conflicting argument.
/// - Ensure exclusion between arguments.
/// - Extract a value from a group instead of determining exactly which argument was used.
///
/// # Examples
///
/// The following example demonstrates using an [`ArgGroup`] to ensure that one, and only one,
/// of the arguments from the specified group is present at runtime.
///
/// ```no_run
/// # use clap::{Command, arg, ArgGroup};
/// Command::new("cmd")
/// .arg(arg!("--set-ver [ver] 'set the version manually'"))
/// .arg(arg!("--major 'auto increase major'"))
/// .arg(arg!("--minor 'auto increase minor'"))
/// .arg(arg!("--patch 'auto increase patch'"))
/// .group(ArgGroup::new("vers")
/// .args(&["set-ver", "major", "minor","patch"])
/// .required(true))
/// # ;
/// ```
#[inline]
#[must_use]
pub fn group<G: Into<ArgGroup<'help>>>(mut self, group: G) -> Self {
self.groups.push(group.into());
self
}
/// Adds multiple [`ArgGroup`]s to the [`Command`] at once.
///
/// # Examples
///
/// ```no_run
/// # use clap::{Command, arg, ArgGroup};
/// Command::new("cmd")
/// .arg(arg!("--set-ver [ver] 'set the version manually'"))
/// .arg(arg!("--major 'auto increase major'"))
/// .arg(arg!("--minor 'auto increase minor'"))
/// .arg(arg!("--patch 'auto increase patch'"))
/// .arg(arg!("-c [FILE] 'a config file'"))
/// .arg(arg!("-i [IFACE] 'an interface'"))
/// .groups(&[
/// ArgGroup::new("vers")
/// .args(&["set-ver", "major", "minor","patch"])
/// .required(true),
/// ArgGroup::new("input")
/// .args(&["c", "i"])
/// ])
/// # ;
/// ```
#[must_use]
pub fn groups<I, T>(mut self, groups: I) -> Self
where
I: IntoIterator<Item = T>,
T: Into<ArgGroup<'help>>,
{
for g in groups.into_iter() {
self = self.group(g.into());
}
self
}
/// Adds a subcommand to the list of valid possibilities.
///
/// Subcommands are effectively sub-[`Command`]s, because they can contain their own arguments,
/// subcommands, version, usage, etc. They also function just like [`Command`]s, in that they get
/// their own auto generated help, version, and usage.
///
/// A subcommand's [`Command::name`] will be used for:
/// - The argument the user passes in
/// - Programmatically looking up the subcommand
///
/// # Examples
///
/// ```no_run
/// # use clap::{Command, arg};
/// Command::new("myprog")
/// .subcommand(Command::new("config")
/// .about("Controls configuration features")
/// .arg(arg!("<config> 'Required configuration file to use'")))
/// # ;
/// ```
#[inline]
#[must_use]
pub fn subcommand<S: Into<App<'help>>>(mut self, subcmd: S) -> Self {
self.subcommands.push(subcmd.into());
self
}
/// Adds multiple subcommands to the list of valid possibilities.
///
/// # Examples
///
/// ```rust
/// # use clap::{Command, Arg, };
/// # Command::new("myprog")
/// .subcommands( vec![
/// Command::new("config").about("Controls configuration functionality")
/// .arg(Arg::new("config_file")),
/// Command::new("debug").about("Controls debug functionality")])
/// # ;
/// ```
/// [`IntoIterator`]: std::iter::IntoIterator
#[must_use]
pub fn subcommands<I, T>(mut self, subcmds: I) -> Self
where
I: IntoIterator<Item = T>,
T: Into<App<'help>>,
{
for subcmd in subcmds.into_iter() {
self.subcommands.push(subcmd.into());
}
self
}
/// Catch problems earlier in the development cycle.
///
/// Most error states are handled as asserts under the assumption they are programming mistake
/// and not something to handle at runtime. Rather than relying on tests (manual or automated)
/// that exhaustively test your CLI to ensure the asserts are evaluated, this will run those
/// asserts in a way convenient for running as a test.
///
/// **Note::** This will not help with asserts in [`ArgMatches`], those will need exhaustive
/// testing of your CLI.
///
/// # Examples
///
/// ```rust
/// # use clap::{Command, Arg, ArgAction};
/// fn cmd() -> Command<'static> {
/// Command::new("foo")
/// .arg(
/// Arg::new("bar").short('b').action(ArgAction::SetTrue)
/// )
/// }
///
/// #[test]
/// fn verify_app() {
/// cmd().debug_assert();
/// }
///
/// fn main() {
/// let m = cmd().get_matches_from(vec!["foo", "-b"]);
/// println!("{}", *m.get_one::<bool>("bar").expect("defaulted by clap"));
/// }
/// ```
pub fn debug_assert(mut self) {
self._build_all();
}
/// Custom error message for post-parsing validation
///
/// # Examples
///
/// ```rust
/// # use clap::{Command, ErrorKind};
/// let mut cmd = Command::new("myprog");
/// let err = cmd.error(ErrorKind::InvalidValue, "Some failure case");
/// ```
pub fn error(&mut self, kind: ErrorKind, message: impl std::fmt::Display) -> Error {
Error::raw(kind, message).format(self)
}
/// Parse [`env::args_os`], exiting on failure.
///
/// # Panics
///
/// If contradictory arguments or settings exist.
///
/// # Examples
///
/// ```no_run
/// # use clap::{Command, Arg};
/// let matches = Command::new("myprog")
/// // Args and options go here...
/// .get_matches();
/// ```
/// [`env::args_os`]: std::env::args_os()
/// [`App::try_get_matches_from_mut`]: Command::try_get_matches_from_mut()
#[inline]
pub fn get_matches(self) -> ArgMatches {
self.get_matches_from(&mut env::args_os())
}
/// Parse [`env::args_os`], exiting on failure.
///
/// Like [`App::get_matches`] but doesn't consume the `Command`.
///
/// # Panics
///
/// If contradictory arguments or settings exist.
///
/// # Examples
///
/// ```no_run
/// # use clap::{Command, Arg};
/// let mut cmd = Command::new("myprog")
/// // Args and options go here...
/// ;
/// let matches = cmd.get_matches_mut();
/// ```
/// [`env::args_os`]: std::env::args_os()
/// [`App::get_matches`]: Command::get_matches()
pub fn get_matches_mut(&mut self) -> ArgMatches {
self.try_get_matches_from_mut(&mut env::args_os())
.unwrap_or_else(|e| e.exit())
}
/// Parse [`env::args_os`], returning a [`clap::Result`] on failure.
///
/// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
/// used. It will return a [`clap::Error`], where the [`kind`] is a
/// [`ErrorKind::DisplayHelp`] or [`ErrorKind::DisplayVersion`] respectively. You must call
/// [`Error::exit`] or perform a [`std::process::exit`].
///
/// # Panics
///
/// If contradictory arguments or settings exist.
///
/// # Examples
///
/// ```no_run
/// # use clap::{Command, Arg};
/// let matches = Command::new("myprog")
/// // Args and options go here...
/// .try_get_matches()
/// .unwrap_or_else(|e| e.exit());
/// ```
/// [`env::args_os`]: std::env::args_os()
/// [`Error::exit`]: crate::Error::exit()
/// [`std::process::exit`]: std::process::exit()
/// [`clap::Result`]: Result
/// [`clap::Error`]: crate::Error
/// [`kind`]: crate::Error
/// [`ErrorKind::DisplayHelp`]: crate::ErrorKind::DisplayHelp
/// [`ErrorKind::DisplayVersion`]: crate::ErrorKind::DisplayVersion
#[inline]
pub fn try_get_matches(self) -> ClapResult<ArgMatches> {
// Start the parsing
self.try_get_matches_from(&mut env::args_os())
}
/// Parse the specified arguments, exiting on failure.
///
/// **NOTE:** The first argument will be parsed as the binary name unless
/// [`Command::no_binary_name`] is used.
///
/// # Panics
///
/// If contradictory arguments or settings exist.
///
/// # Examples
///
/// ```no_run
/// # use clap::{Command, Arg};
/// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
///
/// let matches = Command::new("myprog")
/// // Args and options go here...
/// .get_matches_from(arg_vec);
/// ```
/// [`App::get_matches`]: Command::get_matches()
/// [`clap::Result`]: Result
/// [`Vec`]: std::vec::Vec
pub fn get_matches_from<I, T>(mut self, itr: I) -> ArgMatches
where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
{
self.try_get_matches_from_mut(itr).unwrap_or_else(|e| {
drop(self);
e.exit()
})
}
/// Parse the specified arguments, returning a [`clap::Result`] on failure.
///
/// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
/// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`]
/// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or
/// perform a [`std::process::exit`] yourself.
///
/// **NOTE:** The first argument will be parsed as the binary name unless
/// [`Command::no_binary_name`] is used.
///
/// # Panics
///
/// If contradictory arguments or settings exist.
///
/// # Examples
///
/// ```no_run
/// # use clap::{Command, Arg};
/// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
///
/// let matches = Command::new("myprog")
/// // Args and options go here...
/// .try_get_matches_from(arg_vec)
/// .unwrap_or_else(|e| e.exit());
/// ```
/// [`App::get_matches_from`]: Command::get_matches_from()
/// [`App::try_get_matches`]: Command::try_get_matches()
/// [`Error::exit`]: crate::Error::exit()
/// [`std::process::exit`]: std::process::exit()
/// [`clap::Error`]: crate::Error
/// [`Error::exit`]: crate::Error::exit()
/// [`kind`]: crate::Error
/// [`ErrorKind::DisplayHelp`]: crate::ErrorKind::DisplayHelp
/// [`ErrorKind::DisplayVersion`]: crate::ErrorKind::DisplayVersion
/// [`clap::Result`]: Result
pub fn try_get_matches_from<I, T>(mut self, itr: I) -> ClapResult<ArgMatches>
where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
{
self.try_get_matches_from_mut(itr)
}
/// Parse the specified arguments, returning a [`clap::Result`] on failure.
///
/// Like [`App::try_get_matches_from`] but doesn't consume the `Command`.
///
/// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
/// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`]
/// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or
/// perform a [`std::process::exit`] yourself.
///
/// **NOTE:** The first argument will be parsed as the binary name unless
/// [`Command::no_binary_name`] is used.
///
/// # Panics
///
/// If contradictory arguments or settings exist.
///
/// # Examples
///
/// ```no_run
/// # use clap::{Command, Arg};
/// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
///
/// let mut cmd = Command::new("myprog");
/// // Args and options go here...
/// let matches = cmd.try_get_matches_from_mut(arg_vec)
/// .unwrap_or_else(|e| e.exit());
/// ```
/// [`App::try_get_matches_from`]: Command::try_get_matches_from()
/// [`clap::Result`]: Result
/// [`clap::Error`]: crate::Error
/// [`kind`]: crate::Error
pub fn try_get_matches_from_mut<I, T>(&mut self, itr: I) -> ClapResult<ArgMatches>
where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
{
let mut raw_args = clap_lex::RawArgs::new(itr.into_iter());
let mut cursor = raw_args.cursor();
if self.settings.is_set(AppSettings::Multicall) {
if let Some(argv0) = raw_args.next_os(&mut cursor) {
let argv0 = Path::new(&argv0);
if let Some(command) = argv0.file_stem().and_then(|f| f.to_str()) {
// Stop borrowing command so we can get another mut ref to it.
let command = command.to_owned();
debug!(
"Command::try_get_matches_from_mut: Parsed command {} from argv",
command
);
debug!("Command::try_get_matches_from_mut: Reinserting command into arguments so subcommand parser matches it");
raw_args.insert(&cursor, &[&command]);
debug!("Command::try_get_matches_from_mut: Clearing name and bin_name so that displayed command name starts with applet name");
self.name.clear();
self.bin_name = None;
return self._do_parse(&mut raw_args, cursor);
}
}
};
// Get the name of the program (argument 1 of env::args()) and determine the
// actual file
// that was used to execute the program. This is because a program called
// ./target/release/my_prog -a
// will have two arguments, './target/release/my_prog', '-a' but we don't want
// to display
// the full path when displaying help messages and such
if !self.settings.is_set(AppSettings::NoBinaryName) {
if let Some(name) = raw_args.next_os(&mut cursor) {
let p = Path::new(name);
if let Some(f) = p.file_name() {
if let Some(s) = f.to_str() {
if self.bin_name.is_none() {
self.bin_name = Some(s.to_owned());
}
}
}
}
}
self._do_parse(&mut raw_args, cursor)
}
/// Prints the short help message (`-h`) to [`io::stdout()`].
///
/// See also [`Command::print_long_help`].
///
/// # Examples
///
/// ```rust
/// # use clap::Command;
/// let mut cmd = Command::new("myprog");
/// cmd.print_help();
/// ```
/// [`io::stdout()`]: std::io::stdout()
pub fn print_help(&mut self) -> io::Result<()> {
self._build_self();
let color = self.get_color();
let mut c = Colorizer::new(Stream::Stdout, color);
let usage = Usage::new(self);
Help::new(HelpWriter::Buffer(&mut c), self, &usage, false).write_help()?;
c.print()
}
/// Prints the long help message (`--help`) to [`io::stdout()`].
///
/// See also [`Command::print_help`].
///
/// # Examples
///
/// ```rust
/// # use clap::Command;
/// let mut cmd = Command::new("myprog");
/// cmd.print_long_help();
/// ```
/// [`io::stdout()`]: std::io::stdout()
/// [`BufWriter`]: std::io::BufWriter
/// [`-h` (short)]: Arg::help()
/// [`--help` (long)]: Arg::long_help()
pub fn print_long_help(&mut self) -> io::Result<()> {
self._build_self();
let color = self.get_color();
let mut c = Colorizer::new(Stream::Stdout, color);
let usage = Usage::new(self);
Help::new(HelpWriter::Buffer(&mut c), self, &usage, true).write_help()?;
c.print()
}
/// Writes the short help message (`-h`) to a [`io::Write`] object.
///
/// See also [`Command::write_long_help`].
///
/// # Examples
///
/// ```rust
/// # use clap::Command;
/// use std::io;
/// let mut cmd = Command::new("myprog");
/// let mut out = io::stdout();
/// cmd.write_help(&mut out).expect("failed to write to stdout");
/// ```
/// [`io::Write`]: std::io::Write
/// [`-h` (short)]: Arg::help()
/// [`--help` (long)]: Arg::long_help()
pub fn write_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> {
self._build_self();
let usage = Usage::new(self);
Help::new(HelpWriter::Normal(w), self, &usage, false).write_help()?;
w.flush()
}
/// Writes the long help message (`--help`) to a [`io::Write`] object.
///
/// See also [`Command::write_help`].
///
/// # Examples
///
/// ```rust
/// # use clap::Command;
/// use std::io;
/// let mut cmd = Command::new("myprog");
/// let mut out = io::stdout();
/// cmd.write_long_help(&mut out).expect("failed to write to stdout");
/// ```
/// [`io::Write`]: std::io::Write
/// [`-h` (short)]: Arg::help()
/// [`--help` (long)]: Arg::long_help()
pub fn write_long_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> {
self._build_self();
let usage = Usage::new(self);
Help::new(HelpWriter::Normal(w), self, &usage, true).write_help()?;
w.flush()
}
/// Version message rendered as if the user ran `-V`.
///
/// See also [`Command::render_long_version`].
///
/// ### Coloring
///
/// This function does not try to color the message nor it inserts any [ANSI escape codes].
///
/// ### Examples
///
/// ```rust
/// # use clap::Command;
/// use std::io;
/// let cmd = Command::new("myprog");
/// println!("{}", cmd.render_version());
/// ```
/// [`io::Write`]: std::io::Write
/// [`-V` (short)]: Command::version()
/// [`--version` (long)]: Command::long_version()
/// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
pub fn render_version(&self) -> String {
self._render_version(false)
}
/// Version message rendered as if the user ran `--version`.
///
/// See also [`Command::render_version`].
///
/// ### Coloring
///
/// This function does not try to color the message nor it inserts any [ANSI escape codes].
///
/// ### Examples
///
/// ```rust
/// # use clap::Command;
/// use std::io;
/// let cmd = Command::new("myprog");
/// println!("{}", cmd.render_long_version());
/// ```
/// [`io::Write`]: std::io::Write
/// [`-V` (short)]: Command::version()
/// [`--version` (long)]: Command::long_version()
/// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
pub fn render_long_version(&self) -> String {
self._render_version(true)
}
/// Usage statement
///
/// ### Examples
///
/// ```rust
/// # use clap::Command;
/// use std::io;
/// let mut cmd = Command::new("myprog");
/// println!("{}", cmd.render_usage());
/// ```
pub fn render_usage(&mut self) -> String {
// If there are global arguments, or settings we need to propagate them down to subcommands
// before parsing incase we run into a subcommand
self._build_self();
Usage::new(self).create_usage_with_title(&[])
}
}
/// # Application-wide Settings
///
/// These settings will apply to the top-level command and all subcommands, by default. Some
/// settings can be overridden in subcommands.
impl<'help> App<'help> {
/// Specifies that the parser should not assume the first argument passed is the binary name.
///
/// This is normally the case when using a "daemon" style mode. For shells / REPLs, see
/// [`Command::multicall`][App::multicall].
///
/// # Examples
///
/// ```rust
/// # use clap::{Command, arg};
/// let m = Command::new("myprog")
/// .no_binary_name(true)
/// .arg(arg!(<cmd> ... "commands to run"))
/// .get_matches_from(vec!["command", "set"]);
///
/// let cmds: Vec<&str> = m.values_of("cmd").unwrap().collect();
/// assert_eq!(cmds, ["command", "set"]);
/// ```
/// [`try_get_matches_from_mut`]: crate::Command::try_get_matches_from_mut()
#[inline]
pub fn no_binary_name(self, yes: bool) -> Self {
if yes {
self.global_setting(AppSettings::NoBinaryName)
} else {
self.unset_global_setting(AppSettings::NoBinaryName)
}
}
/// Try not to fail on parse errors, like missing option values.
///
/// **Note:** Make sure you apply it as `global_setting` if you want this setting
/// to be propagated to subcommands and sub-subcommands!
///
/// **NOTE:** This choice is propagated to all child subcommands.
///
/// # Examples
///
/// ```rust
/// # use clap::{Command, arg};
/// let cmd = Command::new("cmd")
/// .ignore_errors(true)
/// .arg(arg!(-c --config <FILE> "Sets a custom config file").required(false))
/// .arg(arg!(-x --stuff <FILE> "Sets a custom stuff file").required(false))
/// .arg(arg!(f: -f "Flag"));
///
/// let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]);
///
/// assert!(r.is_ok(), "unexpected error: {:?}", r);
/// let m = r.unwrap();
/// assert_eq!(m.value_of("config"), Some("file"));
/// assert!(m.is_present("f"));
/// assert_eq!(m.value_of("stuff"), None);
/// ```
#[inline]
pub fn ignore_errors(self, yes: bool) -> Self {
if yes {
self.global_setting(AppSettings::IgnoreErrors)
} else {
self.unset_global_setting(AppSettings::IgnoreErrors)
}
}
/// Deprecated, replaced with [`ArgAction::Set`][super::ArgAction::Set]
#[cfg_attr(
feature = "deprecated",
deprecated(since = "3.2.0", note = "Replaced with `Arg::action(ArgAction::Set)`")
)]
pub fn args_override_self(self, yes: bool) -> Self {
if yes {
self.global_setting(AppSettings::AllArgsOverrideSelf)
} else {
self.unset_global_setting(AppSettings::AllArgsOverrideSelf)
}
}
/// Disables the automatic delimiting of values after `--` or when [`Command::trailing_var_arg`]
/// was used.
///
/// **NOTE:** The same thing can be done manually by setting the final positional argument to
/// [`Arg::use_value_delimiter(false)`]. Using this setting is safer, because it's easier to locate
/// when making changes.
///
/// **NOTE:** This choice is propagated to all child subcommands.
///
/// # Examples
///
/// ```no_run
/// # use clap::{Command, Arg};
/// Command::new("myprog")
/// .dont_delimit_trailing_values(true)
/// .get_matches();
/// ```
///
/// [`Arg::use_value_delimiter(false)`]: crate::Arg::use_value_delimiter()
#[inline]
pub fn dont_delimit_trailing_values(self, yes: bool) -> Self {
if yes {
self.global_setting(AppSettings::DontDelimitTrailingValues)
} else {
self.unset_global_setting(AppSettings::DontDelimitTrailingValues)
}
}