1 #![cfg_attr(not(feature = "usage"), allow(unused_mut))]
5 use std
::ffi
::OsString
;
12 use crate::builder
::app_settings
::{AppFlags, AppSettings}
;
13 use crate::builder
::arg_settings
::ArgSettings
;
14 use crate::builder
::ArgAction
;
15 use crate::builder
::IntoResettable
;
16 use crate::builder
::PossibleValue
;
17 use crate::builder
::Str
;
18 use crate::builder
::StyledStr
;
19 use crate::builder
::{Arg, ArgGroup, ArgPredicate}
;
20 use crate::error
::ErrorKind
;
21 use crate::error
::Result
as ClapResult
;
22 use crate::mkeymap
::MKeyMap
;
23 use crate::output
::fmt
::Stream
;
24 use crate::output
::{fmt::Colorizer, write_help, Usage}
;
25 use crate::parser
::{ArgMatcher, ArgMatches, Parser}
;
26 use crate::util
::ChildGraph
;
27 use crate::util
::FlatMap
;
28 use crate::util
::{color::ColorChoice, Id}
;
29 use crate::{Error, INTERNAL_ERROR_MSG}
;
31 #[cfg(debug_assertions)]
32 use crate::builder
::debug_asserts
::assert_app
;
34 /// Build a command-line interface.
36 /// This includes defining arguments, subcommands, parser behavior, and help output.
37 /// Once all configuration is complete,
38 /// the [`Command::get_matches`] family of methods starts the runtime-parsing
39 /// process. These methods then return information about the user supplied
40 /// arguments (or lack thereof).
42 /// When deriving a [`Parser`][crate::Parser], you can use
43 /// [`CommandFactory::command`][crate::CommandFactory::command] to access the
46 /// - [Basic API][crate::Command#basic-api]
47 /// - [Application-wide Settings][crate::Command#application-wide-settings]
48 /// - [Command-specific Settings][crate::Command#command-specific-settings]
49 /// - [Subcommand-specific Settings][crate::Command#subcommand-specific-settings]
50 /// - [Reflection][crate::Command#reflection]
55 /// # use clap::{Command, Arg};
56 /// let m = Command::new("My Program")
57 /// .author("Me, me@mail.com")
59 /// .about("Explains in brief what the program does")
61 /// Arg::new("in_file")
63 /// .after_help("Longer explanation to appear after the options when \
64 /// displaying the help information from --help or -h")
67 /// // Your program logic starts here...
69 /// [`Command::get_matches`]: Command::get_matches()
70 #[derive(Debug, Clone)]
73 long_flag
: Option
<Str
>,
74 short_flag
: Option
<char>,
75 display_name
: Option
<String
>,
76 bin_name
: Option
<String
>,
79 long_version
: Option
<Str
>,
80 about
: Option
<StyledStr
>,
81 long_about
: Option
<StyledStr
>,
82 before_help
: Option
<StyledStr
>,
83 before_long_help
: Option
<StyledStr
>,
84 after_help
: Option
<StyledStr
>,
85 after_long_help
: Option
<StyledStr
>,
86 aliases
: Vec
<(Str
, bool
)>, // (name, visible)
87 short_flag_aliases
: Vec
<(char, bool
)>, // (name, visible)
88 long_flag_aliases
: Vec
<(Str
, bool
)>, // (name, visible)
89 usage_str
: Option
<StyledStr
>,
90 usage_name
: Option
<String
>,
91 help_str
: Option
<StyledStr
>,
92 disp_ord
: Option
<usize>,
93 term_w
: Option
<usize>,
95 #[cfg(feature = "help")]
96 template
: Option
<StyledStr
>,
100 subcommands
: Vec
<Command
>,
101 replacers
: FlatMap
<Str
, Vec
<Str
>>,
102 groups
: Vec
<ArgGroup
>,
103 current_help_heading
: Option
<Str
>,
104 current_disp_ord
: Option
<usize>,
105 subcommand_value_name
: Option
<Str
>,
106 subcommand_heading
: Option
<Str
>,
107 external_value_parser
: Option
<super::ValueParser
>,
108 long_help_exists
: bool
,
113 /// Creates a new instance of an `Command`.
115 /// It is common, but not required, to use binary name as the `name`. This
116 /// name will only be displayed to the user when they request to print
117 /// version or help and usage information.
119 /// See also [`command!`](crate::command!) and [`crate_name!`](crate::crate_name!).
124 /// # use clap::Command;
125 /// Command::new("My Program")
128 pub fn new(name
: impl Into
<Str
>) -> Self {
129 /// The actual implementation of `new`, non-generic to save code size.
131 /// If we don't do this rustc will unnecessarily generate multiple versions
133 fn new_inner(name
: Str
) -> Command
{
140 new_inner(name
.into())
143 /// Adds an [argument] to the list of valid possibilities.
148 /// # use clap::{Command, arg, Arg};
149 /// Command::new("myprog")
150 /// // Adding a single "flag" argument with a short and help text, using Arg::new()
152 /// Arg::new("debug")
154 /// .help("turns on debugging mode")
156 /// // Adding a single "option" argument with a short, a long, and help text using the less
157 /// // verbose Arg::from()
159 /// arg!(-c --config <CONFIG> "Optionally sets a config file to use")
165 pub fn arg(mut self, a
: impl Into
<Arg
>) -> Self {
167 self.arg_internal(arg
);
171 fn arg_internal(&mut self, mut arg
: Arg
) {
172 if let Some(current_disp_ord
) = self.current_disp_ord
.as_mut() {
173 if !arg
.is_positional() {
174 let current
= *current_disp_ord
;
175 arg
.disp_ord
.get_or_insert(current
);
176 *current_disp_ord
= current
+ 1;
181 .get_or_insert_with(|| self.current_help_heading
.clone());
185 /// Adds multiple [arguments] to the list of valid possibilities.
190 /// # use clap::{Command, arg, Arg};
191 /// Command::new("myprog")
193 /// arg!("[debug] -d 'turns on debugging info'"),
194 /// Arg::new("input").help("the input file to use")
200 pub fn args(mut self, args
: impl IntoIterator
<Item
= impl Into
<Arg
>>) -> Self {
202 self = self.arg(arg
);
207 /// Allows one to mutate an [`Arg`] after it's been added to a [`Command`].
209 /// This can be useful for modifying the auto-generated help or version arguments.
213 /// If the argument is undefined
218 /// # use clap::{Command, Arg, ArgAction};
220 /// let mut cmd = Command::new("foo")
221 /// .arg(Arg::new("bar")
223 /// .action(ArgAction::SetTrue))
224 /// .mut_arg("bar", |a| a.short('B'));
226 /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-b"]);
228 /// // Since we changed `bar`'s short to "B" this should err as there
229 /// // is no `-b` anymore, only `-B`
231 /// assert!(res.is_err());
233 /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-B"]);
234 /// assert!(res.is_ok());
237 #[cfg_attr(debug_assertions, track_caller)]
238 pub fn mut_arg
<F
>(mut self, arg_id
: impl AsRef
<str>, f
: F
) -> Self
240 F
: FnOnce(Arg
) -> Arg
,
242 let id
= arg_id
.as_ref();
246 .unwrap_or_else(|| panic
!("Argument `{}` is undefined", id
));
248 self.args
.push(f(a
));
252 /// Allows one to mutate a [`Command`] after it's been added as a subcommand.
254 /// This can be useful for modifying auto-generated arguments of nested subcommands with
255 /// [`Command::mut_arg`].
259 /// If the subcommand is undefined
264 /// # use clap::Command;
266 /// let mut cmd = Command::new("foo")
267 /// .subcommand(Command::new("bar"))
268 /// .mut_subcommand("bar", |subcmd| subcmd.disable_help_flag(true));
270 /// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar", "--help"]);
272 /// // Since we disabled the help flag on the "bar" subcommand, this should err.
274 /// assert!(res.is_err());
276 /// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar"]);
277 /// assert!(res.is_ok());
280 pub fn mut_subcommand
<F
>(mut self, name
: impl AsRef
<str>, f
: F
) -> Self
282 F
: FnOnce(Self) -> Self,
284 let name
= name
.as_ref();
285 let pos
= self.subcommands
.iter().position(|s
| s
.name
== name
);
287 let subcmd
= if let Some(idx
) = pos
{
288 self.subcommands
.remove(idx
)
290 panic
!("Command `{}` is undefined", name
)
293 self.subcommands
.push(f(subcmd
));
297 /// Adds an [`ArgGroup`] to the application.
299 /// [`ArgGroup`]s are a family of related arguments.
300 /// By placing them in a logical group, you can build easier requirement and exclusion rules.
302 /// Example use cases:
303 /// - Make an entire [`ArgGroup`] required, meaning that one (and *only*
304 /// one) argument from that group must be present at runtime.
305 /// - Name an [`ArgGroup`] as a conflict to another argument.
306 /// Meaning any of the arguments that belong to that group will cause a failure if present with
307 /// the conflicting argument.
308 /// - Ensure exclusion between arguments.
309 /// - Extract a value from a group instead of determining exactly which argument was used.
313 /// The following example demonstrates using an [`ArgGroup`] to ensure that one, and only one,
314 /// of the arguments from the specified group is present at runtime.
317 /// # use clap::{Command, arg, ArgGroup};
318 /// Command::new("cmd")
319 /// .arg(arg!("--set-ver [ver] 'set the version manually'"))
320 /// .arg(arg!("--major 'auto increase major'"))
321 /// .arg(arg!("--minor 'auto increase minor'"))
322 /// .arg(arg!("--patch 'auto increase patch'"))
323 /// .group(ArgGroup::new("vers")
324 /// .args(["set-ver", "major", "minor","patch"])
330 pub fn group(mut self, group
: impl Into
<ArgGroup
>) -> Self {
331 self.groups
.push(group
.into());
335 /// Adds multiple [`ArgGroup`]s to the [`Command`] at once.
340 /// # use clap::{Command, arg, ArgGroup};
341 /// Command::new("cmd")
342 /// .arg(arg!("--set-ver [ver] 'set the version manually'"))
343 /// .arg(arg!("--major 'auto increase major'"))
344 /// .arg(arg!("--minor 'auto increase minor'"))
345 /// .arg(arg!("--patch 'auto increase patch'"))
346 /// .arg(arg!("-c [FILE] 'a config file'"))
347 /// .arg(arg!("-i [IFACE] 'an interface'"))
349 /// ArgGroup::new("vers")
350 /// .args(["set-ver", "major", "minor","patch"])
352 /// ArgGroup::new("input")
353 /// .args(["c", "i"])
358 pub fn groups(mut self, groups
: impl IntoIterator
<Item
= impl Into
<ArgGroup
>>) -> Self {
359 for g
in groups
.into_iter() {
360 self = self.group(g
.into());
365 /// Adds a subcommand to the list of valid possibilities.
367 /// Subcommands are effectively sub-[`Command`]s, because they can contain their own arguments,
368 /// subcommands, version, usage, etc. They also function just like [`Command`]s, in that they get
369 /// their own auto generated help, version, and usage.
371 /// A subcommand's [`Command::name`] will be used for:
372 /// - The argument the user passes in
373 /// - Programmatically looking up the subcommand
378 /// # use clap::{Command, arg};
379 /// Command::new("myprog")
380 /// .subcommand(Command::new("config")
381 /// .about("Controls configuration features")
382 /// .arg(arg!("<config> 'Required configuration file to use'")))
387 pub fn subcommand(self, subcmd
: impl Into
<Command
>) -> Self {
388 let subcmd
= subcmd
.into();
389 self.subcommand_internal(subcmd
)
392 fn subcommand_internal(mut self, mut subcmd
: Self) -> Self {
393 if let Some(current_disp_ord
) = self.current_disp_ord
.as_mut() {
394 let current
= *current_disp_ord
;
395 subcmd
.disp_ord
.get_or_insert(current
);
396 *current_disp_ord
= current
+ 1;
398 self.subcommands
.push(subcmd
);
402 /// Adds multiple subcommands to the list of valid possibilities.
407 /// # use clap::{Command, Arg, };
408 /// # Command::new("myprog")
410 /// Command::new("config").about("Controls configuration functionality")
411 /// .arg(Arg::new("config_file")),
412 /// Command::new("debug").about("Controls debug functionality")])
415 /// [`IntoIterator`]: std::iter::IntoIterator
417 pub fn subcommands(mut self, subcmds
: impl IntoIterator
<Item
= impl Into
<Self>>) -> Self {
418 for subcmd
in subcmds
{
419 self = self.subcommand(subcmd
);
424 /// Catch problems earlier in the development cycle.
426 /// Most error states are handled as asserts under the assumption they are programming mistake
427 /// and not something to handle at runtime. Rather than relying on tests (manual or automated)
428 /// that exhaustively test your CLI to ensure the asserts are evaluated, this will run those
429 /// asserts in a way convenient for running as a test.
431 /// **Note::** This will not help with asserts in [`ArgMatches`], those will need exhaustive
432 /// testing of your CLI.
437 /// # use clap::{Command, Arg, ArgAction};
438 /// fn cmd() -> Command {
439 /// Command::new("foo")
441 /// Arg::new("bar").short('b').action(ArgAction::SetTrue)
446 /// fn verify_app() {
447 /// cmd().debug_assert();
451 /// let m = cmd().get_matches_from(vec!["foo", "-b"]);
452 /// println!("{}", m.get_flag("bar"));
455 pub fn debug_assert(mut self) {
459 /// Custom error message for post-parsing validation
464 /// # use clap::{Command, error::ErrorKind};
465 /// let mut cmd = Command::new("myprog");
466 /// let err = cmd.error(ErrorKind::InvalidValue, "Some failure case");
468 pub fn error(&mut self, kind
: ErrorKind
, message
: impl std
::fmt
::Display
) -> Error
{
469 Error
::raw(kind
, message
).format(self)
472 /// Parse [`env::args_os`], exiting on failure.
476 /// If contradictory arguments or settings exist.
481 /// # use clap::{Command, Arg};
482 /// let matches = Command::new("myprog")
483 /// // Args and options go here...
486 /// [`env::args_os`]: std::env::args_os()
487 /// [`Command::try_get_matches_from_mut`]: Command::try_get_matches_from_mut()
489 pub fn get_matches(self) -> ArgMatches
{
490 self.get_matches_from(env
::args_os())
493 /// Parse [`env::args_os`], exiting on failure.
495 /// Like [`Command::get_matches`] but doesn't consume the `Command`.
499 /// If contradictory arguments or settings exist.
504 /// # use clap::{Command, Arg};
505 /// let mut cmd = Command::new("myprog")
506 /// // Args and options go here...
508 /// let matches = cmd.get_matches_mut();
510 /// [`env::args_os`]: std::env::args_os()
511 /// [`Command::get_matches`]: Command::get_matches()
512 pub fn get_matches_mut(&mut self) -> ArgMatches
{
513 self.try_get_matches_from_mut(&mut env
::args_os())
514 .unwrap_or_else(|e
| e
.exit())
517 /// Parse [`env::args_os`], returning a [`clap::Result`] on failure.
519 /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
520 /// used. It will return a [`clap::Error`], where the [`kind`] is a
521 /// [`ErrorKind::DisplayHelp`] or [`ErrorKind::DisplayVersion`] respectively. You must call
522 /// [`Error::exit`] or perform a [`std::process::exit`].
526 /// If contradictory arguments or settings exist.
531 /// # use clap::{Command, Arg};
532 /// let matches = Command::new("myprog")
533 /// // Args and options go here...
534 /// .try_get_matches()
535 /// .unwrap_or_else(|e| e.exit());
537 /// [`env::args_os`]: std::env::args_os()
538 /// [`Error::exit`]: crate::Error::exit()
539 /// [`std::process::exit`]: std::process::exit()
540 /// [`clap::Result`]: Result
541 /// [`clap::Error`]: crate::Error
542 /// [`kind`]: crate::Error
543 /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp
544 /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion
546 pub fn try_get_matches(self) -> ClapResult
<ArgMatches
> {
548 self.try_get_matches_from(env
::args_os())
551 /// Parse the specified arguments, exiting on failure.
553 /// **NOTE:** The first argument will be parsed as the binary name unless
554 /// [`Command::no_binary_name`] is used.
558 /// If contradictory arguments or settings exist.
563 /// # use clap::{Command, Arg};
564 /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
566 /// let matches = Command::new("myprog")
567 /// // Args and options go here...
568 /// .get_matches_from(arg_vec);
570 /// [`Command::get_matches`]: Command::get_matches()
571 /// [`clap::Result`]: Result
572 /// [`Vec`]: std::vec::Vec
573 pub fn get_matches_from
<I
, T
>(mut self, itr
: I
) -> ArgMatches
575 I
: IntoIterator
<Item
= T
>,
576 T
: Into
<OsString
> + Clone
,
578 self.try_get_matches_from_mut(itr
).unwrap_or_else(|e
| {
584 /// Parse the specified arguments, returning a [`clap::Result`] on failure.
586 /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
587 /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`]
588 /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or
589 /// perform a [`std::process::exit`] yourself.
591 /// **NOTE:** The first argument will be parsed as the binary name unless
592 /// [`Command::no_binary_name`] is used.
596 /// If contradictory arguments or settings exist.
601 /// # use clap::{Command, Arg};
602 /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
604 /// let matches = Command::new("myprog")
605 /// // Args and options go here...
606 /// .try_get_matches_from(arg_vec)
607 /// .unwrap_or_else(|e| e.exit());
609 /// [`Command::get_matches_from`]: Command::get_matches_from()
610 /// [`Command::try_get_matches`]: Command::try_get_matches()
611 /// [`Error::exit`]: crate::Error::exit()
612 /// [`std::process::exit`]: std::process::exit()
613 /// [`clap::Error`]: crate::Error
614 /// [`Error::exit`]: crate::Error::exit()
615 /// [`kind`]: crate::Error
616 /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp
617 /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion
618 /// [`clap::Result`]: Result
619 pub fn try_get_matches_from
<I
, T
>(mut self, itr
: I
) -> ClapResult
<ArgMatches
>
621 I
: IntoIterator
<Item
= T
>,
622 T
: Into
<OsString
> + Clone
,
624 self.try_get_matches_from_mut(itr
)
627 /// Parse the specified arguments, returning a [`clap::Result`] on failure.
629 /// Like [`Command::try_get_matches_from`] but doesn't consume the `Command`.
631 /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
632 /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`]
633 /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or
634 /// perform a [`std::process::exit`] yourself.
636 /// **NOTE:** The first argument will be parsed as the binary name unless
637 /// [`Command::no_binary_name`] is used.
641 /// If contradictory arguments or settings exist.
646 /// # use clap::{Command, Arg};
647 /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
649 /// let mut cmd = Command::new("myprog");
650 /// // Args and options go here...
651 /// let matches = cmd.try_get_matches_from_mut(arg_vec)
652 /// .unwrap_or_else(|e| e.exit());
654 /// [`Command::try_get_matches_from`]: Command::try_get_matches_from()
655 /// [`clap::Result`]: Result
656 /// [`clap::Error`]: crate::Error
657 /// [`kind`]: crate::Error
658 pub fn try_get_matches_from_mut
<I
, T
>(&mut self, itr
: I
) -> ClapResult
<ArgMatches
>
660 I
: IntoIterator
<Item
= T
>,
661 T
: Into
<OsString
> + Clone
,
663 let mut raw_args
= clap_lex
::RawArgs
::new(itr
.into_iter());
664 let mut cursor
= raw_args
.cursor();
666 if self.settings
.is_set(AppSettings
::Multicall
) {
667 if let Some(argv0
) = raw_args
.next_os(&mut cursor
) {
668 let argv0
= Path
::new(&argv0
);
669 if let Some(command
) = argv0
.file_stem().and_then(|f
| f
.to_str()) {
670 // Stop borrowing command so we can get another mut ref to it.
671 let command
= command
.to_owned();
673 "Command::try_get_matches_from_mut: Parsed command {} from argv",
677 debug
!("Command::try_get_matches_from_mut: Reinserting command into arguments so subcommand parser matches it");
678 raw_args
.insert(&cursor
, [&command
]);
679 debug
!("Command::try_get_matches_from_mut: Clearing name and bin_name so that displayed command name starts with applet name");
680 self.name
= "".into();
681 self.bin_name
= None
;
682 return self._do_parse(&mut raw_args
, cursor
);
687 // Get the name of the program (argument 1 of env::args()) and determine the
689 // that was used to execute the program. This is because a program called
690 // ./target/release/my_prog -a
691 // will have two arguments, './target/release/my_prog', '-a' but we don't want
693 // the full path when displaying help messages and such
694 if !self.settings
.is_set(AppSettings
::NoBinaryName
) {
695 if let Some(name
) = raw_args
.next_os(&mut cursor
) {
696 let p
= Path
::new(name
);
698 if let Some(f
) = p
.file_name() {
699 if let Some(s
) = f
.to_str() {
700 if self.bin_name
.is_none() {
701 self.bin_name
= Some(s
.to_owned());
708 self._do_parse(&mut raw_args
, cursor
)
711 /// Prints the short help message (`-h`) to [`io::stdout()`].
713 /// See also [`Command::print_long_help`].
718 /// # use clap::Command;
719 /// let mut cmd = Command::new("myprog");
720 /// cmd.print_help();
722 /// [`io::stdout()`]: std::io::stdout()
723 pub fn print_help(&mut self) -> io
::Result
<()> {
724 self._build_self(false);
725 let color
= self.color_help();
727 let mut styled
= StyledStr
::new();
728 let usage
= Usage
::new(self);
729 write_help(&mut styled
, self, &usage
, false);
731 let c
= Colorizer
::new(Stream
::Stdout
, color
).with_content(styled
);
735 /// Prints the long help message (`--help`) to [`io::stdout()`].
737 /// See also [`Command::print_help`].
742 /// # use clap::Command;
743 /// let mut cmd = Command::new("myprog");
744 /// cmd.print_long_help();
746 /// [`io::stdout()`]: std::io::stdout()
747 /// [`BufWriter`]: std::io::BufWriter
748 /// [`-h` (short)]: Arg::help()
749 /// [`--help` (long)]: Arg::long_help()
750 pub fn print_long_help(&mut self) -> io
::Result
<()> {
751 self._build_self(false);
752 let color
= self.color_help();
754 let mut styled
= StyledStr
::new();
755 let usage
= Usage
::new(self);
756 write_help(&mut styled
, self, &usage
, true);
758 let c
= Colorizer
::new(Stream
::Stdout
, color
).with_content(styled
);
762 /// Render the short help message (`-h`) to a [`StyledStr`]
764 /// See also [`Command::render_long_help`].
769 /// # use clap::Command;
771 /// let mut cmd = Command::new("myprog");
772 /// let mut out = io::stdout();
773 /// let help = cmd.render_help();
774 /// println!("{}", help);
776 /// [`io::Write`]: std::io::Write
777 /// [`-h` (short)]: Arg::help()
778 /// [`--help` (long)]: Arg::long_help()
779 pub fn render_help(&mut self) -> StyledStr
{
780 self._build_self(false);
782 let mut styled
= StyledStr
::new();
783 let usage
= Usage
::new(self);
784 write_help(&mut styled
, self, &usage
, false);
788 /// Render the long help message (`--help`) to a [`StyledStr`].
790 /// See also [`Command::render_help`].
795 /// # use clap::Command;
797 /// let mut cmd = Command::new("myprog");
798 /// let mut out = io::stdout();
799 /// let help = cmd.render_long_help();
800 /// println!("{}", help);
802 /// [`io::Write`]: std::io::Write
803 /// [`-h` (short)]: Arg::help()
804 /// [`--help` (long)]: Arg::long_help()
805 pub fn render_long_help(&mut self) -> StyledStr
{
806 self._build_self(false);
808 let mut styled
= StyledStr
::new();
809 let usage
= Usage
::new(self);
810 write_help(&mut styled
, self, &usage
, true);
816 feature
= "deprecated",
817 deprecated(since
= "4.0.0", note
= "Replaced with `Command::render_help`")
819 pub fn write_help
<W
: io
::Write
>(&mut self, w
: &mut W
) -> io
::Result
<()> {
820 self._build_self(false);
822 let mut styled
= StyledStr
::new();
823 let usage
= Usage
::new(self);
824 write_help(&mut styled
, self, &usage
, false);
825 ok
!(write
!(w
, "{}", styled
));
831 feature
= "deprecated",
832 deprecated(since
= "4.0.0", note
= "Replaced with `Command::render_long_help`")
834 pub fn write_long_help
<W
: io
::Write
>(&mut self, w
: &mut W
) -> io
::Result
<()> {
835 self._build_self(false);
837 let mut styled
= StyledStr
::new();
838 let usage
= Usage
::new(self);
839 write_help(&mut styled
, self, &usage
, true);
840 ok
!(write
!(w
, "{}", styled
));
844 /// Version message rendered as if the user ran `-V`.
846 /// See also [`Command::render_long_version`].
850 /// This function does not try to color the message nor it inserts any [ANSI escape codes].
855 /// # use clap::Command;
857 /// let cmd = Command::new("myprog");
858 /// println!("{}", cmd.render_version());
860 /// [`io::Write`]: std::io::Write
861 /// [`-V` (short)]: Command::version()
862 /// [`--version` (long)]: Command::long_version()
863 /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
864 pub fn render_version(&self) -> String
{
865 self._render_version(false)
868 /// Version message rendered as if the user ran `--version`.
870 /// See also [`Command::render_version`].
874 /// This function does not try to color the message nor it inserts any [ANSI escape codes].
879 /// # use clap::Command;
881 /// let cmd = Command::new("myprog");
882 /// println!("{}", cmd.render_long_version());
884 /// [`io::Write`]: std::io::Write
885 /// [`-V` (short)]: Command::version()
886 /// [`--version` (long)]: Command::long_version()
887 /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
888 pub fn render_long_version(&self) -> String
{
889 self._render_version(true)
897 /// # use clap::Command;
899 /// let mut cmd = Command::new("myprog");
900 /// println!("{}", cmd.render_usage());
902 pub fn render_usage(&mut self) -> StyledStr
{
903 self.render_usage_().unwrap_or_default()
906 pub(crate) fn render_usage_(&mut self) -> Option
<StyledStr
> {
907 // If there are global arguments, or settings we need to propagate them down to subcommands
908 // before parsing incase we run into a subcommand
909 self._build_self(false);
911 Usage
::new(self).create_usage_with_title(&[])
915 /// # Application-wide Settings
917 /// These settings will apply to the top-level command and all subcommands, by default. Some
918 /// settings can be overridden in subcommands.
920 /// Specifies that the parser should not assume the first argument passed is the binary name.
922 /// This is normally the case when using a "daemon" style mode. For shells / REPLs, see
923 /// [`Command::multicall`][Command::multicall].
928 /// # use clap::{Command, arg};
929 /// let m = Command::new("myprog")
930 /// .no_binary_name(true)
931 /// .arg(arg!(<cmd> ... "commands to run"))
932 /// .get_matches_from(vec!["command", "set"]);
934 /// let cmds: Vec<_> = m.get_many::<String>("cmd").unwrap().collect();
935 /// assert_eq!(cmds, ["command", "set"]);
937 /// [`try_get_matches_from_mut`]: crate::Command::try_get_matches_from_mut()
939 pub fn no_binary_name(self, yes
: bool
) -> Self {
941 self.global_setting(AppSettings
::NoBinaryName
)
943 self.unset_global_setting(AppSettings
::NoBinaryName
)
947 /// Try not to fail on parse errors, like missing option values.
949 /// **NOTE:** This choice is propagated to all child subcommands.
954 /// # use clap::{Command, arg};
955 /// let cmd = Command::new("cmd")
956 /// .ignore_errors(true)
957 /// .arg(arg!(-c --config <FILE> "Sets a custom config file"))
958 /// .arg(arg!(-x --stuff <FILE> "Sets a custom stuff file"))
959 /// .arg(arg!(f: -f "Flag"));
961 /// let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]);
963 /// assert!(r.is_ok(), "unexpected error: {:?}", r);
964 /// let m = r.unwrap();
965 /// assert_eq!(m.get_one::<String>("config").unwrap(), "file");
966 /// assert!(m.get_flag("f"));
967 /// assert_eq!(m.get_one::<String>("stuff"), None);
970 pub fn ignore_errors(self, yes
: bool
) -> Self {
972 self.global_setting(AppSettings
::IgnoreErrors
)
974 self.unset_global_setting(AppSettings
::IgnoreErrors
)
978 /// Replace prior occurrences of arguments rather than error
980 /// For any argument that would conflict with itself by default (e.g.
981 /// [`ArgAction::Set`][ArgAction::Set], it will now override itself.
983 /// This is the equivalent to saying the `foo` arg using [`Arg::overrides_with("foo")`] for all
984 /// defined arguments.
986 /// **NOTE:** This choice is propagated to all child subcommands.
988 /// [`Arg::overrides_with("foo")`]: crate::Arg::overrides_with()
990 pub fn args_override_self(self, yes
: bool
) -> Self {
992 self.global_setting(AppSettings
::AllArgsOverrideSelf
)
994 self.unset_global_setting(AppSettings
::AllArgsOverrideSelf
)
998 /// Disables the automatic delimiting of values after `--` or when [`Command::trailing_var_arg`]
1001 /// **NOTE:** The same thing can be done manually by setting the final positional argument to
1002 /// [`Arg::value_delimiter(None)`]. Using this setting is safer, because it's easier to locate
1003 /// when making changes.
1005 /// **NOTE:** This choice is propagated to all child subcommands.
1010 /// # use clap::{Command, Arg};
1011 /// Command::new("myprog")
1012 /// .dont_delimit_trailing_values(true)
1016 /// [`Arg::value_delimiter(None)`]: crate::Arg::value_delimiter()
1018 pub fn dont_delimit_trailing_values(self, yes
: bool
) -> Self {
1020 self.global_setting(AppSettings
::DontDelimitTrailingValues
)
1022 self.unset_global_setting(AppSettings
::DontDelimitTrailingValues
)
1026 /// Sets when to color output.
1028 /// **NOTE:** This choice is propagated to all child subcommands.
1030 /// **NOTE:** Default behaviour is [`ColorChoice::Auto`].
1035 /// # use clap::{Command, ColorChoice};
1036 /// Command::new("myprog")
1037 /// .color(ColorChoice::Never)
1040 /// [`ColorChoice::Auto`]: crate::ColorChoice::Auto
1041 #[cfg(feature = "color")]
1044 pub fn color(self, color
: ColorChoice
) -> Self {
1046 .unset_global_setting(AppSettings
::ColorAuto
)
1047 .unset_global_setting(AppSettings
::ColorAlways
)
1048 .unset_global_setting(AppSettings
::ColorNever
);
1050 ColorChoice
::Auto
=> cmd
.global_setting(AppSettings
::ColorAuto
),
1051 ColorChoice
::Always
=> cmd
.global_setting(AppSettings
::ColorAlways
),
1052 ColorChoice
::Never
=> cmd
.global_setting(AppSettings
::ColorNever
),
1056 /// Sets the terminal width at which to wrap help messages.
1058 /// Using `0` will ignore terminal widths and use source formatting.
1060 /// Defaults to current terminal width when `wrap_help` feature flag is enabled. If the flag
1061 /// is disabled or it cannot be determined, the default is 100.
1063 /// **NOTE:** This setting applies globally and *not* on a per-command basis.
1065 /// **NOTE:** This requires the [`wrap_help` feature][crate::_features]
1070 /// # use clap::Command;
1071 /// Command::new("myprog")
1077 #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))]
1078 pub fn term_width(mut self, width
: usize) -> Self {
1079 self.term_w
= Some(width
);
1083 /// Limit the line length for wrapping help when using the current terminal's width.
1085 /// This only applies when [`term_width`][Command::term_width] is unset so that the current
1086 /// terminal's width will be used. See [`Command::term_width`] for more details.
1088 /// Using `0` will ignore terminal widths and use source formatting (default).
1090 /// **NOTE:** This setting applies globally and *not* on a per-command basis.
1092 /// **NOTE:** This requires the [`wrap_help` feature][crate::_features]
1097 /// # use clap::Command;
1098 /// Command::new("myprog")
1099 /// .max_term_width(100)
1104 #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))]
1105 pub fn max_term_width(mut self, w
: usize) -> Self {
1106 self.max_w
= Some(w
);
1110 /// Disables `-V` and `--version` flag.
1115 /// # use clap::{Command, error::ErrorKind};
1116 /// let res = Command::new("myprog")
1117 /// .disable_version_flag(true)
1118 /// .try_get_matches_from(vec![
1121 /// assert!(res.is_err());
1122 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
1125 pub fn disable_version_flag(self, yes
: bool
) -> Self {
1127 self.global_setting(AppSettings
::DisableVersionFlag
)
1129 self.unset_global_setting(AppSettings
::DisableVersionFlag
)
1133 /// Specifies to use the version of the current command for all [`subcommands`].
1135 /// Defaults to `false`; subcommands have independent version strings from their parents.
1137 /// **NOTE:** This choice is propagated to all child subcommands.
1142 /// # use clap::{Command, Arg};
1143 /// Command::new("myprog")
1144 /// .version("v1.1")
1145 /// .propagate_version(true)
1146 /// .subcommand(Command::new("test"))
1148 /// // running `$ myprog test --version` will display
1149 /// // "myprog-test v1.1"
1152 /// [`subcommands`]: crate::Command::subcommand()
1154 pub fn propagate_version(self, yes
: bool
) -> Self {
1156 self.global_setting(AppSettings
::PropagateVersion
)
1158 self.unset_global_setting(AppSettings
::PropagateVersion
)
1162 /// Places the help string for all arguments and subcommands on the line after them.
1164 /// **NOTE:** This choice is propagated to all child subcommands.
1169 /// # use clap::{Command, Arg};
1170 /// Command::new("myprog")
1171 /// .next_line_help(true)
1175 pub fn next_line_help(self, yes
: bool
) -> Self {
1177 self.global_setting(AppSettings
::NextLineHelp
)
1179 self.unset_global_setting(AppSettings
::NextLineHelp
)
1183 /// Disables `-h` and `--help` flag.
1185 /// **NOTE:** This choice is propagated to all child subcommands.
1190 /// # use clap::{Command, error::ErrorKind};
1191 /// let res = Command::new("myprog")
1192 /// .disable_help_flag(true)
1193 /// .try_get_matches_from(vec![
1196 /// assert!(res.is_err());
1197 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
1200 pub fn disable_help_flag(self, yes
: bool
) -> Self {
1202 self.global_setting(AppSettings
::DisableHelpFlag
)
1204 self.unset_global_setting(AppSettings
::DisableHelpFlag
)
1208 /// Disables the `help` [`subcommand`].
1213 /// # use clap::{Command, error::ErrorKind};
1214 /// let res = Command::new("myprog")
1215 /// .disable_help_subcommand(true)
1216 /// // Normally, creating a subcommand causes a `help` subcommand to automatically
1217 /// // be generated as well
1218 /// .subcommand(Command::new("test"))
1219 /// .try_get_matches_from(vec![
1220 /// "myprog", "help"
1222 /// assert!(res.is_err());
1223 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::InvalidSubcommand);
1226 /// [`subcommand`]: crate::Command::subcommand()
1228 pub fn disable_help_subcommand(self, yes
: bool
) -> Self {
1230 self.global_setting(AppSettings
::DisableHelpSubcommand
)
1232 self.unset_global_setting(AppSettings
::DisableHelpSubcommand
)
1236 /// Disables colorized help messages.
1238 /// **NOTE:** This choice is propagated to all child subcommands.
1243 /// # use clap::Command;
1244 /// Command::new("myprog")
1245 /// .disable_colored_help(true)
1249 pub fn disable_colored_help(self, yes
: bool
) -> Self {
1251 self.global_setting(AppSettings
::DisableColoredHelp
)
1253 self.unset_global_setting(AppSettings
::DisableColoredHelp
)
1257 /// Panic if help descriptions are omitted.
1259 /// **NOTE:** When deriving [`Parser`][crate::Parser], you could instead check this at
1260 /// compile-time with `#![deny(missing_docs)]`
1262 /// **NOTE:** This choice is propagated to all child subcommands.
1267 /// # use clap::{Command, Arg};
1268 /// Command::new("myprog")
1269 /// .help_expected(true)
1271 /// Arg::new("foo").help("It does foo stuff")
1272 /// // As required via `help_expected`, a help message was supplied
1274 /// # .get_matches();
1280 /// # use clap::{Command, Arg};
1281 /// Command::new("myapp")
1282 /// .help_expected(true)
1285 /// // Someone forgot to put .about("...") here
1286 /// // Since the setting `help_expected` is activated, this will lead to
1287 /// // a panic (if you are in debug mode)
1289 /// # .get_matches();
1292 pub fn help_expected(self, yes
: bool
) -> Self {
1294 self.global_setting(AppSettings
::HelpExpected
)
1296 self.unset_global_setting(AppSettings
::HelpExpected
)
1302 feature
= "deprecated",
1303 deprecated(since
= "4.0.0", note
= "This is now the default")
1305 pub fn dont_collapse_args_in_usage(self, _yes
: bool
) -> Self {
1309 /// Tells `clap` *not* to print possible values when displaying help information.
1311 /// This can be useful if there are many values, or they are explained elsewhere.
1313 /// To set this per argument, see
1314 /// [`Arg::hide_possible_values`][crate::Arg::hide_possible_values].
1316 /// **NOTE:** This choice is propagated to all child subcommands.
1318 pub fn hide_possible_values(self, yes
: bool
) -> Self {
1320 self.global_setting(AppSettings
::HidePossibleValues
)
1322 self.unset_global_setting(AppSettings
::HidePossibleValues
)
1326 /// Allow partial matches of long arguments or their [aliases].
1328 /// For example, to match an argument named `--test`, one could use `--t`, `--te`, `--tes`, and
1331 /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match
1332 /// `--te` to `--test` there could not also be another argument or alias `--temp` because both
1333 /// start with `--te`
1335 /// **NOTE:** This choice is propagated to all child subcommands.
1337 /// [aliases]: crate::Command::aliases()
1339 pub fn infer_long_args(self, yes
: bool
) -> Self {
1341 self.global_setting(AppSettings
::InferLongArgs
)
1343 self.unset_global_setting(AppSettings
::InferLongArgs
)
1347 /// Allow partial matches of [subcommand] names and their [aliases].
1349 /// For example, to match a subcommand named `test`, one could use `t`, `te`, `tes`, and
1352 /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match `te`
1353 /// to `test` there could not also be a subcommand or alias `temp` because both start with `te`
1355 /// **CAUTION:** This setting can interfere with [positional/free arguments], take care when
1356 /// designing CLIs which allow inferred subcommands and have potential positional/free
1357 /// arguments whose values could start with the same characters as subcommands. If this is the
1358 /// case, it's recommended to use settings such as [`Command::args_conflicts_with_subcommands`] in
1359 /// conjunction with this setting.
1361 /// **NOTE:** This choice is propagated to all child subcommands.
1366 /// # use clap::{Command, Arg};
1367 /// let m = Command::new("prog")
1368 /// .infer_subcommands(true)
1369 /// .subcommand(Command::new("test"))
1370 /// .get_matches_from(vec![
1373 /// assert_eq!(m.subcommand_name(), Some("test"));
1376 /// [subcommand]: crate::Command::subcommand()
1377 /// [positional/free arguments]: crate::Arg::index()
1378 /// [aliases]: crate::Command::aliases()
1380 pub fn infer_subcommands(self, yes
: bool
) -> Self {
1382 self.global_setting(AppSettings
::InferSubcommands
)
1384 self.unset_global_setting(AppSettings
::InferSubcommands
)
1389 /// # Command-specific Settings
1391 /// These apply only to the current command and are not inherited by subcommands.
1393 /// (Re)Sets the program's name.
1395 /// See [`Command::new`] for more details.
1400 /// let cmd = clap::command!()
1403 /// // continued logic goes here, such as `cmd.get_matches()` etc.
1406 pub fn name(mut self, name
: impl Into
<Str
>) -> Self {
1407 self.name
= name
.into();
1411 /// Overrides the runtime-determined name of the binary for help and error messages.
1413 /// This should only be used when absolutely necessary, such as when the binary name for your
1414 /// application is misleading, or perhaps *not* how the user should invoke your program.
1416 /// **Pro-tip:** When building things such as third party `cargo`
1417 /// subcommands, this setting **should** be used!
1419 /// **NOTE:** This *does not* change or set the name of the binary file on
1420 /// disk. It only changes what clap thinks the name is for the purposes of
1421 /// error or help messages.
1426 /// # use clap::Command;
1427 /// Command::new("My Program")
1428 /// .bin_name("my_binary")
1432 pub fn bin_name(mut self, name
: impl IntoResettable
<String
>) -> Self {
1433 self.bin_name
= name
.into_resettable().into_option();
1437 /// Overrides the runtime-determined display name of the program for help and error messages.
1442 /// # use clap::Command;
1443 /// Command::new("My Program")
1444 /// .display_name("my_program")
1448 pub fn display_name(mut self, name
: impl IntoResettable
<String
>) -> Self {
1449 self.display_name
= name
.into_resettable().into_option();
1453 /// Sets the author(s) for the help message.
1455 /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to
1456 /// automatically set your application's author(s) to the same thing as your
1457 /// crate at compile time.
1459 /// **NOTE:** A custom [`help_template`][Command::help_template] is needed for author to show
1465 /// # use clap::Command;
1466 /// Command::new("myprog")
1467 /// .author("Me, me@mymain.com")
1471 pub fn author(mut self, author
: impl IntoResettable
<Str
>) -> Self {
1472 self.author
= author
.into_resettable().into_option();
1476 /// Sets the program's description for the short help (`-h`).
1478 /// If [`Command::long_about`] is not specified, this message will be displayed for `--help`.
1480 /// **NOTE:** Only `Command::about` (short format) is used in completion
1481 /// script generation in order to be concise.
1483 /// See also [`crate_description!`](crate::crate_description!).
1488 /// # use clap::Command;
1489 /// Command::new("myprog")
1490 /// .about("Does really amazing things for great people")
1494 pub fn about(mut self, about
: impl IntoResettable
<StyledStr
>) -> Self {
1495 self.about
= about
.into_resettable().into_option();
1499 /// Sets the program's description for the long help (`--help`).
1501 /// If [`Command::about`] is not specified, this message will be displayed for `-h`.
1503 /// **NOTE:** Only [`Command::about`] (short format) is used in completion
1504 /// script generation in order to be concise.
1509 /// # use clap::Command;
1510 /// Command::new("myprog")
1512 /// "Does really amazing things to great people. Now let's talk a little
1513 /// more in depth about how this subcommand really works. It may take about
1514 /// a few lines of text, but that's ok!")
1517 /// [`Command::about`]: Command::about()
1519 pub fn long_about(mut self, long_about
: impl IntoResettable
<StyledStr
>) -> Self {
1520 self.long_about
= long_about
.into_resettable().into_option();
1524 /// Free-form help text for after auto-generated short help (`-h`).
1526 /// This is often used to describe how to use the arguments, caveats to be noted, or license
1527 /// and contact information.
1529 /// If [`Command::after_long_help`] is not specified, this message will be displayed for `--help`.
1534 /// # use clap::Command;
1535 /// Command::new("myprog")
1536 /// .after_help("Does really amazing things for great people... but be careful with -R!")
1541 pub fn after_help(mut self, help
: impl IntoResettable
<StyledStr
>) -> Self {
1542 self.after_help
= help
.into_resettable().into_option();
1546 /// Free-form help text for after auto-generated long help (`--help`).
1548 /// This is often used to describe how to use the arguments, caveats to be noted, or license
1549 /// and contact information.
1551 /// If [`Command::after_help`] is not specified, this message will be displayed for `-h`.
1556 /// # use clap::Command;
1557 /// Command::new("myprog")
1558 /// .after_long_help("Does really amazing things to great people... but be careful with -R, \
1559 /// like, for real, be careful with this!")
1563 pub fn after_long_help(mut self, help
: impl IntoResettable
<StyledStr
>) -> Self {
1564 self.after_long_help
= help
.into_resettable().into_option();
1568 /// Free-form help text for before auto-generated short help (`-h`).
1570 /// This is often used for header, copyright, or license information.
1572 /// If [`Command::before_long_help`] is not specified, this message will be displayed for `--help`.
1577 /// # use clap::Command;
1578 /// Command::new("myprog")
1579 /// .before_help("Some info I'd like to appear before the help info")
1583 pub fn before_help(mut self, help
: impl IntoResettable
<StyledStr
>) -> Self {
1584 self.before_help
= help
.into_resettable().into_option();
1588 /// Free-form help text for before auto-generated long help (`--help`).
1590 /// This is often used for header, copyright, or license information.
1592 /// If [`Command::before_help`] is not specified, this message will be displayed for `-h`.
1597 /// # use clap::Command;
1598 /// Command::new("myprog")
1599 /// .before_long_help("Some verbose and long info I'd like to appear before the help info")
1603 pub fn before_long_help(mut self, help
: impl IntoResettable
<StyledStr
>) -> Self {
1604 self.before_long_help
= help
.into_resettable().into_option();
1608 /// Sets the version for the short version (`-V`) and help messages.
1610 /// If [`Command::long_version`] is not specified, this message will be displayed for `--version`.
1612 /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to
1613 /// automatically set your application's version to the same thing as your
1614 /// crate at compile time.
1619 /// # use clap::Command;
1620 /// Command::new("myprog")
1621 /// .version("v0.1.24")
1625 pub fn version(mut self, ver
: impl IntoResettable
<Str
>) -> Self {
1626 self.version
= ver
.into_resettable().into_option();
1630 /// Sets the version for the long version (`--version`) and help messages.
1632 /// If [`Command::version`] is not specified, this message will be displayed for `-V`.
1634 /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to
1635 /// automatically set your application's version to the same thing as your
1636 /// crate at compile time.
1641 /// # use clap::Command;
1642 /// Command::new("myprog")
1645 /// commit: abcdef89726d
1648 /// binary: myprog")
1652 pub fn long_version(mut self, ver
: impl IntoResettable
<Str
>) -> Self {
1653 self.long_version
= ver
.into_resettable().into_option();
1657 /// Overrides the `clap` generated usage string for help and error messages.
1659 /// **NOTE:** Using this setting disables `clap`s "context-aware" usage
1660 /// strings. After this setting is set, this will be *the only* usage string
1661 /// displayed to the user!
1663 /// **NOTE:** Multiple usage lines may be present in the usage argument, but
1664 /// some rules need to be followed to ensure the usage lines are formatted
1665 /// correctly by the default help formatter:
1667 /// - Do not indent the first usage line.
1668 /// - Indent all subsequent usage lines with seven spaces.
1669 /// - The last line must not end with a newline.
1674 /// # use clap::{Command, Arg};
1675 /// Command::new("myprog")
1676 /// .override_usage("myapp [-clDas] <some_file>")
1680 /// Or for multiple usage lines:
1683 /// # use clap::{Command, Arg};
1684 /// Command::new("myprog")
1685 /// .override_usage(
1686 /// "myapp -X [-a] [-b] <file>\n \
1687 /// myapp -Y [-c] <file1> <file2>\n \
1688 /// myapp -Z [-d|-e]"
1693 /// [`ArgMatches::usage`]: ArgMatches::usage()
1695 pub fn override_usage(mut self, usage
: impl IntoResettable
<StyledStr
>) -> Self {
1696 self.usage_str
= usage
.into_resettable().into_option();
1700 /// Overrides the `clap` generated help message (both `-h` and `--help`).
1702 /// This should only be used when the auto-generated message does not suffice.
1704 /// **NOTE:** This **only** replaces the help message for the current
1705 /// command, meaning if you are using subcommands, those help messages will
1706 /// still be auto-generated unless you specify a [`Command::override_help`] for
1712 /// # use clap::{Command, Arg};
1713 /// Command::new("myapp")
1714 /// .override_help("myapp v1.0\n\
1715 /// Does awesome things\n\
1716 /// (C) me@mail.com\n\n\
1718 /// Usage: myapp <opts> <command>\n\n\
1721 /// -h, --help Display this message\n\
1722 /// -V, --version Display version info\n\
1723 /// -s <stuff> Do something with stuff\n\
1724 /// -v Be verbose\n\n\
1727 /// help Print this message\n\
1728 /// work Do some work")
1732 pub fn override_help(mut self, help
: impl IntoResettable
<StyledStr
>) -> Self {
1733 self.help_str
= help
.into_resettable().into_option();
1737 /// Sets the help template to be used, overriding the default format.
1739 /// **NOTE:** The template system is by design very simple. Therefore, the
1740 /// tags have to be written in the lowercase and without spacing.
1742 /// Tags are given inside curly brackets.
1746 /// * `{name}` - Display name for the (sub-)command.
1747 /// * `{bin}` - Binary name.(deprecated)
1748 /// * `{version}` - Version number.
1749 /// * `{author}` - Author information.
1750 /// * `{author-with-newline}` - Author followed by `\n`.
1751 /// * `{author-section}` - Author preceded and followed by `\n`.
1752 /// * `{about}` - General description (from [`Command::about`] or
1753 /// [`Command::long_about`]).
1754 /// * `{about-with-newline}` - About followed by `\n`.
1755 /// * `{about-section}` - About preceded and followed by '\n'.
1756 /// * `{usage-heading}` - Automatically generated usage heading.
1757 /// * `{usage}` - Automatically generated or given usage string.
1758 /// * `{all-args}` - Help for all arguments (options, flags, positional
1759 /// arguments, and subcommands) including titles.
1760 /// * `{options}` - Help for options.
1761 /// * `{positionals}` - Help for positional arguments.
1762 /// * `{subcommands}` - Help for subcommands.
1763 /// * `{tab}` - Standard tab sized used within clap
1764 /// * `{after-help}` - Help from [`Command::after_help`] or [`Command::after_long_help`].
1765 /// * `{before-help}` - Help from [`Command::before_help`] or [`Command::before_long_help`].
1769 /// For a very brief help:
1772 /// # use clap::Command;
1773 /// Command::new("myprog")
1775 /// .help_template("{name} ({version}) - {usage}")
1779 /// For showing more application context:
1782 /// # use clap::Command;
1783 /// Command::new("myprog")
1785 /// .help_template("\
1786 /// {before-help}{name} {version}
1787 /// {author-with-newline}{about-with-newline}
1788 /// {usage-heading} {usage}
1790 /// {all-args}{after-help}
1794 /// [`Command::about`]: Command::about()
1795 /// [`Command::long_about`]: Command::long_about()
1796 /// [`Command::after_help`]: Command::after_help()
1797 /// [`Command::after_long_help`]: Command::after_long_help()
1798 /// [`Command::before_help`]: Command::before_help()
1799 /// [`Command::before_long_help`]: Command::before_long_help()
1801 #[cfg(feature = "help")]
1802 pub fn help_template(mut self, s
: impl IntoResettable
<StyledStr
>) -> Self {
1803 self.template
= s
.into_resettable().into_option();
1809 pub(crate) fn setting
<F
>(mut self, setting
: F
) -> Self
1813 self.settings
.insert(setting
.into());
1819 pub(crate) fn unset_setting
<F
>(mut self, setting
: F
) -> Self
1823 self.settings
.remove(setting
.into());
1829 pub(crate) fn global_setting(mut self, setting
: AppSettings
) -> Self {
1830 self.settings
.set(setting
);
1831 self.g_settings
.set(setting
);
1837 pub(crate) fn unset_global_setting(mut self, setting
: AppSettings
) -> Self {
1838 self.settings
.unset(setting
);
1839 self.g_settings
.unset(setting
);
1843 /// Set the default section heading for future args.
1845 /// This will be used for any arg that hasn't had [`Arg::help_heading`] called.
1847 /// This is useful if the default `Options` or `Arguments` headings are
1848 /// not specific enough for one's use case.
1850 /// For subcommands, see [`Command::subcommand_help_heading`]
1852 /// [`Command::arg`]: Command::arg()
1853 /// [`Arg::help_heading`]: crate::Arg::help_heading()
1856 pub fn next_help_heading(mut self, heading
: impl IntoResettable
<Str
>) -> Self {
1857 self.current_help_heading
= heading
.into_resettable().into_option();
1861 /// Change the starting value for assigning future display orders for ags.
1863 /// This will be used for any arg that hasn't had [`Arg::display_order`] called.
1866 pub fn next_display_order(mut self, disp_ord
: impl IntoResettable
<usize>) -> Self {
1867 self.current_disp_ord
= disp_ord
.into_resettable().into_option();
1871 /// Replaces an argument or subcommand used on the CLI at runtime with other arguments or subcommands.
1873 /// **Note:** This is gated behind [`unstable-replace`](https://github.com/clap-rs/clap/issues/2836)
1875 /// When this method is used, `name` is removed from the CLI, and `target`
1876 /// is inserted in its place. Parsing continues as if the user typed
1877 /// `target` instead of `name`.
1879 /// This can be used to create "shortcuts" for subcommands, or if a
1880 /// particular argument has the semantic meaning of several other specific
1881 /// arguments and values.
1885 /// We'll start with the "subcommand short" example. In this example, let's
1886 /// assume we have a program with a subcommand `module` which can be invoked
1887 /// via `cmd module`. Now let's also assume `module` also has a subcommand
1888 /// called `install` which can be invoked `cmd module install`. If for some
1889 /// reason users needed to be able to reach `cmd module install` via the
1890 /// short-hand `cmd install`, we'd have several options.
1892 /// We *could* create another sibling subcommand to `module` called
1893 /// `install`, but then we would need to manage another subcommand and manually
1894 /// dispatch to `cmd module install` handling code. This is error prone and
1897 /// We could instead use [`Command::replace`] so that, when the user types `cmd
1898 /// install`, `clap` will replace `install` with `module install` which will
1899 /// end up getting parsed as if the user typed the entire incantation.
1902 /// # use clap::Command;
1903 /// let m = Command::new("cmd")
1904 /// .subcommand(Command::new("module")
1905 /// .subcommand(Command::new("install")))
1906 /// .replace("install", &["module", "install"])
1907 /// .get_matches_from(vec!["cmd", "install"]);
1909 /// assert!(m.subcommand_matches("module").is_some());
1910 /// assert!(m.subcommand_matches("module").unwrap().subcommand_matches("install").is_some());
1913 /// Now let's show an argument example!
1915 /// Let's assume we have an application with two flags `--save-context` and
1916 /// `--save-runtime`. But often users end up needing to do *both* at the
1917 /// same time. We can add a third flag `--save-all` which semantically means
1918 /// the same thing as `cmd --save-context --save-runtime`. To implement that,
1919 /// we have several options.
1921 /// We could create this third argument and manually check if that argument
1922 /// and in our own consumer code handle the fact that both `--save-context`
1923 /// and `--save-runtime` *should* have been used. But again this is error
1924 /// prone and tedious. If we had code relying on checking `--save-context`
1925 /// and we forgot to update that code to *also* check `--save-all` it'd mean
1928 /// Luckily we can use [`Command::replace`] so that when the user types
1929 /// `--save-all`, `clap` will replace that argument with `--save-context
1930 /// --save-runtime`, and parsing will continue like normal. Now all our code
1931 /// that was originally checking for things like `--save-context` doesn't
1935 /// # use clap::{Command, Arg, ArgAction};
1936 /// let m = Command::new("cmd")
1937 /// .arg(Arg::new("save-context")
1938 /// .long("save-context")
1939 /// .action(ArgAction::SetTrue))
1940 /// .arg(Arg::new("save-runtime")
1941 /// .long("save-runtime")
1942 /// .action(ArgAction::SetTrue))
1943 /// .replace("--save-all", &["--save-context", "--save-runtime"])
1944 /// .get_matches_from(vec!["cmd", "--save-all"]);
1946 /// assert!(m.get_flag("save-context"));
1947 /// assert!(m.get_flag("save-runtime"));
1950 /// This can also be used with options, for example if our application with
1951 /// `--save-*` above also had a `--format=TYPE` option. Let's say it
1952 /// accepted `txt` or `json` values. However, when `--save-all` is used,
1953 /// only `--format=json` is allowed, or valid. We could change the example
1954 /// above to enforce this:
1957 /// # use clap::{Command, Arg, ArgAction};
1958 /// let m = Command::new("cmd")
1959 /// .arg(Arg::new("save-context")
1960 /// .long("save-context")
1961 /// .action(ArgAction::SetTrue))
1962 /// .arg(Arg::new("save-runtime")
1963 /// .long("save-runtime")
1964 /// .action(ArgAction::SetTrue))
1965 /// .arg(Arg::new("format")
1967 /// .action(ArgAction::Set)
1968 /// .value_parser(["txt", "json"]))
1969 /// .replace("--save-all", &["--save-context", "--save-runtime", "--format=json"])
1970 /// .get_matches_from(vec!["cmd", "--save-all"]);
1972 /// assert!(m.get_flag("save-context"));
1973 /// assert!(m.get_flag("save-runtime"));
1974 /// assert_eq!(m.get_one::<String>("format").unwrap(), "json");
1977 /// [`Command::replace`]: Command::replace()
1979 #[cfg(feature = "unstable-replace")]
1983 name
: impl Into
<Str
>,
1984 target
: impl IntoIterator
<Item
= impl Into
<Str
>>,
1987 .insert(name
.into(), target
.into_iter().map(Into
::into
).collect());
1991 /// Exit gracefully if no arguments are present (e.g. `$ myprog`).
1993 /// **NOTE:** [`subcommands`] count as arguments
1998 /// # use clap::{Command};
1999 /// Command::new("myprog")
2000 /// .arg_required_else_help(true);
2003 /// [`subcommands`]: crate::Command::subcommand()
2004 /// [`Arg::default_value`]: crate::Arg::default_value()
2006 pub fn arg_required_else_help(self, yes
: bool
) -> Self {
2008 self.setting(AppSettings
::ArgRequiredElseHelp
)
2010 self.unset_setting(AppSettings
::ArgRequiredElseHelp
)
2016 feature
= "deprecated",
2017 deprecated(since
= "4.0.0", note
= "Replaced with `Arg::allow_hyphen_values`")
2019 pub fn allow_hyphen_values(self, yes
: bool
) -> Self {
2021 self.setting(AppSettings
::AllowHyphenValues
)
2023 self.unset_setting(AppSettings
::AllowHyphenValues
)
2029 feature
= "deprecated",
2030 deprecated(since
= "4.0.0", note
= "Replaced with `Arg::allow_negative_numbers`")
2032 pub fn allow_negative_numbers(self, yes
: bool
) -> Self {
2034 self.setting(AppSettings
::AllowNegativeNumbers
)
2036 self.unset_setting(AppSettings
::AllowNegativeNumbers
)
2042 feature
= "deprecated",
2043 deprecated(since
= "4.0.0", note
= "Replaced with `Arg::trailing_var_arg`")
2045 pub fn trailing_var_arg(self, yes
: bool
) -> Self {
2047 self.setting(AppSettings
::TrailingVarArg
)
2049 self.unset_setting(AppSettings
::TrailingVarArg
)
2053 /// Allows one to implement two styles of CLIs where positionals can be used out of order.
2055 /// The first example is a CLI where the second to last positional argument is optional, but
2056 /// the final positional argument is required. Such as `$ prog [optional] <required>` where one
2057 /// of the two following usages is allowed:
2059 /// * `$ prog [optional] <required>`
2060 /// * `$ prog <required>`
2062 /// This would otherwise not be allowed. This is useful when `[optional]` has a default value.
2064 /// **Note:** when using this style of "missing positionals" the final positional *must* be
2065 /// [required] if `--` will not be used to skip to the final positional argument.
2067 /// **Note:** This style also only allows a single positional argument to be "skipped" without
2068 /// the use of `--`. To skip more than one, see the second example.
2070 /// The second example is when one wants to skip multiple optional positional arguments, and use
2071 /// of the `--` operator is OK (but not required if all arguments will be specified anyways).
2073 /// For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where
2074 /// `baz` accepts multiple values (similar to man `ARGS...` style training arguments).
2076 /// With this setting the following invocations are posisble:
2078 /// * `$ prog foo bar baz1 baz2 baz3`
2079 /// * `$ prog foo -- baz1 baz2 baz3`
2080 /// * `$ prog -- baz1 baz2 baz3`
2084 /// Style number one from above:
2087 /// # use clap::{Command, Arg};
2088 /// // Assume there is an external subcommand named "subcmd"
2089 /// let m = Command::new("myprog")
2090 /// .allow_missing_positional(true)
2091 /// .arg(Arg::new("arg1"))
2092 /// .arg(Arg::new("arg2")
2093 /// .required(true))
2094 /// .get_matches_from(vec![
2098 /// assert_eq!(m.get_one::<String>("arg1"), None);
2099 /// assert_eq!(m.get_one::<String>("arg2").unwrap(), "other");
2102 /// Now the same example, but using a default value for the first optional positional argument
2105 /// # use clap::{Command, Arg};
2106 /// // Assume there is an external subcommand named "subcmd"
2107 /// let m = Command::new("myprog")
2108 /// .allow_missing_positional(true)
2109 /// .arg(Arg::new("arg1")
2110 /// .default_value("something"))
2111 /// .arg(Arg::new("arg2")
2112 /// .required(true))
2113 /// .get_matches_from(vec![
2117 /// assert_eq!(m.get_one::<String>("arg1").unwrap(), "something");
2118 /// assert_eq!(m.get_one::<String>("arg2").unwrap(), "other");
2121 /// Style number two from above:
2124 /// # use clap::{Command, Arg, ArgAction};
2125 /// // Assume there is an external subcommand named "subcmd"
2126 /// let m = Command::new("myprog")
2127 /// .allow_missing_positional(true)
2128 /// .arg(Arg::new("foo"))
2129 /// .arg(Arg::new("bar"))
2130 /// .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..))
2131 /// .get_matches_from(vec![
2132 /// "prog", "foo", "bar", "baz1", "baz2", "baz3"
2135 /// assert_eq!(m.get_one::<String>("foo").unwrap(), "foo");
2136 /// assert_eq!(m.get_one::<String>("bar").unwrap(), "bar");
2137 /// assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
2140 /// Now nofice if we don't specify `foo` or `baz` but use the `--` operator.
2143 /// # use clap::{Command, Arg, ArgAction};
2144 /// // Assume there is an external subcommand named "subcmd"
2145 /// let m = Command::new("myprog")
2146 /// .allow_missing_positional(true)
2147 /// .arg(Arg::new("foo"))
2148 /// .arg(Arg::new("bar"))
2149 /// .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..))
2150 /// .get_matches_from(vec![
2151 /// "prog", "--", "baz1", "baz2", "baz3"
2154 /// assert_eq!(m.get_one::<String>("foo"), None);
2155 /// assert_eq!(m.get_one::<String>("bar"), None);
2156 /// assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
2159 /// [required]: crate::Arg::required()
2161 pub fn allow_missing_positional(self, yes
: bool
) -> Self {
2163 self.setting(AppSettings
::AllowMissingPositional
)
2165 self.unset_setting(AppSettings
::AllowMissingPositional
)
2170 /// # Subcommand-specific Settings
2172 /// Sets the short version of the subcommand flag without the preceding `-`.
2174 /// Allows the subcommand to be used as if it were an [`Arg::short`].
2179 /// # use clap::{Command, Arg, ArgAction};
2180 /// let matches = Command::new("pacman")
2182 /// Command::new("sync").short_flag('S').arg(
2183 /// Arg::new("search")
2186 /// .action(ArgAction::SetTrue)
2187 /// .help("search remote repositories for matching strings"),
2190 /// .get_matches_from(vec!["pacman", "-Ss"]);
2192 /// assert_eq!(matches.subcommand_name().unwrap(), "sync");
2193 /// let sync_matches = matches.subcommand_matches("sync").unwrap();
2194 /// assert!(sync_matches.get_flag("search"));
2196 /// [`Arg::short`]: Arg::short()
2198 pub fn short_flag(mut self, short
: impl IntoResettable
<char>) -> Self {
2199 self.short_flag
= short
.into_resettable().into_option();
2203 /// Sets the long version of the subcommand flag without the preceding `--`.
2205 /// Allows the subcommand to be used as if it were an [`Arg::long`].
2207 /// **NOTE:** Any leading `-` characters will be stripped.
2211 /// To set `long_flag` use a word containing valid UTF-8 codepoints. If you supply a double leading
2212 /// `--` such as `--sync` they will be stripped. Hyphens in the middle of the word; however,
2213 /// will *not* be stripped (i.e. `sync-file` is allowed).
2216 /// # use clap::{Command, Arg, ArgAction};
2217 /// let matches = Command::new("pacman")
2219 /// Command::new("sync").long_flag("sync").arg(
2220 /// Arg::new("search")
2223 /// .action(ArgAction::SetTrue)
2224 /// .help("search remote repositories for matching strings"),
2227 /// .get_matches_from(vec!["pacman", "--sync", "--search"]);
2229 /// assert_eq!(matches.subcommand_name().unwrap(), "sync");
2230 /// let sync_matches = matches.subcommand_matches("sync").unwrap();
2231 /// assert!(sync_matches.get_flag("search"));
2234 /// [`Arg::long`]: Arg::long()
2236 pub fn long_flag(mut self, long
: impl Into
<Str
>) -> Self {
2237 self.long_flag
= Some(long
.into());
2241 /// Sets a hidden alias to this subcommand.
2243 /// This allows the subcommand to be accessed via *either* the original name, or this given
2244 /// alias. This is more efficient and easier than creating multiple hidden subcommands as one
2245 /// only needs to check for the existence of this command, and not all aliased variants.
2247 /// **NOTE:** Aliases defined with this method are *hidden* from the help
2248 /// message. If you're looking for aliases that will be displayed in the help
2249 /// message, see [`Command::visible_alias`].
2251 /// **NOTE:** When using aliases and checking for the existence of a
2252 /// particular subcommand within an [`ArgMatches`] struct, one only needs to
2253 /// search for the original name and not all aliases.
2258 /// # use clap::{Command, Arg, };
2259 /// let m = Command::new("myprog")
2260 /// .subcommand(Command::new("test")
2261 /// .alias("do-stuff"))
2262 /// .get_matches_from(vec!["myprog", "do-stuff"]);
2263 /// assert_eq!(m.subcommand_name(), Some("test"));
2265 /// [`Command::visible_alias`]: Command::visible_alias()
2267 pub fn alias(mut self, name
: impl IntoResettable
<Str
>) -> Self {
2268 if let Some(name
) = name
.into_resettable().into_option() {
2269 self.aliases
.push((name
, false));
2271 self.aliases
.clear();
2276 /// Add an alias, which functions as "hidden" short flag subcommand
2278 /// This will automatically dispatch as if this subcommand was used. This is more efficient,
2279 /// and easier than creating multiple hidden subcommands as one only needs to check for the
2280 /// existence of this command, and not all variants.
2285 /// # use clap::{Command, Arg, };
2286 /// let m = Command::new("myprog")
2287 /// .subcommand(Command::new("test").short_flag('t')
2288 /// .short_flag_alias('d'))
2289 /// .get_matches_from(vec!["myprog", "-d"]);
2290 /// assert_eq!(m.subcommand_name(), Some("test"));
2293 pub fn short_flag_alias(mut self, name
: impl IntoResettable
<char>) -> Self {
2294 if let Some(name
) = name
.into_resettable().into_option() {
2295 debug_assert
!(name
!= '
-'
, "short alias name cannot be `-`");
2296 self.short_flag_aliases
.push((name
, false));
2298 self.short_flag_aliases
.clear();
2303 /// Add an alias, which functions as a "hidden" long flag subcommand.
2305 /// This will automatically dispatch as if this subcommand was used. This is more efficient,
2306 /// and easier than creating multiple hidden subcommands as one only needs to check for the
2307 /// existence of this command, and not all variants.
2312 /// # use clap::{Command, Arg, };
2313 /// let m = Command::new("myprog")
2314 /// .subcommand(Command::new("test").long_flag("test")
2315 /// .long_flag_alias("testing"))
2316 /// .get_matches_from(vec!["myprog", "--testing"]);
2317 /// assert_eq!(m.subcommand_name(), Some("test"));
2320 pub fn long_flag_alias(mut self, name
: impl IntoResettable
<Str
>) -> Self {
2321 if let Some(name
) = name
.into_resettable().into_option() {
2322 self.long_flag_aliases
.push((name
, false));
2324 self.long_flag_aliases
.clear();
2329 /// Sets multiple hidden aliases to this subcommand.
2331 /// This allows the subcommand to be accessed via *either* the original name or any of the
2332 /// given aliases. This is more efficient, and easier than creating multiple hidden subcommands
2333 /// as one only needs to check for the existence of this command and not all aliased variants.
2335 /// **NOTE:** Aliases defined with this method are *hidden* from the help
2336 /// message. If looking for aliases that will be displayed in the help
2337 /// message, see [`Command::visible_aliases`].
2339 /// **NOTE:** When using aliases and checking for the existence of a
2340 /// particular subcommand within an [`ArgMatches`] struct, one only needs to
2341 /// search for the original name and not all aliases.
2346 /// # use clap::{Command, Arg};
2347 /// let m = Command::new("myprog")
2348 /// .subcommand(Command::new("test")
2349 /// .aliases(["do-stuff", "do-tests", "tests"]))
2350 /// .arg(Arg::new("input")
2351 /// .help("the file to add")
2352 /// .required(false))
2353 /// .get_matches_from(vec!["myprog", "do-tests"]);
2354 /// assert_eq!(m.subcommand_name(), Some("test"));
2356 /// [`Command::visible_aliases`]: Command::visible_aliases()
2358 pub fn aliases(mut self, names
: impl IntoIterator
<Item
= impl Into
<Str
>>) -> Self {
2360 .extend(names
.into_iter().map(|n
| (n
.into(), false)));
2364 /// Add aliases, which function as "hidden" short flag subcommands.
2366 /// These will automatically dispatch as if this subcommand was used. This is more efficient,
2367 /// and easier than creating multiple hidden subcommands as one only needs to check for the
2368 /// existence of this command, and not all variants.
2373 /// # use clap::{Command, Arg, };
2374 /// let m = Command::new("myprog")
2375 /// .subcommand(Command::new("test").short_flag('t')
2376 /// .short_flag_aliases(['a', 'b', 'c']))
2377 /// .arg(Arg::new("input")
2378 /// .help("the file to add")
2379 /// .required(false))
2380 /// .get_matches_from(vec!["myprog", "-a"]);
2381 /// assert_eq!(m.subcommand_name(), Some("test"));
2384 pub fn short_flag_aliases(mut self, names
: impl IntoIterator
<Item
= char>) -> Self {
2386 debug_assert
!(s
!= '
-'
, "short alias name cannot be `-`");
2387 self.short_flag_aliases
.push((s
, false));
2392 /// Add aliases, which function as "hidden" long flag subcommands.
2394 /// These will automatically dispatch as if this subcommand was used. This is more efficient,
2395 /// and easier than creating multiple hidden subcommands as one only needs to check for the
2396 /// existence of this command, and not all variants.
2401 /// # use clap::{Command, Arg, };
2402 /// let m = Command::new("myprog")
2403 /// .subcommand(Command::new("test").long_flag("test")
2404 /// .long_flag_aliases(["testing", "testall", "test_all"]))
2405 /// .arg(Arg::new("input")
2406 /// .help("the file to add")
2407 /// .required(false))
2408 /// .get_matches_from(vec!["myprog", "--testing"]);
2409 /// assert_eq!(m.subcommand_name(), Some("test"));
2412 pub fn long_flag_aliases(mut self, names
: impl IntoIterator
<Item
= impl Into
<Str
>>) -> Self {
2414 self = self.long_flag_alias(s
)
2419 /// Sets a visible alias to this subcommand.
2421 /// This allows the subcommand to be accessed via *either* the
2422 /// original name or the given alias. This is more efficient and easier
2423 /// than creating hidden subcommands as one only needs to check for
2424 /// the existence of this command and not all aliased variants.
2426 /// **NOTE:** The alias defined with this method is *visible* from the help
2427 /// message and displayed as if it were just another regular subcommand. If
2428 /// looking for an alias that will not be displayed in the help message, see
2429 /// [`Command::alias`].
2431 /// **NOTE:** When using aliases and checking for the existence of a
2432 /// particular subcommand within an [`ArgMatches`] struct, one only needs to
2433 /// search for the original name and not all aliases.
2438 /// # use clap::{Command, Arg};
2439 /// let m = Command::new("myprog")
2440 /// .subcommand(Command::new("test")
2441 /// .visible_alias("do-stuff"))
2442 /// .get_matches_from(vec!["myprog", "do-stuff"]);
2443 /// assert_eq!(m.subcommand_name(), Some("test"));
2445 /// [`Command::alias`]: Command::alias()
2447 pub fn visible_alias(mut self, name
: impl IntoResettable
<Str
>) -> Self {
2448 if let Some(name
) = name
.into_resettable().into_option() {
2449 self.aliases
.push((name
, true));
2451 self.aliases
.clear();
2456 /// Add an alias, which functions as "visible" short flag subcommand
2458 /// This will automatically dispatch as if this subcommand was used. This is more efficient,
2459 /// and easier than creating multiple hidden subcommands as one only needs to check for the
2460 /// existence of this command, and not all variants.
2462 /// See also [`Command::short_flag_alias`].
2467 /// # use clap::{Command, Arg, };
2468 /// let m = Command::new("myprog")
2469 /// .subcommand(Command::new("test").short_flag('t')
2470 /// .visible_short_flag_alias('d'))
2471 /// .get_matches_from(vec!["myprog", "-d"]);
2472 /// assert_eq!(m.subcommand_name(), Some("test"));
2474 /// [`Command::short_flag_alias`]: Command::short_flag_alias()
2476 pub fn visible_short_flag_alias(mut self, name
: impl IntoResettable
<char>) -> Self {
2477 if let Some(name
) = name
.into_resettable().into_option() {
2478 debug_assert
!(name
!= '
-'
, "short alias name cannot be `-`");
2479 self.short_flag_aliases
.push((name
, true));
2481 self.short_flag_aliases
.clear();
2486 /// Add an alias, which functions as a "visible" long flag subcommand.
2488 /// This will automatically dispatch as if this subcommand was used. This is more efficient,
2489 /// and easier than creating multiple hidden subcommands as one only needs to check for the
2490 /// existence of this command, and not all variants.
2492 /// See also [`Command::long_flag_alias`].
2497 /// # use clap::{Command, Arg, };
2498 /// let m = Command::new("myprog")
2499 /// .subcommand(Command::new("test").long_flag("test")
2500 /// .visible_long_flag_alias("testing"))
2501 /// .get_matches_from(vec!["myprog", "--testing"]);
2502 /// assert_eq!(m.subcommand_name(), Some("test"));
2504 /// [`Command::long_flag_alias`]: Command::long_flag_alias()
2506 pub fn visible_long_flag_alias(mut self, name
: impl IntoResettable
<Str
>) -> Self {
2507 if let Some(name
) = name
.into_resettable().into_option() {
2508 self.long_flag_aliases
.push((name
, true));
2510 self.long_flag_aliases
.clear();
2515 /// Sets multiple visible aliases to this subcommand.
2517 /// This allows the subcommand to be accessed via *either* the
2518 /// original name or any of the given aliases. This is more efficient and easier
2519 /// than creating multiple hidden subcommands as one only needs to check for
2520 /// the existence of this command and not all aliased variants.
2522 /// **NOTE:** The alias defined with this method is *visible* from the help
2523 /// message and displayed as if it were just another regular subcommand. If
2524 /// looking for an alias that will not be displayed in the help message, see
2525 /// [`Command::alias`].
2527 /// **NOTE:** When using aliases, and checking for the existence of a
2528 /// particular subcommand within an [`ArgMatches`] struct, one only needs to
2529 /// search for the original name and not all aliases.
2534 /// # use clap::{Command, Arg, };
2535 /// let m = Command::new("myprog")
2536 /// .subcommand(Command::new("test")
2537 /// .visible_aliases(["do-stuff", "tests"]))
2538 /// .get_matches_from(vec!["myprog", "do-stuff"]);
2539 /// assert_eq!(m.subcommand_name(), Some("test"));
2541 /// [`Command::alias`]: Command::alias()
2543 pub fn visible_aliases(mut self, names
: impl IntoIterator
<Item
= impl Into
<Str
>>) -> Self {
2545 .extend(names
.into_iter().map(|n
| (n
.into(), true)));
2549 /// Add aliases, which function as *visible* short flag subcommands.
2551 /// See [`Command::short_flag_aliases`].
2556 /// # use clap::{Command, Arg, };
2557 /// let m = Command::new("myprog")
2558 /// .subcommand(Command::new("test").short_flag('b')
2559 /// .visible_short_flag_aliases(['t']))
2560 /// .get_matches_from(vec!["myprog", "-t"]);
2561 /// assert_eq!(m.subcommand_name(), Some("test"));
2563 /// [`Command::short_flag_aliases`]: Command::short_flag_aliases()
2565 pub fn visible_short_flag_aliases(mut self, names
: impl IntoIterator
<Item
= char>) -> Self {
2567 debug_assert
!(s
!= '
-'
, "short alias name cannot be `-`");
2568 self.short_flag_aliases
.push((s
, true));
2573 /// Add aliases, which function as *visible* long flag subcommands.
2575 /// See [`Command::long_flag_aliases`].
2580 /// # use clap::{Command, Arg, };
2581 /// let m = Command::new("myprog")
2582 /// .subcommand(Command::new("test").long_flag("test")
2583 /// .visible_long_flag_aliases(["testing", "testall", "test_all"]))
2584 /// .get_matches_from(vec!["myprog", "--testing"]);
2585 /// assert_eq!(m.subcommand_name(), Some("test"));
2587 /// [`Command::long_flag_aliases`]: Command::long_flag_aliases()
2589 pub fn visible_long_flag_aliases(
2591 names
: impl IntoIterator
<Item
= impl Into
<Str
>>,
2594 self = self.visible_long_flag_alias(s
);
2599 /// Set the placement of this subcommand within the help.
2601 /// Subcommands with a lower value will be displayed first in the help message. Subcommands
2602 /// with duplicate display orders will be displayed in alphabetical order.
2604 /// This is helpful when one would like to emphasize frequently used subcommands, or prioritize
2605 /// those towards the top of the list.
2607 /// **NOTE:** The default is 999 for all subcommands.
2611 #[cfg_attr(not(feature = "help"), doc = " ```ignore")]
2612 #[cfg_attr(feature = "help", doc = " ```")]
2613 /// # use clap::{Command, };
2614 /// let m = Command::new("cust-ord")
2615 /// .subcommand(Command::new("alpha") // typically subcommands are grouped
2616 /// // alphabetically by name. Subcommands
2617 /// // without a display_order have a value of
2618 /// // 999 and are displayed alphabetically with
2619 /// // all other 999 subcommands
2620 /// .about("Some help and text"))
2621 /// .subcommand(Command::new("beta")
2622 /// .display_order(1) // In order to force this subcommand to appear *first*
2623 /// // all we have to do is give it a value lower than 999.
2624 /// // Any other subcommands with a value of 1 will be displayed
2625 /// // alphabetically with this one...then 2 values, then 3, etc.
2626 /// .about("I should be first!"))
2627 /// .get_matches_from(vec![
2628 /// "cust-ord", "--help"
2632 /// The above example displays the following help message
2637 /// Usage: cust-ord [OPTIONS]
2640 /// beta I should be first!
2641 /// alpha Some help and text
2644 /// -h, --help Print help
2645 /// -V, --version Print version
2649 pub fn display_order(mut self, ord
: impl IntoResettable
<usize>) -> Self {
2650 self.disp_ord
= ord
.into_resettable().into_option();
2654 /// Specifies that this [`subcommand`] should be hidden from help messages
2659 /// # use clap::{Command, Arg};
2660 /// Command::new("myprog")
2662 /// Command::new("test").hide(true)
2667 /// [`subcommand`]: crate::Command::subcommand()
2669 pub fn hide(self, yes
: bool
) -> Self {
2671 self.setting(AppSettings
::Hidden
)
2673 self.unset_setting(AppSettings
::Hidden
)
2677 /// If no [`subcommand`] is present at runtime, error and exit gracefully.
2682 /// # use clap::{Command, error::ErrorKind};
2683 /// let err = Command::new("myprog")
2684 /// .subcommand_required(true)
2685 /// .subcommand(Command::new("test"))
2686 /// .try_get_matches_from(vec![
2689 /// assert!(err.is_err());
2690 /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand);
2694 /// [`subcommand`]: crate::Command::subcommand()
2695 pub fn subcommand_required(self, yes
: bool
) -> Self {
2697 self.setting(AppSettings
::SubcommandRequired
)
2699 self.unset_setting(AppSettings
::SubcommandRequired
)
2703 /// Assume unexpected positional arguments are a [`subcommand`].
2705 /// Arguments will be stored in the `""` argument in the [`ArgMatches`]
2707 /// **NOTE:** Use this setting with caution,
2708 /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand)
2709 /// will **not** cause an error and instead be treated as a potential subcommand.
2710 /// One should check for such cases manually and inform the user appropriately.
2712 /// **NOTE:** A built-in subcommand will be parsed as an external subcommand when escaped with
2718 /// # use std::ffi::OsString;
2719 /// # use clap::Command;
2720 /// // Assume there is an external subcommand named "subcmd"
2721 /// let m = Command::new("myprog")
2722 /// .allow_external_subcommands(true)
2723 /// .get_matches_from(vec![
2724 /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
2727 /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
2728 /// // string argument name
2729 /// match m.subcommand() {
2730 /// Some((external, ext_m)) => {
2731 /// let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect();
2732 /// assert_eq!(external, "subcmd");
2733 /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
2739 /// [`subcommand`]: crate::Command::subcommand()
2740 /// [`ArgMatches`]: crate::ArgMatches
2741 /// [`ErrorKind::UnknownArgument`]: crate::error::ErrorKind::UnknownArgument
2742 pub fn allow_external_subcommands(self, yes
: bool
) -> Self {
2744 self.setting(AppSettings
::AllowExternalSubcommands
)
2746 self.unset_setting(AppSettings
::AllowExternalSubcommands
)
2750 /// Specifies how to parse external subcommand arguments.
2752 /// The default parser is for `OsString`. This can be used to switch it to `String` or another
2755 /// **NOTE:** Setting this requires [`Command::allow_external_subcommands`]
2759 #[cfg_attr(not(unix), doc = " ```ignore")]
2760 #[cfg_attr(unix, doc = " ```")]
2761 /// # use std::ffi::OsString;
2762 /// # use clap::Command;
2763 /// # use clap::value_parser;
2764 /// // Assume there is an external subcommand named "subcmd"
2765 /// let m = Command::new("myprog")
2766 /// .allow_external_subcommands(true)
2767 /// .get_matches_from(vec![
2768 /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
2771 /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
2772 /// // string argument name
2773 /// match m.subcommand() {
2774 /// Some((external, ext_m)) => {
2775 /// let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect();
2776 /// assert_eq!(external, "subcmd");
2777 /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
2784 /// # use clap::Command;
2785 /// # use clap::value_parser;
2786 /// // Assume there is an external subcommand named "subcmd"
2787 /// let m = Command::new("myprog")
2788 /// .external_subcommand_value_parser(value_parser!(String))
2789 /// .get_matches_from(vec![
2790 /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
2793 /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
2794 /// // string argument name
2795 /// match m.subcommand() {
2796 /// Some((external, ext_m)) => {
2797 /// let ext_args: Vec<_> = ext_m.get_many::<String>("").unwrap().collect();
2798 /// assert_eq!(external, "subcmd");
2799 /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
2805 /// [`subcommands`]: crate::Command::subcommand()
2806 pub fn external_subcommand_value_parser(
2808 parser
: impl IntoResettable
<super::ValueParser
>,
2810 self.external_value_parser
= parser
.into_resettable().into_option();
2814 /// Specifies that use of an argument prevents the use of [`subcommands`].
2816 /// By default `clap` allows arguments between subcommands such
2817 /// as `<cmd> [cmd_args] <subcmd> [subcmd_args] <subsubcmd> [subsubcmd_args]`.
2819 /// This setting disables that functionality and says that arguments can
2820 /// only follow the *final* subcommand. For instance using this setting
2821 /// makes only the following invocations possible:
2823 /// * `<cmd> <subcmd> <subsubcmd> [subsubcmd_args]`
2824 /// * `<cmd> <subcmd> [subcmd_args]`
2825 /// * `<cmd> [cmd_args]`
2830 /// # use clap::Command;
2831 /// Command::new("myprog")
2832 /// .args_conflicts_with_subcommands(true);
2835 /// [`subcommands`]: crate::Command::subcommand()
2836 pub fn args_conflicts_with_subcommands(self, yes
: bool
) -> Self {
2838 self.setting(AppSettings
::ArgsNegateSubcommands
)
2840 self.unset_setting(AppSettings
::ArgsNegateSubcommands
)
2844 /// Prevent subcommands from being consumed as an arguments value.
2846 /// By default, if an option taking multiple values is followed by a subcommand, the
2847 /// subcommand will be parsed as another value.
2850 /// cmd --foo val1 val2 subcommand
2851 /// --------- ----------
2852 /// values another value
2855 /// This setting instructs the parser to stop when encountering a subcommand instead of
2856 /// greedily consuming arguments.
2859 /// cmd --foo val1 val2 subcommand
2860 /// --------- ----------
2861 /// values subcommand
2867 /// # use clap::{Command, Arg, ArgAction};
2868 /// let cmd = Command::new("cmd").subcommand(Command::new("sub")).arg(
2872 /// .action(ArgAction::Set),
2875 /// let matches = cmd
2877 /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
2880 /// matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(),
2881 /// &["1", "2", "3", "sub"]
2883 /// assert!(matches.subcommand_matches("sub").is_none());
2885 /// let matches = cmd
2886 /// .subcommand_precedence_over_arg(true)
2887 /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
2890 /// matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(),
2891 /// &["1", "2", "3"]
2893 /// assert!(matches.subcommand_matches("sub").is_some());
2895 pub fn subcommand_precedence_over_arg(self, yes
: bool
) -> Self {
2897 self.setting(AppSettings
::SubcommandPrecedenceOverArg
)
2899 self.unset_setting(AppSettings
::SubcommandPrecedenceOverArg
)
2903 /// Allows [`subcommands`] to override all requirements of the parent command.
2905 /// For example, if you had a subcommand or top level application with a required argument
2906 /// that is only required as long as there is no subcommand present,
2907 /// using this setting would allow you to set those arguments to [`Arg::required(true)`]
2908 /// and yet receive no error so long as the user uses a valid subcommand instead.
2910 /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements)
2914 /// This first example shows that it is an error to not use a required argument
2917 /// # use clap::{Command, Arg, error::ErrorKind};
2918 /// let err = Command::new("myprog")
2919 /// .subcommand_negates_reqs(true)
2920 /// .arg(Arg::new("opt").required(true))
2921 /// .subcommand(Command::new("test"))
2922 /// .try_get_matches_from(vec![
2925 /// assert!(err.is_err());
2926 /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
2930 /// This next example shows that it is no longer error to not use a required argument if a
2931 /// valid subcommand is used.
2934 /// # use clap::{Command, Arg, error::ErrorKind};
2935 /// let noerr = Command::new("myprog")
2936 /// .subcommand_negates_reqs(true)
2937 /// .arg(Arg::new("opt").required(true))
2938 /// .subcommand(Command::new("test"))
2939 /// .try_get_matches_from(vec![
2940 /// "myprog", "test"
2942 /// assert!(noerr.is_ok());
2946 /// [`Arg::required(true)`]: crate::Arg::required()
2947 /// [`subcommands`]: crate::Command::subcommand()
2948 pub fn subcommand_negates_reqs(self, yes
: bool
) -> Self {
2950 self.setting(AppSettings
::SubcommandsNegateReqs
)
2952 self.unset_setting(AppSettings
::SubcommandsNegateReqs
)
2956 /// Multiple-personality program dispatched on the binary name (`argv[0]`)
2958 /// A "multicall" executable is a single executable
2959 /// that contains a variety of applets,
2960 /// and decides which applet to run based on the name of the file.
2961 /// The executable can be called from different names by creating hard links
2962 /// or symbolic links to it.
2964 /// This is desirable for:
2965 /// - Easy distribution, a single binary that can install hardlinks to access the different
2967 /// - Minimal binary size by sharing common code (e.g. standard library, clap)
2968 /// - Custom shells or REPLs where there isn't a single top-level command
2970 /// Setting `multicall` will cause
2971 /// - `argv[0]` to be stripped to the base name and parsed as the first argument, as if
2972 /// [`Command::no_binary_name`][Command::no_binary_name] was set.
2973 /// - Help and errors to report subcommands as if they were the top-level command
2975 /// When the subcommand is not present, there are several strategies you may employ, depending
2977 /// - Let the error percolate up normally
2978 /// - Print a specialized error message using the
2979 /// [`Error::context`][crate::Error::context]
2980 /// - Print the [help][Command::write_help] but this might be ambiguous
2981 /// - Disable `multicall` and re-parse it
2982 /// - Disable `multicall` and re-parse it with a specific subcommand
2984 /// When detecting the error condition, the [`ErrorKind`] isn't sufficient as a sub-subcommand
2985 /// might report the same error. Enable
2986 /// [`allow_external_subcommands`][Command::allow_external_subcommands] if you want to specifically
2987 /// get the unrecognized binary name.
2989 /// **NOTE:** Multicall can't be used with [`no_binary_name`] since they interpret
2990 /// the command name in incompatible ways.
2992 /// **NOTE:** The multicall command cannot have arguments.
2994 /// **NOTE:** Applets are slightly semantically different from subcommands,
2995 /// so it's recommended to use [`Command::subcommand_help_heading`] and
2996 /// [`Command::subcommand_value_name`] to change the descriptive text as above.
3000 /// `hostname` is an example of a multicall executable.
3001 /// Both `hostname` and `dnsdomainname` are provided by the same executable
3002 /// and which behaviour to use is based on the executable file name.
3004 /// This is desirable when the executable has a primary purpose
3005 /// but there is related functionality that would be convenient to provide
3006 /// and implement it to be in the same executable.
3008 /// The name of the cmd is essentially unused
3009 /// and may be the same as the name of a subcommand.
3011 /// The names of the immediate subcommands of the Command
3012 /// are matched against the basename of the first argument,
3013 /// which is conventionally the path of the executable.
3015 /// This does not allow the subcommand to be passed as the first non-path argument.
3018 /// # use clap::{Command, error::ErrorKind};
3019 /// let mut cmd = Command::new("hostname")
3020 /// .multicall(true)
3021 /// .subcommand(Command::new("hostname"))
3022 /// .subcommand(Command::new("dnsdomainname"));
3023 /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/hostname", "dnsdomainname"]);
3024 /// assert!(m.is_err());
3025 /// assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument);
3026 /// let m = cmd.get_matches_from(&["/usr/bin/dnsdomainname"]);
3027 /// assert_eq!(m.subcommand_name(), Some("dnsdomainname"));
3030 /// Busybox is another common example of a multicall executable
3031 /// with a subcommmand for each applet that can be run directly,
3032 /// e.g. with the `cat` applet being run by running `busybox cat`,
3033 /// or with `cat` as a link to the `busybox` binary.
3035 /// This is desirable when the launcher program has additional options
3036 /// or it is useful to run the applet without installing a symlink
3037 /// e.g. to test the applet without installing it
3038 /// or there may already be a command of that name installed.
3040 /// To make an applet usable as both a multicall link and a subcommand
3041 /// the subcommands must be defined both in the top-level Command
3042 /// and as subcommands of the "main" applet.
3045 /// # use clap::Command;
3046 /// fn applet_commands() -> [Command; 2] {
3047 /// [Command::new("true"), Command::new("false")]
3049 /// let mut cmd = Command::new("busybox")
3050 /// .multicall(true)
3052 /// Command::new("busybox")
3053 /// .subcommand_value_name("APPLET")
3054 /// .subcommand_help_heading("APPLETS")
3055 /// .subcommands(applet_commands()),
3057 /// .subcommands(applet_commands());
3058 /// // When called from the executable's canonical name
3059 /// // its applets can be matched as subcommands.
3060 /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/busybox", "true"]).unwrap();
3061 /// assert_eq!(m.subcommand_name(), Some("busybox"));
3062 /// assert_eq!(m.subcommand().unwrap().1.subcommand_name(), Some("true"));
3063 /// // When called from a link named after an applet that applet is matched.
3064 /// let m = cmd.get_matches_from(&["/usr/bin/true"]);
3065 /// assert_eq!(m.subcommand_name(), Some("true"));
3068 /// [`no_binary_name`]: crate::Command::no_binary_name
3069 /// [`Command::subcommand_value_name`]: crate::Command::subcommand_value_name
3070 /// [`Command::subcommand_help_heading`]: crate::Command::subcommand_help_heading
3072 pub fn multicall(self, yes
: bool
) -> Self {
3074 self.setting(AppSettings
::Multicall
)
3076 self.unset_setting(AppSettings
::Multicall
)
3080 /// Sets the value name used for subcommands when printing usage and help.
3082 /// By default, this is "COMMAND".
3084 /// See also [`Command::subcommand_help_heading`]
3089 /// # use clap::{Command, Arg};
3090 /// Command::new("myprog")
3091 /// .subcommand(Command::new("sub1"))
3101 /// Usage: myprog [COMMAND]
3104 /// help Print this message or the help of the given subcommand(s)
3108 /// -h, --help Print help
3109 /// -V, --version Print version
3112 /// but usage of `subcommand_value_name`
3115 /// # use clap::{Command, Arg};
3116 /// Command::new("myprog")
3117 /// .subcommand(Command::new("sub1"))
3118 /// .subcommand_value_name("THING")
3128 /// Usage: myprog [THING]
3131 /// help Print this message or the help of the given subcommand(s)
3135 /// -h, --help Print help
3136 /// -V, --version Print version
3139 pub fn subcommand_value_name(mut self, value_name
: impl IntoResettable
<Str
>) -> Self {
3140 self.subcommand_value_name
= value_name
.into_resettable().into_option();
3144 /// Sets the help heading used for subcommands when printing usage and help.
3146 /// By default, this is "Commands".
3148 /// See also [`Command::subcommand_value_name`]
3153 /// # use clap::{Command, Arg};
3154 /// Command::new("myprog")
3155 /// .subcommand(Command::new("sub1"))
3165 /// Usage: myprog [COMMAND]
3168 /// help Print this message or the help of the given subcommand(s)
3172 /// -h, --help Print help
3173 /// -V, --version Print version
3176 /// but usage of `subcommand_help_heading`
3179 /// # use clap::{Command, Arg};
3180 /// Command::new("myprog")
3181 /// .subcommand(Command::new("sub1"))
3182 /// .subcommand_help_heading("Things")
3192 /// Usage: myprog [COMMAND]
3195 /// help Print this message or the help of the given subcommand(s)
3199 /// -h, --help Print help
3200 /// -V, --version Print version
3203 pub fn subcommand_help_heading(mut self, heading
: impl IntoResettable
<Str
>) -> Self {
3204 self.subcommand_heading
= heading
.into_resettable().into_option();
3212 #[cfg(feature = "usage")]
3213 pub(crate) fn get_usage_name(&self) -> Option
<&str> {
3214 self.usage_name
.as_deref()
3217 /// Get the name of the binary.
3219 pub fn get_display_name(&self) -> Option
<&str> {
3220 self.display_name
.as_deref()
3223 /// Get the name of the binary.
3225 pub fn get_bin_name(&self) -> Option
<&str> {
3226 self.bin_name
.as_deref()
3229 /// Set binary name. Uses `&mut self` instead of `self`.
3230 pub fn set_bin_name(&mut self, name
: impl Into
<String
>) {
3231 self.bin_name
= Some(name
.into());
3234 /// Get the name of the cmd.
3236 pub fn get_name(&self) -> &str {
3241 #[cfg(debug_assertions)]
3242 pub(crate) fn get_name_str(&self) -> &Str
{
3246 /// Get the version of the cmd.
3248 pub fn get_version(&self) -> Option
<&str> {
3249 self.version
.as_deref()
3252 /// Get the long version of the cmd.
3254 pub fn get_long_version(&self) -> Option
<&str> {
3255 self.long_version
.as_deref()
3258 /// Get the authors of the cmd.
3260 pub fn get_author(&self) -> Option
<&str> {
3261 self.author
.as_deref()
3264 /// Get the short flag of the subcommand.
3266 pub fn get_short_flag(&self) -> Option
<char> {
3270 /// Get the long flag of the subcommand.
3272 pub fn get_long_flag(&self) -> Option
<&str> {
3273 self.long_flag
.as_deref()
3276 /// Get the help message specified via [`Command::about`].
3278 /// [`Command::about`]: Command::about()
3280 pub fn get_about(&self) -> Option
<&StyledStr
> {
3284 /// Get the help message specified via [`Command::long_about`].
3286 /// [`Command::long_about`]: Command::long_about()
3288 pub fn get_long_about(&self) -> Option
<&StyledStr
> {
3289 self.long_about
.as_ref()
3292 /// Get the custom section heading specified via [`Command::next_help_heading`].
3294 /// [`Command::help_heading`]: Command::help_heading()
3296 pub fn get_next_help_heading(&self) -> Option
<&str> {
3297 self.current_help_heading
.as_deref()
3300 /// Iterate through the *visible* aliases for this subcommand.
3302 pub fn get_visible_aliases(&self) -> impl Iterator
<Item
= &str> + '_
{
3305 .filter(|(_
, vis
)| *vis
)
3306 .map(|a
| a
.0.as_str())
3309 /// Iterate through the *visible* short aliases for this subcommand.
3311 pub fn get_visible_short_flag_aliases(&self) -> impl Iterator
<Item
= char> + '_
{
3312 self.short_flag_aliases
3314 .filter(|(_
, vis
)| *vis
)
3318 /// Iterate through the *visible* long aliases for this subcommand.
3320 pub fn get_visible_long_flag_aliases(&self) -> impl Iterator
<Item
= &str> + '_
{
3321 self.long_flag_aliases
3323 .filter(|(_
, vis
)| *vis
)
3324 .map(|a
| a
.0.as_str())
3327 /// Iterate through the set of *all* the aliases for this subcommand, both visible and hidden.
3329 pub fn get_all_aliases(&self) -> impl Iterator
<Item
= &str> + '_
{
3330 self.aliases
.iter().map(|a
| a
.0.as_str())
3333 /// Iterate through the set of *all* the short aliases for this subcommand, both visible and hidden.
3335 pub fn get_all_short_flag_aliases(&self) -> impl Iterator
<Item
= char> + '_
{
3336 self.short_flag_aliases
.iter().map(|a
| a
.0)
3339 /// Iterate through the set of *all* the long aliases for this subcommand, both visible and hidden.
3341 pub fn get_all_long_flag_aliases(&self) -> impl Iterator
<Item
= &str> + '_
{
3342 self.long_flag_aliases
.iter().map(|a
| a
.0.as_str())
3346 pub(crate) fn is_set(&self, s
: AppSettings
) -> bool
{
3347 self.settings
.is_set(s
) || self.g_settings
.is_set(s
)
3350 /// Should we color the output?
3351 pub fn get_color(&self) -> ColorChoice
{
3352 debug
!("Command::color: Color setting...");
3354 if cfg
!(feature
= "color") {
3355 if self.is_set(AppSettings
::ColorNever
) {
3358 } else if self.is_set(AppSettings
::ColorAlways
) {
3370 /// Iterate through the set of subcommands, getting a reference to each.
3372 pub fn get_subcommands(&self) -> impl Iterator
<Item
= &Command
> {
3373 self.subcommands
.iter()
3376 /// Iterate through the set of subcommands, getting a mutable reference to each.
3378 pub fn get_subcommands_mut(&mut self) -> impl Iterator
<Item
= &mut Command
> {
3379 self.subcommands
.iter_mut()
3382 /// Returns `true` if this `Command` has subcommands.
3384 pub fn has_subcommands(&self) -> bool
{
3385 !self.subcommands
.is_empty()
3388 /// Returns the help heading for listing subcommands.
3390 pub fn get_subcommand_help_heading(&self) -> Option
<&str> {
3391 self.subcommand_heading
.as_deref()
3394 /// Returns the subcommand value name.
3396 pub fn get_subcommand_value_name(&self) -> Option
<&str> {
3397 self.subcommand_value_name
.as_deref()
3400 /// Returns the help heading for listing subcommands.
3402 pub fn get_before_help(&self) -> Option
<&StyledStr
> {
3403 self.before_help
.as_ref()
3406 /// Returns the help heading for listing subcommands.
3408 pub fn get_before_long_help(&self) -> Option
<&StyledStr
> {
3409 self.before_long_help
.as_ref()
3412 /// Returns the help heading for listing subcommands.
3414 pub fn get_after_help(&self) -> Option
<&StyledStr
> {
3415 self.after_help
.as_ref()
3418 /// Returns the help heading for listing subcommands.
3420 pub fn get_after_long_help(&self) -> Option
<&StyledStr
> {
3421 self.after_long_help
.as_ref()
3424 /// Find subcommand such that its name or one of aliases equals `name`.
3426 /// This does not recurse through subcommands of subcommands.
3428 pub fn find_subcommand(&self, name
: impl AsRef
<std
::ffi
::OsStr
>) -> Option
<&Command
> {
3429 let name
= name
.as_ref();
3430 self.get_subcommands().find(|s
| s
.aliases_to(name
))
3433 /// Find subcommand such that its name or one of aliases equals `name`, returning
3434 /// a mutable reference to the subcommand.
3436 /// This does not recurse through subcommands of subcommands.
3438 pub fn find_subcommand_mut(
3440 name
: impl AsRef
<std
::ffi
::OsStr
>,
3441 ) -> Option
<&mut Command
> {
3442 let name
= name
.as_ref();
3443 self.get_subcommands_mut().find(|s
| s
.aliases_to(name
))
3446 /// Iterate through the set of groups.
3448 pub fn get_groups(&self) -> impl Iterator
<Item
= &ArgGroup
> {
3452 /// Iterate through the set of arguments.
3454 pub fn get_arguments(&self) -> impl Iterator
<Item
= &Arg
> {
3458 /// Iterate through the *positionals* arguments.
3460 pub fn get_positionals(&self) -> impl Iterator
<Item
= &Arg
> {
3461 self.get_arguments().filter(|a
| a
.is_positional())
3464 /// Iterate through the *options*.
3465 pub fn get_opts(&self) -> impl Iterator
<Item
= &Arg
> {
3466 self.get_arguments()
3467 .filter(|a
| a
.is_takes_value_set() && !a
.is_positional())
3470 /// Get a list of all arguments the given argument conflicts with.
3472 /// If the provided argument is declared as global, the conflicts will be determined
3473 /// based on the propagation rules of global arguments.
3477 /// If the given arg contains a conflict with an argument that is unknown to
3479 pub fn get_arg_conflicts_with(&self, arg
: &Arg
) -> Vec
<&Arg
> // FIXME: This could probably have been an iterator
3481 if arg
.is_global_set() {
3482 self.get_global_arg_conflicts_with(arg
)
3484 let mut result
= Vec
::new();
3485 for id
in arg
.blacklist
.iter() {
3486 if let Some(arg
) = self.find(id
) {
3488 } else if let Some(group
) = self.find_group(id
) {
3490 self.unroll_args_in_group(&group
.id
)
3492 .map(|id
| self.find(id
).expect(INTERNAL_ERROR_MSG
)),
3495 panic
!("Command::get_arg_conflicts_with: The passed arg conflicts with an arg unknown to the cmd");
3502 // Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with.
3504 // This behavior follows the propagation rules of global arguments.
3505 // It is useful for finding conflicts for arguments declared as global.
3509 // If the given arg contains a conflict with an argument that is unknown to
3511 fn get_global_arg_conflicts_with(&self, arg
: &Arg
) -> Vec
<&Arg
> // FIXME: This could probably have been an iterator
3519 self.get_subcommands_containing(arg
)
3521 .flat_map(|x
| x
.args
.args()),
3523 .find(|arg
| arg
.get_id() == id
)
3525 "Command::get_arg_conflicts_with: \
3526 The passed arg conflicts with an arg unknown to the cmd",
3532 // Get a list of subcommands which contain the provided Argument
3534 // This command will only include subcommands in its list for which the subcommands
3535 // parent also contains the Argument.
3537 // This search follows the propagation rules of global arguments.
3538 // It is useful to finding subcommands, that have inherited a global argument.
3540 // **NOTE:** In this case only Sucommand_1 will be included
3541 // Subcommand_1 (contains Arg)
3542 // Subcommand_1.1 (doesn't contain Arg)
3543 // Subcommand_1.1.1 (contains Arg)
3545 fn get_subcommands_containing(&self, arg
: &Arg
) -> Vec
<&Self> {
3546 let mut vec
= std
::vec
::Vec
::new();
3547 for idx
in 0..self.subcommands
.len() {
3548 if self.subcommands
[idx
]
3551 .any(|ar
| ar
.get_id() == arg
.get_id())
3553 vec
.push(&self.subcommands
[idx
]);
3554 vec
.append(&mut self.subcommands
[idx
].get_subcommands_containing(arg
));
3560 /// Report whether [`Command::no_binary_name`] is set
3561 pub fn is_no_binary_name_set(&self) -> bool
{
3562 self.is_set(AppSettings
::NoBinaryName
)
3565 /// Report whether [`Command::ignore_errors`] is set
3566 pub(crate) fn is_ignore_errors_set(&self) -> bool
{
3567 self.is_set(AppSettings
::IgnoreErrors
)
3570 /// Report whether [`Command::dont_delimit_trailing_values`] is set
3571 pub fn is_dont_delimit_trailing_values_set(&self) -> bool
{
3572 self.is_set(AppSettings
::DontDelimitTrailingValues
)
3575 /// Report whether [`Command::disable_version_flag`] is set
3576 pub fn is_disable_version_flag_set(&self) -> bool
{
3577 self.is_set(AppSettings
::DisableVersionFlag
)
3578 || (self.version
.is_none() && self.long_version
.is_none())
3581 /// Report whether [`Command::propagate_version`] is set
3582 pub fn is_propagate_version_set(&self) -> bool
{
3583 self.is_set(AppSettings
::PropagateVersion
)
3586 /// Report whether [`Command::next_line_help`] is set
3587 pub fn is_next_line_help_set(&self) -> bool
{
3588 self.is_set(AppSettings
::NextLineHelp
)
3591 /// Report whether [`Command::disable_help_flag`] is set
3592 pub fn is_disable_help_flag_set(&self) -> bool
{
3593 self.is_set(AppSettings
::DisableHelpFlag
)
3596 /// Report whether [`Command::disable_help_subcommand`] is set
3597 pub fn is_disable_help_subcommand_set(&self) -> bool
{
3598 self.is_set(AppSettings
::DisableHelpSubcommand
)
3601 /// Report whether [`Command::disable_colored_help`] is set
3602 pub fn is_disable_colored_help_set(&self) -> bool
{
3603 self.is_set(AppSettings
::DisableColoredHelp
)
3606 /// Report whether [`Command::help_expected`] is set
3607 #[cfg(debug_assertions)]
3608 pub(crate) fn is_help_expected_set(&self) -> bool
{
3609 self.is_set(AppSettings
::HelpExpected
)
3614 feature
= "deprecated",
3615 deprecated(since
= "4.0.0", note
= "This is now the default")
3617 pub fn is_dont_collapse_args_in_usage_set(&self) -> bool
{
3621 /// Report whether [`Command::infer_long_args`] is set
3622 pub(crate) fn is_infer_long_args_set(&self) -> bool
{
3623 self.is_set(AppSettings
::InferLongArgs
)
3626 /// Report whether [`Command::infer_subcommands`] is set
3627 pub(crate) fn is_infer_subcommands_set(&self) -> bool
{
3628 self.is_set(AppSettings
::InferSubcommands
)
3631 /// Report whether [`Command::arg_required_else_help`] is set
3632 pub fn is_arg_required_else_help_set(&self) -> bool
{
3633 self.is_set(AppSettings
::ArgRequiredElseHelp
)
3638 feature
= "deprecated",
3641 note
= "Replaced with `Arg::is_allow_hyphen_values_set`"
3644 pub(crate) fn is_allow_hyphen_values_set(&self) -> bool
{
3645 self.is_set(AppSettings
::AllowHyphenValues
)
3650 feature
= "deprecated",
3653 note
= "Replaced with `Arg::is_allow_negative_numbers_set`"
3656 pub fn is_allow_negative_numbers_set(&self) -> bool
{
3657 self.is_set(AppSettings
::AllowNegativeNumbers
)
3662 feature
= "deprecated",
3663 deprecated(since
= "4.0.0", note
= "Replaced with `Arg::is_trailing_var_arg_set`")
3665 pub fn is_trailing_var_arg_set(&self) -> bool
{
3666 self.is_set(AppSettings
::TrailingVarArg
)
3669 /// Report whether [`Command::allow_missing_positional`] is set
3670 pub fn is_allow_missing_positional_set(&self) -> bool
{
3671 self.is_set(AppSettings
::AllowMissingPositional
)
3674 /// Report whether [`Command::hide`] is set
3675 pub fn is_hide_set(&self) -> bool
{
3676 self.is_set(AppSettings
::Hidden
)
3679 /// Report whether [`Command::subcommand_required`] is set
3680 pub fn is_subcommand_required_set(&self) -> bool
{
3681 self.is_set(AppSettings
::SubcommandRequired
)
3684 /// Report whether [`Command::allow_external_subcommands`] is set
3685 pub fn is_allow_external_subcommands_set(&self) -> bool
{
3686 self.is_set(AppSettings
::AllowExternalSubcommands
)
3689 /// Configured parser for values passed to an external subcommand
3694 /// let cmd = clap::Command::new("raw")
3695 /// .external_subcommand_value_parser(clap::value_parser!(String));
3696 /// let value_parser = cmd.get_external_subcommand_value_parser();
3697 /// println!("{:?}", value_parser);
3699 pub fn get_external_subcommand_value_parser(&self) -> Option
<&super::ValueParser
> {
3700 if !self.is_allow_external_subcommands_set() {
3703 static DEFAULT
: super::ValueParser
= super::ValueParser
::os_string();
3704 Some(self.external_value_parser
.as_ref().unwrap_or(&DEFAULT
))
3708 /// Report whether [`Command::args_conflicts_with_subcommands`] is set
3709 pub fn is_args_conflicts_with_subcommands_set(&self) -> bool
{
3710 self.is_set(AppSettings
::ArgsNegateSubcommands
)
3714 pub fn is_args_override_self(&self) -> bool
{
3715 self.is_set(AppSettings
::AllArgsOverrideSelf
)
3718 /// Report whether [`Command::subcommand_precedence_over_arg`] is set
3719 pub fn is_subcommand_precedence_over_arg_set(&self) -> bool
{
3720 self.is_set(AppSettings
::SubcommandPrecedenceOverArg
)
3723 /// Report whether [`Command::subcommand_negates_reqs`] is set
3724 pub fn is_subcommand_negates_reqs_set(&self) -> bool
{
3725 self.is_set(AppSettings
::SubcommandsNegateReqs
)
3728 /// Report whether [`Command::multicall`] is set
3729 pub fn is_multicall_set(&self) -> bool
{
3730 self.is_set(AppSettings
::Multicall
)
3734 // Internally used only
3736 pub(crate) fn get_override_usage(&self) -> Option
<&StyledStr
> {
3737 self.usage_str
.as_ref()
3740 pub(crate) fn get_override_help(&self) -> Option
<&StyledStr
> {
3741 self.help_str
.as_ref()
3744 #[cfg(feature = "help")]
3745 pub(crate) fn get_help_template(&self) -> Option
<&StyledStr
> {
3746 self.template
.as_ref()
3749 #[cfg(feature = "help")]
3750 pub(crate) fn get_term_width(&self) -> Option
<usize> {
3754 #[cfg(feature = "help")]
3755 pub(crate) fn get_max_term_width(&self) -> Option
<usize> {
3759 pub(crate) fn get_replacement(&self, key
: &str) -> Option
<&[Str
]> {
3760 self.replacers
.get(key
).map(|v
| v
.as_slice())
3763 pub(crate) fn get_keymap(&self) -> &MKeyMap
{
3767 fn get_used_global_args(&self, matches
: &ArgMatches
, global_arg_vec
: &mut Vec
<Id
>) {
3768 global_arg_vec
.extend(
3771 .filter(|a
| a
.is_global_set())
3772 .map(|ga
| ga
.id
.clone()),
3774 if let Some((id
, matches
)) = matches
.subcommand() {
3775 if let Some(used_sub
) = self.find_subcommand(id
) {
3776 used_sub
.get_used_global_args(matches
, global_arg_vec
);
3783 raw_args
: &mut clap_lex
::RawArgs
,
3784 args_cursor
: clap_lex
::ArgCursor
,
3785 ) -> ClapResult
<ArgMatches
> {
3786 debug
!("Command::_do_parse");
3788 // If there are global arguments, or settings we need to propagate them down to subcommands
3789 // before parsing in case we run into a subcommand
3790 self._build_self(false);
3792 let mut matcher
= ArgMatcher
::new(self);
3794 // do the real parsing
3795 let mut parser
= Parser
::new(self);
3796 if let Err(error
) = parser
.get_matches_with(&mut matcher
, raw_args
, args_cursor
) {
3797 if self.is_set(AppSettings
::IgnoreErrors
) {
3798 debug
!("Command::_do_parse: ignoring error: {}", error
);
3804 let mut global_arg_vec
= Default
::default();
3805 self.get_used_global_args(&matcher
, &mut global_arg_vec
);
3807 matcher
.propagate_globals(&global_arg_vec
);
3809 Ok(matcher
.into_inner())
3812 /// Prepare for introspecting on all included [`Command`]s
3814 /// Call this on the top-level [`Command`] when done building and before reading state for
3815 /// cases like completions, custom help output, etc.
3816 pub fn build(&mut self) {
3817 self._build_recursive(true);
3818 self._build_bin_names_internal();
3821 pub(crate) fn _build_recursive(&mut self, expand_help_tree
: bool
) {
3822 self._build_self(expand_help_tree
);
3823 for subcmd
in self.get_subcommands_mut() {
3824 subcmd
._build_recursive(expand_help_tree
);
3828 pub(crate) fn _build_self(&mut self, expand_help_tree
: bool
) {
3829 debug
!("Command::_build: name={:?}", self.get_name());
3830 if !self.settings
.is_set(AppSettings
::Built
) {
3831 // Make sure all the globally set flags apply to us as well
3832 self.settings
= self.settings
| self.g_settings
;
3834 if self.is_multicall_set() {
3835 self.settings
.insert(AppSettings
::SubcommandRequired
.into());
3836 self.settings
.insert(AppSettings
::DisableHelpFlag
.into());
3837 self.settings
.insert(AppSettings
::DisableVersionFlag
.into());
3839 if !cfg
!(feature
= "help") && self.get_override_help().is_none() {
3840 self.settings
.insert(AppSettings
::DisableHelpFlag
.into());
3842 .insert(AppSettings
::DisableHelpSubcommand
.into());
3844 if self.is_set(AppSettings
::ArgsNegateSubcommands
) {
3846 .insert(AppSettings
::SubcommandsNegateReqs
.into());
3848 if self.external_value_parser
.is_some() {
3850 .insert(AppSettings
::AllowExternalSubcommands
.into());
3852 if !self.has_subcommands() {
3854 .insert(AppSettings
::DisableHelpSubcommand
.into());
3858 self._check_help_and_version(expand_help_tree
);
3859 self._propagate_global_args();
3861 let mut pos_counter
= 1;
3862 let hide_pv
= self.is_set(AppSettings
::HidePossibleValues
);
3863 for a
in self.args
.args_mut() {
3864 // Fill in the groups
3865 for g
in &a
.groups
{
3866 if let Some(ag
) = self.groups
.iter_mut().find(|grp
| grp
.id
== *g
) {
3867 ag
.args
.push(a
.get_id().clone());
3869 let mut ag
= ArgGroup
::new(g
);
3870 ag
.args
.push(a
.get_id().clone());
3871 self.groups
.push(ag
);
3875 // Figure out implied settings
3877 if hide_pv
&& a
.is_takes_value_set() {
3878 a
.settings
.set(ArgSettings
::HidePossibleValues
);
3880 if a
.is_positional() && a
.index
.is_none() {
3881 a
.index
= Some(pos_counter
);
3888 #[allow(deprecated)]
3890 let highest_idx
= self
3894 if let crate::mkeymap
::KeyType
::Position(n
) = x
{
3902 let is_trailing_var_arg_set
= self.is_trailing_var_arg_set();
3903 let is_allow_hyphen_values_set
= self.is_allow_hyphen_values_set();
3904 let is_allow_negative_numbers_set
= self.is_allow_negative_numbers_set();
3905 for arg
in self.args
.args_mut() {
3906 if is_allow_hyphen_values_set
&& arg
.is_takes_value_set() {
3907 arg
.settings
.insert(ArgSettings
::AllowHyphenValues
.into());
3909 if is_allow_negative_numbers_set
&& arg
.is_takes_value_set() {
3911 .insert(ArgSettings
::AllowNegativeNumbers
.into());
3913 if is_trailing_var_arg_set
&& arg
.get_index() == Some(highest_idx
) {
3914 arg
.settings
.insert(ArgSettings
::TrailingVarArg
.into());
3919 #[cfg(debug_assertions)]
3921 self.settings
.set(AppSettings
::Built
);
3923 debug
!("Command::_build: already built");
3927 pub(crate) fn _build_subcommand(&mut self, name
: &str) -> Option
<&mut Self> {
3928 use std
::fmt
::Write
;
3930 let mut mid_string
= String
::from(" ");
3931 #[cfg(feature = "usage")]
3932 if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set()
3934 let reqs
= Usage
::new(self).get_required_usage_from(&[], None
, true); // maybe Some(m)
3937 mid_string
.push_str(&s
.to_string());
3938 mid_string
.push(' '
);
3941 let is_multicall_set
= self.is_multicall_set();
3943 let sc
= some
!(self.subcommands
.iter_mut().find(|s
| s
.name
== name
));
3945 // Display subcommand name, short and long in usage
3946 let mut sc_names
= String
::new();
3947 sc_names
.push_str(sc
.name
.as_str());
3948 let mut flag_subcmd
= false;
3949 if let Some(l
) = sc
.get_long_flag() {
3950 write
!(sc_names
, "|--{}", l
).unwrap();
3953 if let Some(s
) = sc
.get_short_flag() {
3954 write
!(sc_names
, "|-{}", s
).unwrap();
3959 sc_names
= format
!("{{{}}}", sc_names
);
3962 let usage_name
= self
3965 .map(|bin_name
| format
!("{}{}{}", bin_name
, mid_string
, sc_names
))
3966 .unwrap_or(sc_names
);
3967 sc
.usage_name
= Some(usage_name
);
3969 // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by
3971 let bin_name
= format
!(
3973 self.bin_name
.as_deref().unwrap_or_default(),
3974 if self.bin_name
.is_some() { " " }
else { "" }
,
3978 "Command::_build_subcommand Setting bin_name of {} to {:?}",
3981 sc
.bin_name
= Some(bin_name
);
3983 if sc
.display_name
.is_none() {
3984 let self_display_name
= if is_multicall_set
{
3985 self.display_name
.as_deref().unwrap_or("")
3987 self.display_name
.as_deref().unwrap_or(&self.name
)
3989 let display_name
= format
!(
3992 if !self_display_name
.is_empty() {
4000 "Command::_build_subcommand Setting display_name of {} to {:?}",
4001 sc
.name
, display_name
4003 sc
.display_name
= Some(display_name
);
4006 // Ensure all args are built and ready to parse
4007 sc
._build_self(false);
4012 fn _build_bin_names_internal(&mut self) {
4013 debug
!("Command::_build_bin_names");
4015 if !self.is_set(AppSettings
::BinNameBuilt
) {
4016 let mut mid_string
= String
::from(" ");
4017 #[cfg(feature = "usage")]
4018 if !self.is_subcommand_negates_reqs_set()
4019 && !self.is_args_conflicts_with_subcommands_set()
4021 let reqs
= Usage
::new(self).get_required_usage_from(&[], None
, true); // maybe Some(m)
4024 mid_string
.push_str(&s
.to_string());
4025 mid_string
.push(' '
);
4028 let is_multicall_set
= self.is_multicall_set();
4030 let self_bin_name
= if is_multicall_set
{
4031 self.bin_name
.as_deref().unwrap_or("")
4033 self.bin_name
.as_deref().unwrap_or(&self.name
)
4037 for mut sc
in &mut self.subcommands
{
4038 debug
!("Command::_build_bin_names:iter: bin_name set...");
4040 if sc
.usage_name
.is_none() {
4041 use std
::fmt
::Write
;
4042 // Display subcommand name, short and long in usage
4043 let mut sc_names
= String
::new();
4044 sc_names
.push_str(sc
.name
.as_str());
4045 let mut flag_subcmd
= false;
4046 if let Some(l
) = sc
.get_long_flag() {
4047 write
!(sc_names
, "|--{}", l
).unwrap();
4050 if let Some(s
) = sc
.get_short_flag() {
4051 write
!(sc_names
, "|-{}", s
).unwrap();
4056 sc_names
= format
!("{{{}}}", sc_names
);
4059 let usage_name
= format
!("{}{}{}", self_bin_name
, mid_string
, sc_names
);
4061 "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}",
4064 sc
.usage_name
= Some(usage_name
);
4067 "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})",
4068 sc
.name
, sc
.usage_name
4072 if sc
.bin_name
.is_none() {
4073 let bin_name
= format
!(
4076 if !self_bin_name
.is_empty() { " " }
else { "" }
,
4080 "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}",
4083 sc
.bin_name
= Some(bin_name
);
4086 "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})",
4087 sc
.name
, sc
.bin_name
4091 if sc
.display_name
.is_none() {
4092 let self_display_name
= if is_multicall_set
{
4093 self.display_name
.as_deref().unwrap_or("")
4095 self.display_name
.as_deref().unwrap_or(&self.name
)
4097 let display_name
= format
!(
4100 if !self_display_name
.is_empty() {
4108 "Command::_build_bin_names:iter: Setting display_name of {} to {:?}",
4109 sc
.name
, display_name
4111 sc
.display_name
= Some(display_name
);
4114 "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})",
4115 sc
.name
, sc
.display_name
4119 sc
._build_bin_names_internal();
4121 self.set(AppSettings
::BinNameBuilt
);
4123 debug
!("Command::_build_bin_names: already built");
4127 pub(crate) fn _panic_on_missing_help(&self, help_required_globally
: bool
) {
4128 if self.is_set(AppSettings
::HelpExpected
) || help_required_globally
{
4129 let args_missing_help
: Vec
<Id
> = self
4132 .filter(|arg
| arg
.get_help().is_none() && arg
.get_long_help().is_none())
4133 .map(|arg
| arg
.get_id().clone())
4136 debug_assert
!(args_missing_help
.is_empty(),
4137 "Command::help_expected is enabled for the Command {}, but at least one of its arguments does not have either `help` or `long_help` set. List of such arguments: {}",
4139 args_missing_help
.join(", ")
4143 for sub_app
in &self.subcommands
{
4144 sub_app
._panic_on_missing_help(help_required_globally
);
4148 #[cfg(debug_assertions)]
4149 pub(crate) fn two_args_of
<F
>(&self, condition
: F
) -> Option
<(&Arg
, &Arg
)>
4151 F
: Fn(&Arg
) -> bool
,
4153 two_elements_of(self.args
.args().filter(|a
: &&Arg
| condition(a
)))
4158 fn two_groups_of
<F
>(&self, condition
: F
) -> Option
<(&ArgGroup
, &ArgGroup
)>
4160 F
: Fn(&ArgGroup
) -> bool
,
4162 two_elements_of(self.groups
.iter().filter(|a
| condition(a
)))
4165 /// Propagate global args
4166 pub(crate) fn _propagate_global_args(&mut self) {
4167 debug
!("Command::_propagate_global_args:{}", self.name
);
4169 let autogenerated_help_subcommand
= !self.is_disable_help_subcommand_set();
4171 for sc
in &mut self.subcommands
{
4172 if sc
.get_name() == "help" && autogenerated_help_subcommand
{
4173 // Avoid propagating args to the autogenerated help subtrees used in completion.
4174 // This prevents args from showing up during help completions like
4175 // `myapp help subcmd <TAB>`, which should only suggest subcommands and not args,
4176 // while still allowing args to show up properly on the generated help message.
4180 for a
in self.args
.args().filter(|a
| a
.is_global_set()) {
4181 if sc
.find(&a
.id
).is_some() {
4183 "Command::_propagate skipping {:?} to {}, already exists",
4191 "Command::_propagate pushing {:?} to {}",
4195 sc
.args
.push(a
.clone());
4200 /// Propagate settings
4201 pub(crate) fn _propagate(&mut self) {
4202 debug
!("Command::_propagate:{}", self.name
);
4203 let mut subcommands
= std
::mem
::take(&mut self.subcommands
);
4204 for sc
in &mut subcommands
{
4205 self._propagate_subcommand(sc
);
4207 self.subcommands
= subcommands
;
4210 fn _propagate_subcommand(&self, sc
: &mut Self) {
4211 // We have to create a new scope in order to tell rustc the borrow of `sc` is
4212 // done and to recursively call this method
4214 if self.settings
.is_set(AppSettings
::PropagateVersion
) {
4215 if let Some(version
) = self.version
.as_ref() {
4216 sc
.version
.get_or_insert_with(|| version
.clone());
4218 if let Some(long_version
) = self.long_version
.as_ref() {
4219 sc
.long_version
.get_or_insert_with(|| long_version
.clone());
4223 sc
.settings
= sc
.settings
| self.g_settings
;
4224 sc
.g_settings
= sc
.g_settings
| self.g_settings
;
4225 sc
.term_w
= self.term_w
;
4226 sc
.max_w
= self.max_w
;
4230 pub(crate) fn _check_help_and_version(&mut self, expand_help_tree
: bool
) {
4232 "Command::_check_help_and_version:{} expand_help_tree={}",
4233 self.name
, expand_help_tree
4236 self.long_help_exists
= self.long_help_exists_();
4238 if !self.is_disable_help_flag_set() {
4239 debug
!("Command::_check_help_and_version: Building default --help");
4240 let mut arg
= Arg
::new(Id
::HELP
)
4243 .action(ArgAction
::Help
);
4244 if self.long_help_exists
{
4246 .help("Print help (see more with '--help')")
4247 .long_help("Print help (see a summary with '-h')");
4249 arg
= arg
.help("Print help");
4251 // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
4252 // `next_display_order`
4253 self.args
.push(arg
);
4255 if !self.is_disable_version_flag_set() {
4256 debug
!("Command::_check_help_and_version: Building default --version");
4257 let arg
= Arg
::new(Id
::VERSION
)
4260 .action(ArgAction
::Version
)
4261 .help("Print version");
4262 // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
4263 // `next_display_order`
4264 self.args
.push(arg
);
4267 if !self.is_set(AppSettings
::DisableHelpSubcommand
) {
4268 debug
!("Command::_check_help_and_version: Building help subcommand");
4269 let help_about
= "Print this message or the help of the given subcommand(s)";
4271 let mut help_subcmd
= if expand_help_tree
{
4272 // Slow code path to recursively clone all other subcommand subtrees under help
4273 let help_subcmd
= Command
::new("help")
4275 .global_setting(AppSettings
::DisableHelpSubcommand
)
4276 .subcommands(self.get_subcommands().map(Command
::_copy_subtree_for_help
));
4278 let mut help_help_subcmd
= Command
::new("help").about(help_about
);
4279 help_help_subcmd
.version
= None
;
4280 help_help_subcmd
.long_version
= None
;
4281 help_help_subcmd
= help_help_subcmd
4282 .setting(AppSettings
::DisableHelpFlag
)
4283 .setting(AppSettings
::DisableVersionFlag
);
4285 help_subcmd
.subcommand(help_help_subcmd
)
4287 Command
::new("help").about(help_about
).arg(
4288 Arg
::new("subcommand")
4289 .action(ArgAction
::Append
)
4291 .value_name("COMMAND")
4292 .help("Print help for the subcommand(s)"),
4295 self._propagate_subcommand(&mut help_subcmd
);
4297 // The parser acts like this is set, so let's set it so we don't falsely
4298 // advertise it to the user
4299 help_subcmd
.version
= None
;
4300 help_subcmd
.long_version
= None
;
4301 help_subcmd
= help_subcmd
4302 .setting(AppSettings
::DisableHelpFlag
)
4303 .setting(AppSettings
::DisableVersionFlag
)
4304 .unset_global_setting(AppSettings
::PropagateVersion
);
4306 self.subcommands
.push(help_subcmd
);
4310 fn _copy_subtree_for_help(&self) -> Command
{
4311 let mut cmd
= Command
::new(self.name
.clone())
4312 .hide(self.is_hide_set())
4313 .global_setting(AppSettings
::DisableHelpFlag
)
4314 .global_setting(AppSettings
::DisableVersionFlag
)
4315 .subcommands(self.get_subcommands().map(Command
::_copy_subtree_for_help
));
4316 if self.get_about().is_some() {
4317 cmd
= cmd
.about(self.get_about().unwrap().clone());
4322 pub(crate) fn _render_version(&self, use_long
: bool
) -> String
{
4323 debug
!("Command::_render_version");
4325 let ver
= if use_long
{
4328 .or(self.version
.as_deref())
4329 .unwrap_or_default()
4333 .or(self.long_version
.as_deref())
4334 .unwrap_or_default()
4336 let display_name
= self.get_display_name().unwrap_or_else(|| self.get_name());
4337 format
!("{} {}\n", display_name
, ver
)
4340 pub(crate) fn format_group(&self, g
: &Id
) -> StyledStr
{
4342 .unroll_args_in_group(g
)
4344 .filter_map(|x
| self.find(x
))
4346 if x
.is_positional() {
4347 // Print val_name for positional arguments. e.g. <file_name>
4348 x
.name_no_brackets()
4350 // Print usage string for flags arguments, e.g. <--help>
4354 .collect
::<Vec
<_
>>()
4356 let mut styled
= StyledStr
::new();
4358 styled
.none(g_string
);
4365 /// <https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999>
4366 pub(crate) trait Captures
<'a
> {}
4367 impl<'a
, T
> Captures
<'a
> for T {}
4369 // Internal Query Methods
4371 /// Iterate through the *flags* & *options* arguments.
4372 #[cfg(any(feature = "usage", feature = "help"))]
4373 pub(crate) fn get_non_positionals(&self) -> impl Iterator
<Item
= &Arg
> {
4374 self.get_arguments().filter(|a
| !a
.is_positional())
4377 pub(crate) fn find(&self, arg_id
: &Id
) -> Option
<&Arg
> {
4378 self.args
.args().find(|a
| a
.get_id() == arg_id
)
4382 pub(crate) fn contains_short(&self, s
: char) -> bool
{
4384 self.is_set(AppSettings
::Built
),
4385 "If Command::_build hasn't been called, manually search through Arg shorts"
4388 self.args
.contains(s
)
4392 pub(crate) fn set(&mut self, s
: AppSettings
) {
4393 self.settings
.set(s
)
4397 pub(crate) fn has_positionals(&self) -> bool
{
4398 self.get_positionals().next().is_some()
4401 #[cfg(any(feature = "usage", feature = "help"))]
4402 pub(crate) fn has_visible_subcommands(&self) -> bool
{
4405 .any(|sc
| sc
.name
!= "help" && !sc
.is_set(AppSettings
::Hidden
))
4408 /// Check if this subcommand can be referred to as `name`. In other words,
4409 /// check if `name` is the name of this subcommand or is one of its aliases.
4411 pub(crate) fn aliases_to(&self, name
: impl AsRef
<std
::ffi
::OsStr
>) -> bool
{
4412 let name
= name
.as_ref();
4413 self.get_name() == name
|| self.get_all_aliases().any(|alias
| alias
== name
)
4416 /// Check if this subcommand can be referred to as `name`. In other words,
4417 /// check if `name` is the name of this short flag subcommand or is one of its short flag aliases.
4419 pub(crate) fn short_flag_aliases_to(&self, flag
: char) -> bool
{
4420 Some(flag
) == self.short_flag
4421 || self.get_all_short_flag_aliases().any(|alias
| flag
== alias
)
4424 /// Check if this subcommand can be referred to as `name`. In other words,
4425 /// check if `name` is the name of this long flag subcommand or is one of its long flag aliases.
4427 pub(crate) fn long_flag_aliases_to(&self, flag
: &str) -> bool
{
4428 match self.long_flag
.as_ref() {
4429 Some(long_flag
) => {
4430 long_flag
== flag
|| self.get_all_long_flag_aliases().any(|alias
| alias
== flag
)
4432 None
=> self.get_all_long_flag_aliases().any(|alias
| alias
== flag
),
4436 #[cfg(debug_assertions)]
4437 pub(crate) fn id_exists(&self, id
: &Id
) -> bool
{
4438 self.args
.args().any(|x
| x
.get_id() == id
) || self.groups
.iter().any(|x
| x
.id
== *id
)
4441 /// Iterate through the groups this arg is member of.
4442 pub(crate) fn groups_for_arg
<'a
>(&'a
self, arg
: &Id
) -> impl Iterator
<Item
= Id
> + 'a
{
4443 debug
!("Command::groups_for_arg: id={:?}", arg
);
4444 let arg
= arg
.clone();
4447 .filter(move |grp
| grp
.args
.iter().any(|a
| a
== &arg
))
4448 .map(|grp
| grp
.id
.clone())
4451 pub(crate) fn find_group(&self, group_id
: &Id
) -> Option
<&ArgGroup
> {
4452 self.groups
.iter().find(|g
| g
.id
== *group_id
)
4455 /// Iterate through all the names of all subcommands (not recursively), including aliases.
4456 /// Used for suggestions.
4457 pub(crate) fn all_subcommand_names(&self) -> impl Iterator
<Item
= &str> + Captures
{
4458 self.get_subcommands().flat_map(|sc
| {
4459 let name
= sc
.get_name();
4460 let aliases
= sc
.get_all_aliases();
4461 std
::iter
::once(name
).chain(aliases
)
4465 pub(crate) fn required_graph(&self) -> ChildGraph
<Id
> {
4466 let mut reqs
= ChildGraph
::with_capacity(5);
4467 for a
in self.args
.args().filter(|a
| a
.is_required_set()) {
4468 reqs
.insert(a
.get_id().clone());
4470 for group
in &self.groups
{
4472 let idx
= reqs
.insert(group
.id
.clone());
4473 for a
in &group
.requires
{
4474 reqs
.insert_child(idx
, a
.clone());
4482 pub(crate) fn unroll_args_in_group(&self, group
: &Id
) -> Vec
<Id
> {
4483 debug
!("Command::unroll_args_in_group: group={:?}", group
);
4484 let mut g_vec
= vec
![group
];
4485 let mut args
= vec
![];
4487 while let Some(g
) = g_vec
.pop() {
4491 .find(|grp
| grp
.id
== *g
)
4492 .expect(INTERNAL_ERROR_MSG
)
4496 debug
!("Command::unroll_args_in_group:iter: entity={:?}", n
);
4497 if !args
.contains(n
) {
4498 if self.find(n
).is_some() {
4499 debug
!("Command::unroll_args_in_group:iter: this is an arg");
4500 args
.push(n
.clone())
4502 debug
!("Command::unroll_args_in_group:iter: this is a group");
4512 pub(crate) fn unroll_arg_requires
<F
>(&self, func
: F
, arg
: &Id
) -> Vec
<Id
>
4514 F
: Fn(&(ArgPredicate
, Id
)) -> Option
<Id
>,
4516 let mut processed
= vec
![];
4517 let mut r_vec
= vec
![arg
];
4518 let mut args
= vec
![];
4520 while let Some(a
) = r_vec
.pop() {
4521 if processed
.contains(&a
) {
4527 if let Some(arg
) = self.find(a
) {
4528 for r
in arg
.requires
.iter().filter_map(&func
) {
4529 if let Some(req
) = self.find(&r
) {
4530 if !req
.requires
.is_empty() {
4531 r_vec
.push(req
.get_id())
4542 /// Find a flag subcommand name by short flag or an alias
4543 pub(crate) fn find_short_subcmd(&self, c
: char) -> Option
<&str> {
4544 self.get_subcommands()
4545 .find(|sc
| sc
.short_flag_aliases_to(c
))
4546 .map(|sc
| sc
.get_name())
4549 /// Find a flag subcommand name by long flag or an alias
4550 pub(crate) fn find_long_subcmd(&self, long
: &str) -> Option
<&str> {
4551 self.get_subcommands()
4552 .find(|sc
| sc
.long_flag_aliases_to(long
))
4553 .map(|sc
| sc
.get_name())
4556 #[cfg(feature = "help")]
4557 pub(crate) fn get_display_order(&self) -> usize {
4558 self.disp_ord
.unwrap_or(999)
4561 pub(crate) fn write_help_err(&self, mut use_long
: bool
) -> StyledStr
{
4563 "Command::write_help_err: {}, use_long={:?}",
4564 self.get_display_name().unwrap_or_else(|| self.get_name()),
4565 use_long
&& self.long_help_exists(),
4568 use_long
= use_long
&& self.long_help_exists();
4569 let usage
= Usage
::new(self);
4571 let mut styled
= StyledStr
::new();
4572 write_help(&mut styled
, self, &usage
, use_long
);
4577 pub(crate) fn write_version_err(&self, use_long
: bool
) -> StyledStr
{
4578 let msg
= self._render_version(use_long
);
4579 let mut styled
= StyledStr
::new();
4584 pub(crate) fn long_help_exists(&self) -> bool
{
4585 debug
!("Command::long_help_exists: {}", self.long_help_exists
);
4586 self.long_help_exists
4589 fn long_help_exists_(&self) -> bool
{
4590 debug
!("Command::long_help_exists");
4591 // In this case, both must be checked. This allows the retention of
4592 // original formatting, but also ensures that the actual -h or --help
4593 // specified by the user is sent through. If hide_short_help is not included,
4594 // then items specified with hidden_short_help will also be hidden.
4595 let should_long
= |v
: &Arg
| {
4596 v
.get_long_help().is_some()
4597 || v
.is_hide_long_help_set()
4598 || v
.is_hide_short_help_set()
4599 || v
.get_possible_values()
4601 .any(PossibleValue
::should_show_help
)
4604 // Subcommands aren't checked because we prefer short help for them, deferring to
4605 // `cmd subcmd --help` for more.
4606 self.get_long_about().is_some()
4607 || self.get_before_long_help().is_some()
4608 || self.get_after_long_help().is_some()
4609 || self.get_arguments().any(should_long
)
4612 // Should we color the help?
4613 pub(crate) fn color_help(&self) -> ColorChoice
{
4614 #[cfg(feature = "color")]
4615 if self.is_disable_colored_help_set() {
4616 return ColorChoice
::Never
;
4623 impl Default
for Command
{
4624 fn default() -> Self {
4626 name
: Default
::default(),
4627 long_flag
: Default
::default(),
4628 short_flag
: Default
::default(),
4629 display_name
: Default
::default(),
4630 bin_name
: Default
::default(),
4631 author
: Default
::default(),
4632 version
: Default
::default(),
4633 long_version
: Default
::default(),
4634 about
: Default
::default(),
4635 long_about
: Default
::default(),
4636 before_help
: Default
::default(),
4637 before_long_help
: Default
::default(),
4638 after_help
: Default
::default(),
4639 after_long_help
: Default
::default(),
4640 aliases
: Default
::default(),
4641 short_flag_aliases
: Default
::default(),
4642 long_flag_aliases
: Default
::default(),
4643 usage_str
: Default
::default(),
4644 usage_name
: Default
::default(),
4645 help_str
: Default
::default(),
4646 disp_ord
: Default
::default(),
4647 term_w
: Default
::default(),
4648 max_w
: Default
::default(),
4649 #[cfg(feature = "help")]
4650 template
: Default
::default(),
4651 settings
: Default
::default(),
4652 g_settings
: Default
::default(),
4653 args
: Default
::default(),
4654 subcommands
: Default
::default(),
4655 replacers
: Default
::default(),
4656 groups
: Default
::default(),
4657 current_help_heading
: Default
::default(),
4658 current_disp_ord
: Some(0),
4659 subcommand_value_name
: Default
::default(),
4660 subcommand_heading
: Default
::default(),
4661 external_value_parser
: Default
::default(),
4662 long_help_exists
: false,
4667 impl Index
<&'_ Id
> for Command
{
4670 fn index(&self, key
: &Id
) -> &Self::Output
{
4671 self.find(key
).expect(INTERNAL_ERROR_MSG
)
4675 impl From
<&'_ Command
> for Command
{
4676 fn from(cmd
: &'_ Command
) -> Self {
4681 impl fmt
::Display
for Command
{
4682 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
4683 write
!(f
, "{}", self.name
)
4687 fn two_elements_of
<I
, T
>(mut iter
: I
) -> Option
<(T
, T
)>
4689 I
: Iterator
<Item
= T
>,
4691 let first
= iter
.next();
4692 let second
= iter
.next();
4694 match (first
, second
) {
4695 (Some(first
), Some(second
)) => Some((first
, second
)),
4701 fn check_auto_traits() {
4702 static_assertions
::assert_impl_all
!(Command
: Send
, Sync
, Unpin
);