1#![cfg_attr(not(feature = "usage"), allow(unused_mut))]
2
3// Std
4use std::env;
5use std::ffi::OsString;
6use std::fmt;
7use std::io;
8use std::ops::Index;
9use std::path::Path;
10
11// Internal
12use crate::builder::app_settings::{AppFlags, AppSettings};
13use crate::builder::arg_settings::ArgSettings;
14use crate::builder::ext::Extensions;
15use crate::builder::ArgAction;
16use crate::builder::IntoResettable;
17use crate::builder::PossibleValue;
18use crate::builder::Str;
19use crate::builder::StyledStr;
20use crate::builder::Styles;
21use crate::builder::{Arg, ArgGroup, ArgPredicate};
22use crate::error::ErrorKind;
23use crate::error::Result as ClapResult;
24use crate::mkeymap::MKeyMap;
25use crate::output::fmt::Stream;
26use crate::output::{fmt::Colorizer, write_help, Usage};
27use crate::parser::{ArgMatcher, ArgMatches, Parser};
28use crate::util::ChildGraph;
29use crate::util::{color::ColorChoice, Id};
30use crate::{Error, INTERNAL_ERROR_MSG};
31
32#[cfg(debug_assertions)]
33use crate::builder::debug_asserts::assert_app;
34
35/// Build a command-line interface.
36///
37/// This includes defining arguments, subcommands, parser behavior, and help output.
38/// Once all configuration is complete,
39/// the [`Command::get_matches`] family of methods starts the runtime-parsing
40/// process. These methods then return information about the user supplied
41/// arguments (or lack thereof).
42///
43/// When deriving a [`Parser`][crate::Parser], you can use
44/// [`CommandFactory::command`][crate::CommandFactory::command] to access the
45/// `Command`.
46///
47/// - [Basic API][crate::Command#basic-api]
48/// - [Application-wide Settings][crate::Command#application-wide-settings]
49/// - [Command-specific Settings][crate::Command#command-specific-settings]
50/// - [Subcommand-specific Settings][crate::Command#subcommand-specific-settings]
51/// - [Reflection][crate::Command#reflection]
52///
53/// # Examples
54///
55/// ```no_run
56/// # use clap_builder as clap;
57/// # use clap::{Command, Arg};
58/// let m = Command::new("My Program")
59/// .author("Me, me@mail.com")
60/// .version("1.0.2")
61/// .about("Explains in brief what the program does")
62/// .arg(
63/// Arg::new("in_file")
64/// )
65/// .after_help("Longer explanation to appear after the options when \
66/// displaying the help information from --help or -h")
67/// .get_matches();
68///
69/// // Your program logic starts here...
70/// ```
71/// [`Command::get_matches`]: Command::get_matches()
72#[derive(Debug, Clone)]
73pub struct Command {
74 name: Str,
75 long_flag: Option<Str>,
76 short_flag: Option<char>,
77 display_name: Option<String>,
78 bin_name: Option<String>,
79 author: Option<Str>,
80 version: Option<Str>,
81 long_version: Option<Str>,
82 about: Option<StyledStr>,
83 long_about: Option<StyledStr>,
84 before_help: Option<StyledStr>,
85 before_long_help: Option<StyledStr>,
86 after_help: Option<StyledStr>,
87 after_long_help: Option<StyledStr>,
88 aliases: Vec<(Str, bool)>, // (name, visible)
89 short_flag_aliases: Vec<(char, bool)>, // (name, visible)
90 long_flag_aliases: Vec<(Str, bool)>, // (name, visible)
91 usage_str: Option<StyledStr>,
92 usage_name: Option<String>,
93 help_str: Option<StyledStr>,
94 disp_ord: Option<usize>,
95 #[cfg(feature = "help")]
96 template: Option<StyledStr>,
97 settings: AppFlags,
98 g_settings: AppFlags,
99 args: MKeyMap,
100 subcommands: Vec<Command>,
101 groups: Vec<ArgGroup>,
102 current_help_heading: Option<Str>,
103 current_disp_ord: Option<usize>,
104 subcommand_value_name: Option<Str>,
105 subcommand_heading: Option<Str>,
106 external_value_parser: Option<super::ValueParser>,
107 long_help_exists: bool,
108 deferred: Option<fn(Command) -> Command>,
109 app_ext: Extensions,
110}
111
112/// # Basic API
113impl Command {
114 /// Creates a new instance of an `Command`.
115 ///
116 /// It is common, but not required, to use binary name as the `name`. This
117 /// name will only be displayed to the user when they request to print
118 /// version or help and usage information.
119 ///
120 /// See also [`command!`](crate::command!) and [`crate_name!`](crate::crate_name!).
121 ///
122 /// # Examples
123 ///
124 /// ```rust
125 /// # use clap_builder as clap;
126 /// # use clap::Command;
127 /// Command::new("My Program")
128 /// # ;
129 /// ```
130 pub fn new(name: impl Into<Str>) -> Self {
131 /// The actual implementation of `new`, non-generic to save code size.
132 ///
133 /// If we don't do this rustc will unnecessarily generate multiple versions
134 /// of this code.
135 fn new_inner(name: Str) -> Command {
136 Command {
137 name,
138 ..Default::default()
139 }
140 }
141
142 new_inner(name.into())
143 }
144
145 /// Adds an [argument] to the list of valid possibilities.
146 ///
147 /// # Examples
148 ///
149 /// ```rust
150 /// # use clap_builder as clap;
151 /// # use clap::{Command, arg, Arg};
152 /// Command::new("myprog")
153 /// // Adding a single "flag" argument with a short and help text, using Arg::new()
154 /// .arg(
155 /// Arg::new("debug")
156 /// .short('d')
157 /// .help("turns on debugging mode")
158 /// )
159 /// // Adding a single "option" argument with a short, a long, and help text using the less
160 /// // verbose Arg::from()
161 /// .arg(
162 /// arg!(-c --config <CONFIG> "Optionally sets a config file to use")
163 /// )
164 /// # ;
165 /// ```
166 /// [argument]: Arg
167 #[must_use]
168 pub fn arg(mut self, a: impl Into<Arg>) -> Self {
169 let arg = a.into();
170 self.arg_internal(arg);
171 self
172 }
173
174 fn arg_internal(&mut self, mut arg: Arg) {
175 if let Some(current_disp_ord) = self.current_disp_ord.as_mut() {
176 if !arg.is_positional() {
177 let current = *current_disp_ord;
178 arg.disp_ord.get_or_insert(current);
179 *current_disp_ord = current + 1;
180 }
181 }
182
183 arg.help_heading
184 .get_or_insert_with(|| self.current_help_heading.clone());
185 self.args.push(arg);
186 }
187
188 /// Adds multiple [arguments] to the list of valid possibilities.
189 ///
190 /// # Examples
191 ///
192 /// ```rust
193 /// # use clap_builder as clap;
194 /// # use clap::{Command, arg, Arg};
195 /// Command::new("myprog")
196 /// .args([
197 /// arg!(-d --debug "turns on debugging info"),
198 /// Arg::new("input").help("the input file to use")
199 /// ])
200 /// # ;
201 /// ```
202 /// [arguments]: Arg
203 #[must_use]
204 pub fn args(mut self, args: impl IntoIterator<Item = impl Into<Arg>>) -> Self {
205 for arg in args {
206 self = self.arg(arg);
207 }
208 self
209 }
210
211 /// Allows one to mutate an [`Arg`] after it's been added to a [`Command`].
212 ///
213 /// # Panics
214 ///
215 /// If the argument is undefined
216 ///
217 /// # Examples
218 ///
219 /// ```rust
220 /// # use clap_builder as clap;
221 /// # use clap::{Command, Arg, ArgAction};
222 ///
223 /// let mut cmd = Command::new("foo")
224 /// .arg(Arg::new("bar")
225 /// .short('b')
226 /// .action(ArgAction::SetTrue))
227 /// .mut_arg("bar", |a| a.short('B'));
228 ///
229 /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-b"]);
230 ///
231 /// // Since we changed `bar`'s short to "B" this should err as there
232 /// // is no `-b` anymore, only `-B`
233 ///
234 /// assert!(res.is_err());
235 ///
236 /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-B"]);
237 /// assert!(res.is_ok());
238 /// ```
239 #[must_use]
240 #[cfg_attr(debug_assertions, track_caller)]
241 pub fn mut_arg<F>(mut self, arg_id: impl AsRef<str>, f: F) -> Self
242 where
243 F: FnOnce(Arg) -> Arg,
244 {
245 let id = arg_id.as_ref();
246 let a = self
247 .args
248 .remove_by_name(id)
249 .unwrap_or_else(|| panic!("Argument `{id}` is undefined"));
250
251 self.args.push(f(a));
252 self
253 }
254
255 /// Allows one to mutate all [`Arg`]s after they've been added to a [`Command`].
256 ///
257 /// This does not affect the built-in `--help` or `--version` arguments.
258 ///
259 /// # Examples
260 ///
261 #[cfg_attr(feature = "string", doc = "```")]
262 #[cfg_attr(not(feature = "string"), doc = "```ignore")]
263 /// # use clap_builder as clap;
264 /// # use clap::{Command, Arg, ArgAction};
265 ///
266 /// let mut cmd = Command::new("foo")
267 /// .arg(Arg::new("bar")
268 /// .long("bar")
269 /// .action(ArgAction::SetTrue))
270 /// .arg(Arg::new("baz")
271 /// .long("baz")
272 /// .action(ArgAction::SetTrue))
273 /// .mut_args(|a| {
274 /// if let Some(l) = a.get_long().map(|l| format!("prefix-{l}")) {
275 /// a.long(l)
276 /// } else {
277 /// a
278 /// }
279 /// });
280 ///
281 /// let res = cmd.try_get_matches_from_mut(vec!["foo", "--bar"]);
282 ///
283 /// // Since we changed `bar`'s long to "prefix-bar" this should err as there
284 /// // is no `--bar` anymore, only `--prefix-bar`.
285 ///
286 /// assert!(res.is_err());
287 ///
288 /// let res = cmd.try_get_matches_from_mut(vec!["foo", "--prefix-bar"]);
289 /// assert!(res.is_ok());
290 /// ```
291 #[must_use]
292 #[cfg_attr(debug_assertions, track_caller)]
293 pub fn mut_args<F>(mut self, f: F) -> Self
294 where
295 F: FnMut(Arg) -> Arg,
296 {
297 self.args.mut_args(f);
298 self
299 }
300
301 /// Allows one to mutate an [`ArgGroup`] after it's been added to a [`Command`].
302 ///
303 /// # Panics
304 ///
305 /// If the argument is undefined
306 ///
307 /// # Examples
308 ///
309 /// ```rust
310 /// # use clap_builder as clap;
311 /// # use clap::{Command, arg, ArgGroup};
312 ///
313 /// Command::new("foo")
314 /// .arg(arg!(--"set-ver" <ver> "set the version manually").required(false))
315 /// .arg(arg!(--major "auto increase major"))
316 /// .arg(arg!(--minor "auto increase minor"))
317 /// .arg(arg!(--patch "auto increase patch"))
318 /// .group(ArgGroup::new("vers")
319 /// .args(["set-ver", "major", "minor","patch"])
320 /// .required(true))
321 /// .mut_group("vers", |a| a.required(false));
322 /// ```
323 #[must_use]
324 #[cfg_attr(debug_assertions, track_caller)]
325 pub fn mut_group<F>(mut self, arg_id: impl AsRef<str>, f: F) -> Self
326 where
327 F: FnOnce(ArgGroup) -> ArgGroup,
328 {
329 let id = arg_id.as_ref();
330 let index = self
331 .groups
332 .iter()
333 .position(|g| g.get_id() == id)
334 .unwrap_or_else(|| panic!("Group `{id}` is undefined"));
335 let a = self.groups.remove(index);
336
337 self.groups.push(f(a));
338 self
339 }
340 /// Allows one to mutate a [`Command`] after it's been added as a subcommand.
341 ///
342 /// This can be useful for modifying auto-generated arguments of nested subcommands with
343 /// [`Command::mut_arg`].
344 ///
345 /// # Panics
346 ///
347 /// If the subcommand is undefined
348 ///
349 /// # Examples
350 ///
351 /// ```rust
352 /// # use clap_builder as clap;
353 /// # use clap::Command;
354 ///
355 /// let mut cmd = Command::new("foo")
356 /// .subcommand(Command::new("bar"))
357 /// .mut_subcommand("bar", |subcmd| subcmd.disable_help_flag(true));
358 ///
359 /// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar", "--help"]);
360 ///
361 /// // Since we disabled the help flag on the "bar" subcommand, this should err.
362 ///
363 /// assert!(res.is_err());
364 ///
365 /// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar"]);
366 /// assert!(res.is_ok());
367 /// ```
368 #[must_use]
369 pub fn mut_subcommand<F>(mut self, name: impl AsRef<str>, f: F) -> Self
370 where
371 F: FnOnce(Self) -> Self,
372 {
373 let name = name.as_ref();
374 let pos = self.subcommands.iter().position(|s| s.name == name);
375
376 let subcmd = if let Some(idx) = pos {
377 self.subcommands.remove(idx)
378 } else {
379 panic!("Command `{name}` is undefined")
380 };
381
382 self.subcommands.push(f(subcmd));
383 self
384 }
385
386 /// Adds an [`ArgGroup`] to the application.
387 ///
388 /// [`ArgGroup`]s are a family of related arguments.
389 /// By placing them in a logical group, you can build easier requirement and exclusion rules.
390 ///
391 /// Example use cases:
392 /// - Make an entire [`ArgGroup`] required, meaning that one (and *only*
393 /// one) argument from that group must be present at runtime.
394 /// - Name an [`ArgGroup`] as a conflict to another argument.
395 /// Meaning any of the arguments that belong to that group will cause a failure if present with
396 /// the conflicting argument.
397 /// - Ensure exclusion between arguments.
398 /// - Extract a value from a group instead of determining exactly which argument was used.
399 ///
400 /// # Examples
401 ///
402 /// The following example demonstrates using an [`ArgGroup`] to ensure that one, and only one,
403 /// of the arguments from the specified group is present at runtime.
404 ///
405 /// ```rust
406 /// # use clap_builder as clap;
407 /// # use clap::{Command, arg, ArgGroup};
408 /// Command::new("cmd")
409 /// .arg(arg!(--"set-ver" <ver> "set the version manually").required(false))
410 /// .arg(arg!(--major "auto increase major"))
411 /// .arg(arg!(--minor "auto increase minor"))
412 /// .arg(arg!(--patch "auto increase patch"))
413 /// .group(ArgGroup::new("vers")
414 /// .args(["set-ver", "major", "minor","patch"])
415 /// .required(true))
416 /// # ;
417 /// ```
418 #[inline]
419 #[must_use]
420 pub fn group(mut self, group: impl Into<ArgGroup>) -> Self {
421 self.groups.push(group.into());
422 self
423 }
424
425 /// Adds multiple [`ArgGroup`]s to the [`Command`] at once.
426 ///
427 /// # Examples
428 ///
429 /// ```rust
430 /// # use clap_builder as clap;
431 /// # use clap::{Command, arg, ArgGroup};
432 /// Command::new("cmd")
433 /// .arg(arg!(--"set-ver" <ver> "set the version manually").required(false))
434 /// .arg(arg!(--major "auto increase major"))
435 /// .arg(arg!(--minor "auto increase minor"))
436 /// .arg(arg!(--patch "auto increase patch"))
437 /// .arg(arg!(-c <FILE> "a config file").required(false))
438 /// .arg(arg!(-i <IFACE> "an interface").required(false))
439 /// .groups([
440 /// ArgGroup::new("vers")
441 /// .args(["set-ver", "major", "minor","patch"])
442 /// .required(true),
443 /// ArgGroup::new("input")
444 /// .args(["c", "i"])
445 /// ])
446 /// # ;
447 /// ```
448 #[must_use]
449 pub fn groups(mut self, groups: impl IntoIterator<Item = impl Into<ArgGroup>>) -> Self {
450 for g in groups.into_iter() {
451 self = self.group(g.into());
452 }
453 self
454 }
455
456 /// Adds a subcommand to the list of valid possibilities.
457 ///
458 /// Subcommands are effectively sub-[`Command`]s, because they can contain their own arguments,
459 /// subcommands, version, usage, etc. They also function just like [`Command`]s, in that they get
460 /// their own auto generated help, version, and usage.
461 ///
462 /// A subcommand's [`Command::name`] will be used for:
463 /// - The argument the user passes in
464 /// - Programmatically looking up the subcommand
465 ///
466 /// # Examples
467 ///
468 /// ```rust
469 /// # use clap_builder as clap;
470 /// # use clap::{Command, arg};
471 /// Command::new("myprog")
472 /// .subcommand(Command::new("config")
473 /// .about("Controls configuration features")
474 /// .arg(arg!(<config> "Required configuration file to use")))
475 /// # ;
476 /// ```
477 #[inline]
478 #[must_use]
479 pub fn subcommand(self, subcmd: impl Into<Command>) -> Self {
480 let subcmd = subcmd.into();
481 self.subcommand_internal(subcmd)
482 }
483
484 fn subcommand_internal(mut self, mut subcmd: Self) -> Self {
485 if let Some(current_disp_ord) = self.current_disp_ord.as_mut() {
486 let current = *current_disp_ord;
487 subcmd.disp_ord.get_or_insert(current);
488 *current_disp_ord = current + 1;
489 }
490 self.subcommands.push(subcmd);
491 self
492 }
493
494 /// Adds multiple subcommands to the list of valid possibilities.
495 ///
496 /// # Examples
497 ///
498 /// ```rust
499 /// # use clap_builder as clap;
500 /// # use clap::{Command, Arg, };
501 /// # Command::new("myprog")
502 /// .subcommands( [
503 /// Command::new("config").about("Controls configuration functionality")
504 /// .arg(Arg::new("config_file")),
505 /// Command::new("debug").about("Controls debug functionality")])
506 /// # ;
507 /// ```
508 /// [`IntoIterator`]: std::iter::IntoIterator
509 #[must_use]
510 pub fn subcommands(mut self, subcmds: impl IntoIterator<Item = impl Into<Self>>) -> Self {
511 for subcmd in subcmds {
512 self = self.subcommand(subcmd);
513 }
514 self
515 }
516
517 /// Delay initialization for parts of the `Command`
518 ///
519 /// This is useful for large applications to delay definitions of subcommands until they are
520 /// being invoked.
521 ///
522 /// # Examples
523 ///
524 /// ```rust
525 /// # use clap_builder as clap;
526 /// # use clap::{Command, arg};
527 /// Command::new("myprog")
528 /// .subcommand(Command::new("config")
529 /// .about("Controls configuration features")
530 /// .defer(|cmd| {
531 /// cmd.arg(arg!(<config> "Required configuration file to use"))
532 /// })
533 /// )
534 /// # ;
535 /// ```
536 pub fn defer(mut self, deferred: fn(Command) -> Command) -> Self {
537 self.deferred = Some(deferred);
538 self
539 }
540
541 /// Catch problems earlier in the development cycle.
542 ///
543 /// Most error states are handled as asserts under the assumption they are programming mistake
544 /// and not something to handle at runtime. Rather than relying on tests (manual or automated)
545 /// that exhaustively test your CLI to ensure the asserts are evaluated, this will run those
546 /// asserts in a way convenient for running as a test.
547 ///
548 /// **Note::** This will not help with asserts in [`ArgMatches`], those will need exhaustive
549 /// testing of your CLI.
550 ///
551 /// # Examples
552 ///
553 /// ```rust
554 /// # use clap_builder as clap;
555 /// # use clap::{Command, Arg, ArgAction};
556 /// fn cmd() -> Command {
557 /// Command::new("foo")
558 /// .arg(
559 /// Arg::new("bar").short('b').action(ArgAction::SetTrue)
560 /// )
561 /// }
562 ///
563 /// #[test]
564 /// fn verify_app() {
565 /// cmd().debug_assert();
566 /// }
567 ///
568 /// fn main() {
569 /// let m = cmd().get_matches_from(vec!["foo", "-b"]);
570 /// println!("{}", m.get_flag("bar"));
571 /// }
572 /// ```
573 pub fn debug_assert(mut self) {
574 self.build();
575 }
576
577 /// Custom error message for post-parsing validation
578 ///
579 /// # Examples
580 ///
581 /// ```rust
582 /// # use clap_builder as clap;
583 /// # use clap::{Command, error::ErrorKind};
584 /// let mut cmd = Command::new("myprog");
585 /// let err = cmd.error(ErrorKind::InvalidValue, "Some failure case");
586 /// ```
587 pub fn error(&mut self, kind: ErrorKind, message: impl std::fmt::Display) -> Error {
588 Error::raw(kind, message).format(self)
589 }
590
591 /// Parse [`env::args_os`], exiting on failure.
592 ///
593 /// # Panics
594 ///
595 /// If contradictory arguments or settings exist (debug builds).
596 ///
597 /// # Examples
598 ///
599 /// ```no_run
600 /// # use clap_builder as clap;
601 /// # use clap::{Command, Arg};
602 /// let matches = Command::new("myprog")
603 /// // Args and options go here...
604 /// .get_matches();
605 /// ```
606 /// [`env::args_os`]: std::env::args_os()
607 /// [`Command::try_get_matches_from_mut`]: Command::try_get_matches_from_mut()
608 #[inline]
609 pub fn get_matches(self) -> ArgMatches {
610 self.get_matches_from(env::args_os())
611 }
612
613 /// Parse [`env::args_os`], exiting on failure.
614 ///
615 /// Like [`Command::get_matches`] but doesn't consume the `Command`.
616 ///
617 /// # Panics
618 ///
619 /// If contradictory arguments or settings exist (debug builds).
620 ///
621 /// # Examples
622 ///
623 /// ```no_run
624 /// # use clap_builder as clap;
625 /// # use clap::{Command, Arg};
626 /// let mut cmd = Command::new("myprog")
627 /// // Args and options go here...
628 /// ;
629 /// let matches = cmd.get_matches_mut();
630 /// ```
631 /// [`env::args_os`]: std::env::args_os()
632 /// [`Command::get_matches`]: Command::get_matches()
633 pub fn get_matches_mut(&mut self) -> ArgMatches {
634 self.try_get_matches_from_mut(&mut env::args_os())
635 .unwrap_or_else(|e| e.exit())
636 }
637
638 /// Parse [`env::args_os`], returning a [`clap::Result`] on failure.
639 ///
640 /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
641 /// used. It will return a [`clap::Error`], where the [`kind`] is a
642 /// [`ErrorKind::DisplayHelp`] or [`ErrorKind::DisplayVersion`] respectively. You must call
643 /// [`Error::exit`] or perform a [`std::process::exit`].
644 ///
645 /// # Panics
646 ///
647 /// If contradictory arguments or settings exist (debug builds).
648 ///
649 /// # Examples
650 ///
651 /// ```no_run
652 /// # use clap_builder as clap;
653 /// # use clap::{Command, Arg};
654 /// let matches = Command::new("myprog")
655 /// // Args and options go here...
656 /// .try_get_matches()
657 /// .unwrap_or_else(|e| e.exit());
658 /// ```
659 /// [`env::args_os`]: std::env::args_os()
660 /// [`Error::exit`]: crate::Error::exit()
661 /// [`std::process::exit`]: std::process::exit()
662 /// [`clap::Result`]: Result
663 /// [`clap::Error`]: crate::Error
664 /// [`kind`]: crate::Error
665 /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp
666 /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion
667 #[inline]
668 pub fn try_get_matches(self) -> ClapResult<ArgMatches> {
669 // Start the parsing
670 self.try_get_matches_from(env::args_os())
671 }
672
673 /// Parse the specified arguments, exiting on failure.
674 ///
675 /// **NOTE:** The first argument will be parsed as the binary name unless
676 /// [`Command::no_binary_name`] is used.
677 ///
678 /// # Panics
679 ///
680 /// If contradictory arguments or settings exist (debug builds).
681 ///
682 /// # Examples
683 ///
684 /// ```no_run
685 /// # use clap_builder as clap;
686 /// # use clap::{Command, Arg};
687 /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
688 ///
689 /// let matches = Command::new("myprog")
690 /// // Args and options go here...
691 /// .get_matches_from(arg_vec);
692 /// ```
693 /// [`Command::get_matches`]: Command::get_matches()
694 /// [`clap::Result`]: Result
695 /// [`Vec`]: std::vec::Vec
696 pub fn get_matches_from<I, T>(mut self, itr: I) -> ArgMatches
697 where
698 I: IntoIterator<Item = T>,
699 T: Into<OsString> + Clone,
700 {
701 self.try_get_matches_from_mut(itr).unwrap_or_else(|e| {
702 drop(self);
703 e.exit()
704 })
705 }
706
707 /// Parse the specified arguments, returning a [`clap::Result`] on failure.
708 ///
709 /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
710 /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`]
711 /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or
712 /// perform a [`std::process::exit`] yourself.
713 ///
714 /// **NOTE:** The first argument will be parsed as the binary name unless
715 /// [`Command::no_binary_name`] is used.
716 ///
717 /// # Panics
718 ///
719 /// If contradictory arguments or settings exist (debug builds).
720 ///
721 /// # Examples
722 ///
723 /// ```no_run
724 /// # use clap_builder as clap;
725 /// # use clap::{Command, Arg};
726 /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
727 ///
728 /// let matches = Command::new("myprog")
729 /// // Args and options go here...
730 /// .try_get_matches_from(arg_vec)
731 /// .unwrap_or_else(|e| e.exit());
732 /// ```
733 /// [`Command::get_matches_from`]: Command::get_matches_from()
734 /// [`Command::try_get_matches`]: Command::try_get_matches()
735 /// [`Error::exit`]: crate::Error::exit()
736 /// [`std::process::exit`]: std::process::exit()
737 /// [`clap::Error`]: crate::Error
738 /// [`Error::exit`]: crate::Error::exit()
739 /// [`kind`]: crate::Error
740 /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp
741 /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion
742 /// [`clap::Result`]: Result
743 pub fn try_get_matches_from<I, T>(mut self, itr: I) -> ClapResult<ArgMatches>
744 where
745 I: IntoIterator<Item = T>,
746 T: Into<OsString> + Clone,
747 {
748 self.try_get_matches_from_mut(itr)
749 }
750
751 /// Parse the specified arguments, returning a [`clap::Result`] on failure.
752 ///
753 /// Like [`Command::try_get_matches_from`] but doesn't consume the `Command`.
754 ///
755 /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
756 /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`]
757 /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or
758 /// perform a [`std::process::exit`] yourself.
759 ///
760 /// **NOTE:** The first argument will be parsed as the binary name unless
761 /// [`Command::no_binary_name`] is used.
762 ///
763 /// # Panics
764 ///
765 /// If contradictory arguments or settings exist (debug builds).
766 ///
767 /// # Examples
768 ///
769 /// ```no_run
770 /// # use clap_builder as clap;
771 /// # use clap::{Command, Arg};
772 /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
773 ///
774 /// let mut cmd = Command::new("myprog");
775 /// // Args and options go here...
776 /// let matches = cmd.try_get_matches_from_mut(arg_vec)
777 /// .unwrap_or_else(|e| e.exit());
778 /// ```
779 /// [`Command::try_get_matches_from`]: Command::try_get_matches_from()
780 /// [`clap::Result`]: Result
781 /// [`clap::Error`]: crate::Error
782 /// [`kind`]: crate::Error
783 pub fn try_get_matches_from_mut<I, T>(&mut self, itr: I) -> ClapResult<ArgMatches>
784 where
785 I: IntoIterator<Item = T>,
786 T: Into<OsString> + Clone,
787 {
788 let mut raw_args = clap_lex::RawArgs::new(itr);
789 let mut cursor = raw_args.cursor();
790
791 if self.settings.is_set(AppSettings::Multicall) {
792 if let Some(argv0) = raw_args.next_os(&mut cursor) {
793 let argv0 = Path::new(&argv0);
794 if let Some(command) = argv0.file_stem().and_then(|f| f.to_str()) {
795 // Stop borrowing command so we can get another mut ref to it.
796 let command = command.to_owned();
797 debug!("Command::try_get_matches_from_mut: Parsed command {command} from argv");
798
799 debug!("Command::try_get_matches_from_mut: Reinserting command into arguments so subcommand parser matches it");
800 raw_args.insert(&cursor, [&command]);
801 debug!("Command::try_get_matches_from_mut: Clearing name and bin_name so that displayed command name starts with applet name");
802 self.name = "".into();
803 self.bin_name = None;
804 return self._do_parse(&mut raw_args, cursor);
805 }
806 }
807 };
808
809 // Get the name of the program (argument 1 of env::args()) and determine the
810 // actual file
811 // that was used to execute the program. This is because a program called
812 // ./target/release/my_prog -a
813 // will have two arguments, './target/release/my_prog', '-a' but we don't want
814 // to display
815 // the full path when displaying help messages and such
816 if !self.settings.is_set(AppSettings::NoBinaryName) {
817 if let Some(name) = raw_args.next_os(&mut cursor) {
818 let p = Path::new(name);
819
820 if let Some(f) = p.file_name() {
821 if let Some(s) = f.to_str() {
822 if self.bin_name.is_none() {
823 self.bin_name = Some(s.to_owned());
824 }
825 }
826 }
827 }
828 }
829
830 self._do_parse(&mut raw_args, cursor)
831 }
832
833 /// Prints the short help message (`-h`) to [`io::stdout()`].
834 ///
835 /// See also [`Command::print_long_help`].
836 ///
837 /// # Examples
838 ///
839 /// ```rust
840 /// # use clap_builder as clap;
841 /// # use clap::Command;
842 /// let mut cmd = Command::new("myprog");
843 /// cmd.print_help();
844 /// ```
845 /// [`io::stdout()`]: std::io::stdout()
846 pub fn print_help(&mut self) -> io::Result<()> {
847 self._build_self(false);
848 let color = self.color_help();
849
850 let mut styled = StyledStr::new();
851 let usage = Usage::new(self);
852 write_help(&mut styled, self, &usage, false);
853
854 let c = Colorizer::new(Stream::Stdout, color).with_content(styled);
855 c.print()
856 }
857
858 /// Prints the long help message (`--help`) to [`io::stdout()`].
859 ///
860 /// See also [`Command::print_help`].
861 ///
862 /// # Examples
863 ///
864 /// ```rust
865 /// # use clap_builder as clap;
866 /// # use clap::Command;
867 /// let mut cmd = Command::new("myprog");
868 /// cmd.print_long_help();
869 /// ```
870 /// [`io::stdout()`]: std::io::stdout()
871 /// [`BufWriter`]: std::io::BufWriter
872 /// [`-h` (short)]: Arg::help()
873 /// [`--help` (long)]: Arg::long_help()
874 pub fn print_long_help(&mut self) -> io::Result<()> {
875 self._build_self(false);
876 let color = self.color_help();
877
878 let mut styled = StyledStr::new();
879 let usage = Usage::new(self);
880 write_help(&mut styled, self, &usage, true);
881
882 let c = Colorizer::new(Stream::Stdout, color).with_content(styled);
883 c.print()
884 }
885
886 /// Render the short help message (`-h`) to a [`StyledStr`]
887 ///
888 /// See also [`Command::render_long_help`].
889 ///
890 /// # Examples
891 ///
892 /// ```rust
893 /// # use clap_builder as clap;
894 /// # use clap::Command;
895 /// use std::io;
896 /// let mut cmd = Command::new("myprog");
897 /// let mut out = io::stdout();
898 /// let help = cmd.render_help();
899 /// println!("{help}");
900 /// ```
901 /// [`io::Write`]: std::io::Write
902 /// [`-h` (short)]: Arg::help()
903 /// [`--help` (long)]: Arg::long_help()
904 pub fn render_help(&mut self) -> StyledStr {
905 self._build_self(false);
906
907 let mut styled = StyledStr::new();
908 let usage = Usage::new(self);
909 write_help(&mut styled, self, &usage, false);
910 styled
911 }
912
913 /// Render the long help message (`--help`) to a [`StyledStr`].
914 ///
915 /// See also [`Command::render_help`].
916 ///
917 /// # Examples
918 ///
919 /// ```rust
920 /// # use clap_builder as clap;
921 /// # use clap::Command;
922 /// use std::io;
923 /// let mut cmd = Command::new("myprog");
924 /// let mut out = io::stdout();
925 /// let help = cmd.render_long_help();
926 /// println!("{help}");
927 /// ```
928 /// [`io::Write`]: std::io::Write
929 /// [`-h` (short)]: Arg::help()
930 /// [`--help` (long)]: Arg::long_help()
931 pub fn render_long_help(&mut self) -> StyledStr {
932 self._build_self(false);
933
934 let mut styled = StyledStr::new();
935 let usage = Usage::new(self);
936 write_help(&mut styled, self, &usage, true);
937 styled
938 }
939
940 #[doc(hidden)]
941 #[cfg_attr(
942 feature = "deprecated",
943 deprecated(since = "4.0.0", note = "Replaced with `Command::render_help`")
944 )]
945 pub fn write_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> {
946 self._build_self(false);
947
948 let mut styled = StyledStr::new();
949 let usage = Usage::new(self);
950 write_help(&mut styled, self, &usage, false);
951 ok!(write!(w, "{styled}"));
952 w.flush()
953 }
954
955 #[doc(hidden)]
956 #[cfg_attr(
957 feature = "deprecated",
958 deprecated(since = "4.0.0", note = "Replaced with `Command::render_long_help`")
959 )]
960 pub fn write_long_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> {
961 self._build_self(false);
962
963 let mut styled = StyledStr::new();
964 let usage = Usage::new(self);
965 write_help(&mut styled, self, &usage, true);
966 ok!(write!(w, "{styled}"));
967 w.flush()
968 }
969
970 /// Version message rendered as if the user ran `-V`.
971 ///
972 /// See also [`Command::render_long_version`].
973 ///
974 /// ### Coloring
975 ///
976 /// This function does not try to color the message nor it inserts any [ANSI escape codes].
977 ///
978 /// ### Examples
979 ///
980 /// ```rust
981 /// # use clap_builder as clap;
982 /// # use clap::Command;
983 /// use std::io;
984 /// let cmd = Command::new("myprog");
985 /// println!("{}", cmd.render_version());
986 /// ```
987 /// [`io::Write`]: std::io::Write
988 /// [`-V` (short)]: Command::version()
989 /// [`--version` (long)]: Command::long_version()
990 /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
991 pub fn render_version(&self) -> String {
992 self._render_version(false)
993 }
994
995 /// Version message rendered as if the user ran `--version`.
996 ///
997 /// See also [`Command::render_version`].
998 ///
999 /// ### Coloring
1000 ///
1001 /// This function does not try to color the message nor it inserts any [ANSI escape codes].
1002 ///
1003 /// ### Examples
1004 ///
1005 /// ```rust
1006 /// # use clap_builder as clap;
1007 /// # use clap::Command;
1008 /// use std::io;
1009 /// let cmd = Command::new("myprog");
1010 /// println!("{}", cmd.render_long_version());
1011 /// ```
1012 /// [`io::Write`]: std::io::Write
1013 /// [`-V` (short)]: Command::version()
1014 /// [`--version` (long)]: Command::long_version()
1015 /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
1016 pub fn render_long_version(&self) -> String {
1017 self._render_version(true)
1018 }
1019
1020 /// Usage statement
1021 ///
1022 /// ### Examples
1023 ///
1024 /// ```rust
1025 /// # use clap_builder as clap;
1026 /// # use clap::Command;
1027 /// use std::io;
1028 /// let mut cmd = Command::new("myprog");
1029 /// println!("{}", cmd.render_usage());
1030 /// ```
1031 pub fn render_usage(&mut self) -> StyledStr {
1032 self.render_usage_().unwrap_or_default()
1033 }
1034
1035 pub(crate) fn render_usage_(&mut self) -> Option<StyledStr> {
1036 // If there are global arguments, or settings we need to propagate them down to subcommands
1037 // before parsing incase we run into a subcommand
1038 self._build_self(false);
1039
1040 Usage::new(self).create_usage_with_title(&[])
1041 }
1042}
1043
1044/// # Application-wide Settings
1045///
1046/// These settings will apply to the top-level command and all subcommands, by default. Some
1047/// settings can be overridden in subcommands.
1048impl Command {
1049 /// Specifies that the parser should not assume the first argument passed is the binary name.
1050 ///
1051 /// This is normally the case when using a "daemon" style mode. For shells / REPLs, see
1052 /// [`Command::multicall`][Command::multicall].
1053 ///
1054 /// # Examples
1055 ///
1056 /// ```rust
1057 /// # use clap_builder as clap;
1058 /// # use clap::{Command, arg};
1059 /// let m = Command::new("myprog")
1060 /// .no_binary_name(true)
1061 /// .arg(arg!(<cmd> ... "commands to run"))
1062 /// .get_matches_from(vec!["command", "set"]);
1063 ///
1064 /// let cmds: Vec<_> = m.get_many::<String>("cmd").unwrap().collect();
1065 /// assert_eq!(cmds, ["command", "set"]);
1066 /// ```
1067 /// [`try_get_matches_from_mut`]: crate::Command::try_get_matches_from_mut()
1068 #[inline]
1069 pub fn no_binary_name(self, yes: bool) -> Self {
1070 if yes {
1071 self.global_setting(AppSettings::NoBinaryName)
1072 } else {
1073 self.unset_global_setting(AppSettings::NoBinaryName)
1074 }
1075 }
1076
1077 /// Try not to fail on parse errors, like missing option values.
1078 ///
1079 /// **NOTE:** This choice is propagated to all child subcommands.
1080 ///
1081 /// # Examples
1082 ///
1083 /// ```rust
1084 /// # use clap_builder as clap;
1085 /// # use clap::{Command, arg};
1086 /// let cmd = Command::new("cmd")
1087 /// .ignore_errors(true)
1088 /// .arg(arg!(-c --config <FILE> "Sets a custom config file"))
1089 /// .arg(arg!(-x --stuff <FILE> "Sets a custom stuff file"))
1090 /// .arg(arg!(f: -f "Flag"));
1091 ///
1092 /// let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]);
1093 ///
1094 /// assert!(r.is_ok(), "unexpected error: {r:?}");
1095 /// let m = r.unwrap();
1096 /// assert_eq!(m.get_one::<String>("config").unwrap(), "file");
1097 /// assert!(m.get_flag("f"));
1098 /// assert_eq!(m.get_one::<String>("stuff"), None);
1099 /// ```
1100 #[inline]
1101 pub fn ignore_errors(self, yes: bool) -> Self {
1102 if yes {
1103 self.global_setting(AppSettings::IgnoreErrors)
1104 } else {
1105 self.unset_global_setting(AppSettings::IgnoreErrors)
1106 }
1107 }
1108
1109 /// Replace prior occurrences of arguments rather than error
1110 ///
1111 /// For any argument that would conflict with itself by default (e.g.
1112 /// [`ArgAction::Set`], it will now override itself.
1113 ///
1114 /// This is the equivalent to saying the `foo` arg using [`Arg::overrides_with("foo")`] for all
1115 /// defined arguments.
1116 ///
1117 /// **NOTE:** This choice is propagated to all child subcommands.
1118 ///
1119 /// [`Arg::overrides_with("foo")`]: crate::Arg::overrides_with()
1120 #[inline]
1121 pub fn args_override_self(self, yes: bool) -> Self {
1122 if yes {
1123 self.global_setting(AppSettings::AllArgsOverrideSelf)
1124 } else {
1125 self.unset_global_setting(AppSettings::AllArgsOverrideSelf)
1126 }
1127 }
1128
1129 /// Disables the automatic delimiting of values after `--` or when [`Command::trailing_var_arg`]
1130 /// was used.
1131 ///
1132 /// **NOTE:** The same thing can be done manually by setting the final positional argument to
1133 /// [`Arg::value_delimiter(None)`]. Using this setting is safer, because it's easier to locate
1134 /// when making changes.
1135 ///
1136 /// **NOTE:** This choice is propagated to all child subcommands.
1137 ///
1138 /// # Examples
1139 ///
1140 /// ```no_run
1141 /// # use clap_builder as clap;
1142 /// # use clap::{Command, Arg};
1143 /// Command::new("myprog")
1144 /// .dont_delimit_trailing_values(true)
1145 /// .get_matches();
1146 /// ```
1147 ///
1148 /// [`Arg::value_delimiter(None)`]: crate::Arg::value_delimiter()
1149 #[inline]
1150 pub fn dont_delimit_trailing_values(self, yes: bool) -> Self {
1151 if yes {
1152 self.global_setting(AppSettings::DontDelimitTrailingValues)
1153 } else {
1154 self.unset_global_setting(AppSettings::DontDelimitTrailingValues)
1155 }
1156 }
1157
1158 /// Sets when to color output.
1159 ///
1160 /// **NOTE:** This choice is propagated to all child subcommands.
1161 ///
1162 /// **NOTE:** Default behaviour is [`ColorChoice::Auto`].
1163 ///
1164 /// # Examples
1165 ///
1166 /// ```no_run
1167 /// # use clap_builder as clap;
1168 /// # use clap::{Command, ColorChoice};
1169 /// Command::new("myprog")
1170 /// .color(ColorChoice::Never)
1171 /// .get_matches();
1172 /// ```
1173 /// [`ColorChoice::Auto`]: crate::ColorChoice::Auto
1174 #[cfg(feature = "color")]
1175 #[inline]
1176 #[must_use]
1177 pub fn color(self, color: ColorChoice) -> Self {
1178 let cmd = self
1179 .unset_global_setting(AppSettings::ColorAuto)
1180 .unset_global_setting(AppSettings::ColorAlways)
1181 .unset_global_setting(AppSettings::ColorNever);
1182 match color {
1183 ColorChoice::Auto => cmd.global_setting(AppSettings::ColorAuto),
1184 ColorChoice::Always => cmd.global_setting(AppSettings::ColorAlways),
1185 ColorChoice::Never => cmd.global_setting(AppSettings::ColorNever),
1186 }
1187 }
1188
1189 /// Sets the [`Styles`] for terminal output
1190 ///
1191 /// **NOTE:** This choice is propagated to all child subcommands.
1192 ///
1193 /// **NOTE:** Default behaviour is [`Styles::default`].
1194 ///
1195 /// # Examples
1196 ///
1197 /// ```no_run
1198 /// # use clap_builder as clap;
1199 /// # use clap::{Command, ColorChoice, builder::styling};
1200 /// let styles = styling::Styles::styled()
1201 /// .header(styling::AnsiColor::Green.on_default() | styling::Effects::BOLD)
1202 /// .usage(styling::AnsiColor::Green.on_default() | styling::Effects::BOLD)
1203 /// .literal(styling::AnsiColor::Blue.on_default() | styling::Effects::BOLD)
1204 /// .placeholder(styling::AnsiColor::Cyan.on_default());
1205 /// Command::new("myprog")
1206 /// .styles(styles)
1207 /// .get_matches();
1208 /// ```
1209 #[cfg(feature = "color")]
1210 #[inline]
1211 #[must_use]
1212 pub fn styles(mut self, styles: Styles) -> Self {
1213 self.app_ext.set(styles);
1214 self
1215 }
1216
1217 /// Sets the terminal width at which to wrap help messages.
1218 ///
1219 /// Using `0` will ignore terminal widths and use source formatting.
1220 ///
1221 /// Defaults to current terminal width when `wrap_help` feature flag is enabled. If current
1222 /// width cannot be determined, the default is 100.
1223 ///
1224 /// **`unstable-v5` feature**: Defaults to unbound, being subject to
1225 /// [`Command::max_term_width`].
1226 ///
1227 /// **NOTE:** This setting applies globally and *not* on a per-command basis.
1228 ///
1229 /// **NOTE:** This requires the `wrap_help` feature
1230 ///
1231 /// # Examples
1232 ///
1233 /// ```rust
1234 /// # use clap_builder as clap;
1235 /// # use clap::Command;
1236 /// Command::new("myprog")
1237 /// .term_width(80)
1238 /// # ;
1239 /// ```
1240 #[inline]
1241 #[must_use]
1242 #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))]
1243 pub fn term_width(mut self, width: usize) -> Self {
1244 self.app_ext.set(TermWidth(width));
1245 self
1246 }
1247
1248 /// Limit the line length for wrapping help when using the current terminal's width.
1249 ///
1250 /// This only applies when [`term_width`][Command::term_width] is unset so that the current
1251 /// terminal's width will be used. See [`Command::term_width`] for more details.
1252 ///
1253 /// Using `0` will ignore this, always respecting [`Command::term_width`] (default).
1254 ///
1255 /// **`unstable-v5` feature**: Defaults to 100.
1256 ///
1257 /// **NOTE:** This setting applies globally and *not* on a per-command basis.
1258 ///
1259 /// **NOTE:** This requires the `wrap_help` feature
1260 ///
1261 /// # Examples
1262 ///
1263 /// ```rust
1264 /// # use clap_builder as clap;
1265 /// # use clap::Command;
1266 /// Command::new("myprog")
1267 /// .max_term_width(100)
1268 /// # ;
1269 /// ```
1270 #[inline]
1271 #[must_use]
1272 #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))]
1273 pub fn max_term_width(mut self, width: usize) -> Self {
1274 self.app_ext.set(MaxTermWidth(width));
1275 self
1276 }
1277
1278 /// Disables `-V` and `--version` flag.
1279 ///
1280 /// # Examples
1281 ///
1282 /// ```rust
1283 /// # use clap_builder as clap;
1284 /// # use clap::{Command, error::ErrorKind};
1285 /// let res = Command::new("myprog")
1286 /// .version("1.0.0")
1287 /// .disable_version_flag(true)
1288 /// .try_get_matches_from(vec![
1289 /// "myprog", "--version"
1290 /// ]);
1291 /// assert!(res.is_err());
1292 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
1293 /// ```
1294 ///
1295 /// You can create a custom version flag with [`ArgAction::Version`]
1296 /// ```rust
1297 /// # use clap_builder as clap;
1298 /// # use clap::{Command, Arg, ArgAction, error::ErrorKind};
1299 /// let mut cmd = Command::new("myprog")
1300 /// .version("1.0.0")
1301 /// // Remove the `-V` short flag
1302 /// .disable_version_flag(true)
1303 /// .arg(
1304 /// Arg::new("version")
1305 /// .long("version")
1306 /// .action(ArgAction::Version)
1307 /// .help("Print version")
1308 /// );
1309 ///
1310 /// let res = cmd.try_get_matches_from_mut(vec![
1311 /// "myprog", "-V"
1312 /// ]);
1313 /// assert!(res.is_err());
1314 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
1315 ///
1316 /// let res = cmd.try_get_matches_from_mut(vec![
1317 /// "myprog", "--version"
1318 /// ]);
1319 /// assert!(res.is_err());
1320 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::DisplayVersion);
1321 /// ```
1322 #[inline]
1323 pub fn disable_version_flag(self, yes: bool) -> Self {
1324 if yes {
1325 self.global_setting(AppSettings::DisableVersionFlag)
1326 } else {
1327 self.unset_global_setting(AppSettings::DisableVersionFlag)
1328 }
1329 }
1330
1331 /// Specifies to use the version of the current command for all [`subcommands`].
1332 ///
1333 /// Defaults to `false`; subcommands have independent version strings from their parents.
1334 ///
1335 /// **NOTE:** This choice is propagated to all child subcommands.
1336 ///
1337 /// # Examples
1338 ///
1339 /// ```no_run
1340 /// # use clap_builder as clap;
1341 /// # use clap::{Command, Arg};
1342 /// Command::new("myprog")
1343 /// .version("v1.1")
1344 /// .propagate_version(true)
1345 /// .subcommand(Command::new("test"))
1346 /// .get_matches();
1347 /// // running `$ myprog test --version` will display
1348 /// // "myprog-test v1.1"
1349 /// ```
1350 ///
1351 /// [`subcommands`]: crate::Command::subcommand()
1352 #[inline]
1353 pub fn propagate_version(self, yes: bool) -> Self {
1354 if yes {
1355 self.global_setting(AppSettings::PropagateVersion)
1356 } else {
1357 self.unset_global_setting(AppSettings::PropagateVersion)
1358 }
1359 }
1360
1361 /// Places the help string for all arguments and subcommands on the line after them.
1362 ///
1363 /// **NOTE:** This choice is propagated to all child subcommands.
1364 ///
1365 /// # Examples
1366 ///
1367 /// ```no_run
1368 /// # use clap_builder as clap;
1369 /// # use clap::{Command, Arg};
1370 /// Command::new("myprog")
1371 /// .next_line_help(true)
1372 /// .get_matches();
1373 /// ```
1374 #[inline]
1375 pub fn next_line_help(self, yes: bool) -> Self {
1376 if yes {
1377 self.global_setting(AppSettings::NextLineHelp)
1378 } else {
1379 self.unset_global_setting(AppSettings::NextLineHelp)
1380 }
1381 }
1382
1383 /// Disables `-h` and `--help` flag.
1384 ///
1385 /// **NOTE:** This choice is propagated to all child subcommands.
1386 ///
1387 /// # Examples
1388 ///
1389 /// ```rust
1390 /// # use clap_builder as clap;
1391 /// # use clap::{Command, error::ErrorKind};
1392 /// let res = Command::new("myprog")
1393 /// .disable_help_flag(true)
1394 /// .try_get_matches_from(vec![
1395 /// "myprog", "-h"
1396 /// ]);
1397 /// assert!(res.is_err());
1398 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
1399 /// ```
1400 ///
1401 /// You can create a custom help flag with [`ArgAction::Help`], [`ArgAction::HelpShort`], or
1402 /// [`ArgAction::HelpLong`]
1403 /// ```rust
1404 /// # use clap_builder as clap;
1405 /// # use clap::{Command, Arg, ArgAction, error::ErrorKind};
1406 /// let mut cmd = Command::new("myprog")
1407 /// // Change help short flag to `?`
1408 /// .disable_help_flag(true)
1409 /// .arg(
1410 /// Arg::new("help")
1411 /// .short('?')
1412 /// .long("help")
1413 /// .action(ArgAction::Help)
1414 /// .help("Print help")
1415 /// );
1416 ///
1417 /// let res = cmd.try_get_matches_from_mut(vec![
1418 /// "myprog", "-h"
1419 /// ]);
1420 /// assert!(res.is_err());
1421 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
1422 ///
1423 /// let res = cmd.try_get_matches_from_mut(vec![
1424 /// "myprog", "-?"
1425 /// ]);
1426 /// assert!(res.is_err());
1427 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::DisplayHelp);
1428 /// ```
1429 #[inline]
1430 pub fn disable_help_flag(self, yes: bool) -> Self {
1431 if yes {
1432 self.global_setting(AppSettings::DisableHelpFlag)
1433 } else {
1434 self.unset_global_setting(AppSettings::DisableHelpFlag)
1435 }
1436 }
1437
1438 /// Disables the `help` [`subcommand`].
1439 ///
1440 /// **NOTE:** This choice is propagated to all child subcommands.
1441 ///
1442 /// # Examples
1443 ///
1444 /// ```rust
1445 /// # use clap_builder as clap;
1446 /// # use clap::{Command, error::ErrorKind};
1447 /// let res = Command::new("myprog")
1448 /// .disable_help_subcommand(true)
1449 /// // Normally, creating a subcommand causes a `help` subcommand to automatically
1450 /// // be generated as well
1451 /// .subcommand(Command::new("test"))
1452 /// .try_get_matches_from(vec![
1453 /// "myprog", "help"
1454 /// ]);
1455 /// assert!(res.is_err());
1456 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::InvalidSubcommand);
1457 /// ```
1458 ///
1459 /// [`subcommand`]: crate::Command::subcommand()
1460 #[inline]
1461 pub fn disable_help_subcommand(self, yes: bool) -> Self {
1462 if yes {
1463 self.global_setting(AppSettings::DisableHelpSubcommand)
1464 } else {
1465 self.unset_global_setting(AppSettings::DisableHelpSubcommand)
1466 }
1467 }
1468
1469 /// Disables colorized help messages.
1470 ///
1471 /// **NOTE:** This choice is propagated to all child subcommands.
1472 ///
1473 /// # Examples
1474 ///
1475 /// ```no_run
1476 /// # use clap_builder as clap;
1477 /// # use clap::Command;
1478 /// Command::new("myprog")
1479 /// .disable_colored_help(true)
1480 /// .get_matches();
1481 /// ```
1482 #[inline]
1483 pub fn disable_colored_help(self, yes: bool) -> Self {
1484 if yes {
1485 self.global_setting(AppSettings::DisableColoredHelp)
1486 } else {
1487 self.unset_global_setting(AppSettings::DisableColoredHelp)
1488 }
1489 }
1490
1491 /// Panic if help descriptions are omitted.
1492 ///
1493 /// **NOTE:** When deriving [`Parser`][crate::Parser], you could instead check this at
1494 /// compile-time with `#![deny(missing_docs)]`
1495 ///
1496 /// **NOTE:** This choice is propagated to all child subcommands.
1497 ///
1498 /// # Examples
1499 ///
1500 /// ```rust
1501 /// # use clap_builder as clap;
1502 /// # use clap::{Command, Arg};
1503 /// Command::new("myprog")
1504 /// .help_expected(true)
1505 /// .arg(
1506 /// Arg::new("foo").help("It does foo stuff")
1507 /// // As required via `help_expected`, a help message was supplied
1508 /// )
1509 /// # .get_matches();
1510 /// ```
1511 ///
1512 /// # Panics
1513 ///
1514 /// On debug builds:
1515 /// ```rust,no_run
1516 /// # use clap_builder as clap;
1517 /// # use clap::{Command, Arg};
1518 /// Command::new("myapp")
1519 /// .help_expected(true)
1520 /// .arg(
1521 /// Arg::new("foo")
1522 /// // Someone forgot to put .about("...") here
1523 /// // Since the setting `help_expected` is activated, this will lead to
1524 /// // a panic (if you are in debug mode)
1525 /// )
1526 /// # .get_matches();
1527 ///```
1528 #[inline]
1529 pub fn help_expected(self, yes: bool) -> Self {
1530 if yes {
1531 self.global_setting(AppSettings::HelpExpected)
1532 } else {
1533 self.unset_global_setting(AppSettings::HelpExpected)
1534 }
1535 }
1536
1537 #[doc(hidden)]
1538 #[cfg_attr(
1539 feature = "deprecated",
1540 deprecated(since = "4.0.0", note = "This is now the default")
1541 )]
1542 pub fn dont_collapse_args_in_usage(self, _yes: bool) -> Self {
1543 self
1544 }
1545
1546 /// Tells `clap` *not* to print possible values when displaying help information.
1547 ///
1548 /// This can be useful if there are many values, or they are explained elsewhere.
1549 ///
1550 /// To set this per argument, see
1551 /// [`Arg::hide_possible_values`][crate::Arg::hide_possible_values].
1552 ///
1553 /// **NOTE:** This choice is propagated to all child subcommands.
1554 #[inline]
1555 pub fn hide_possible_values(self, yes: bool) -> Self {
1556 if yes {
1557 self.global_setting(AppSettings::HidePossibleValues)
1558 } else {
1559 self.unset_global_setting(AppSettings::HidePossibleValues)
1560 }
1561 }
1562
1563 /// Allow partial matches of long arguments or their [aliases].
1564 ///
1565 /// For example, to match an argument named `--test`, one could use `--t`, `--te`, `--tes`, and
1566 /// `--test`.
1567 ///
1568 /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match
1569 /// `--te` to `--test` there could not also be another argument or alias `--temp` because both
1570 /// start with `--te`
1571 ///
1572 /// **NOTE:** This choice is propagated to all child subcommands.
1573 ///
1574 /// [aliases]: crate::Command::aliases()
1575 #[inline]
1576 pub fn infer_long_args(self, yes: bool) -> Self {
1577 if yes {
1578 self.global_setting(AppSettings::InferLongArgs)
1579 } else {
1580 self.unset_global_setting(AppSettings::InferLongArgs)
1581 }
1582 }
1583
1584 /// Allow partial matches of [subcommand] names and their [aliases].
1585 ///
1586 /// For example, to match a subcommand named `test`, one could use `t`, `te`, `tes`, and
1587 /// `test`.
1588 ///
1589 /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match `te`
1590 /// to `test` there could not also be a subcommand or alias `temp` because both start with `te`
1591 ///
1592 /// **CAUTION:** This setting can interfere with [positional/free arguments], take care when
1593 /// designing CLIs which allow inferred subcommands and have potential positional/free
1594 /// arguments whose values could start with the same characters as subcommands. If this is the
1595 /// case, it's recommended to use settings such as [`Command::args_conflicts_with_subcommands`] in
1596 /// conjunction with this setting.
1597 ///
1598 /// **NOTE:** This choice is propagated to all child subcommands.
1599 ///
1600 /// # Examples
1601 ///
1602 /// ```no_run
1603 /// # use clap_builder as clap;
1604 /// # use clap::{Command, Arg};
1605 /// let m = Command::new("prog")
1606 /// .infer_subcommands(true)
1607 /// .subcommand(Command::new("test"))
1608 /// .get_matches_from(vec![
1609 /// "prog", "te"
1610 /// ]);
1611 /// assert_eq!(m.subcommand_name(), Some("test"));
1612 /// ```
1613 ///
1614 /// [subcommand]: crate::Command::subcommand()
1615 /// [positional/free arguments]: crate::Arg::index()
1616 /// [aliases]: crate::Command::aliases()
1617 #[inline]
1618 pub fn infer_subcommands(self, yes: bool) -> Self {
1619 if yes {
1620 self.global_setting(AppSettings::InferSubcommands)
1621 } else {
1622 self.unset_global_setting(AppSettings::InferSubcommands)
1623 }
1624 }
1625}
1626
1627/// # Command-specific Settings
1628///
1629/// These apply only to the current command and are not inherited by subcommands.
1630impl Command {
1631 /// (Re)Sets the program's name.
1632 ///
1633 /// See [`Command::new`] for more details.
1634 ///
1635 /// # Examples
1636 ///
1637 /// ```ignore
1638 /// let cmd = clap::command!()
1639 /// .name("foo");
1640 ///
1641 /// // continued logic goes here, such as `cmd.get_matches()` etc.
1642 /// ```
1643 #[must_use]
1644 pub fn name(mut self, name: impl Into<Str>) -> Self {
1645 self.name = name.into();
1646 self
1647 }
1648
1649 /// Overrides the runtime-determined name of the binary for help and error messages.
1650 ///
1651 /// This should only be used when absolutely necessary, such as when the binary name for your
1652 /// application is misleading, or perhaps *not* how the user should invoke your program.
1653 ///
1654 /// **Pro-tip:** When building things such as third party `cargo`
1655 /// subcommands, this setting **should** be used!
1656 ///
1657 /// **NOTE:** This *does not* change or set the name of the binary file on
1658 /// disk. It only changes what clap thinks the name is for the purposes of
1659 /// error or help messages.
1660 ///
1661 /// # Examples
1662 ///
1663 /// ```rust
1664 /// # use clap_builder as clap;
1665 /// # use clap::Command;
1666 /// Command::new("My Program")
1667 /// .bin_name("my_binary")
1668 /// # ;
1669 /// ```
1670 #[must_use]
1671 pub fn bin_name(mut self, name: impl IntoResettable<String>) -> Self {
1672 self.bin_name = name.into_resettable().into_option();
1673 self
1674 }
1675
1676 /// Overrides the runtime-determined display name of the program for help and error messages.
1677 ///
1678 /// # Examples
1679 ///
1680 /// ```rust
1681 /// # use clap_builder as clap;
1682 /// # use clap::Command;
1683 /// Command::new("My Program")
1684 /// .display_name("my_program")
1685 /// # ;
1686 /// ```
1687 #[must_use]
1688 pub fn display_name(mut self, name: impl IntoResettable<String>) -> Self {
1689 self.display_name = name.into_resettable().into_option();
1690 self
1691 }
1692
1693 /// Sets the author(s) for the help message.
1694 ///
1695 /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to
1696 /// automatically set your application's author(s) to the same thing as your
1697 /// crate at compile time.
1698 ///
1699 /// **NOTE:** A custom [`help_template`][Command::help_template] is needed for author to show
1700 /// up.
1701 ///
1702 /// # Examples
1703 ///
1704 /// ```rust
1705 /// # use clap_builder as clap;
1706 /// # use clap::Command;
1707 /// Command::new("myprog")
1708 /// .author("Me, me@mymain.com")
1709 /// # ;
1710 /// ```
1711 #[must_use]
1712 pub fn author(mut self, author: impl IntoResettable<Str>) -> Self {
1713 self.author = author.into_resettable().into_option();
1714 self
1715 }
1716
1717 /// Sets the program's description for the short help (`-h`).
1718 ///
1719 /// If [`Command::long_about`] is not specified, this message will be displayed for `--help`.
1720 ///
1721 /// **NOTE:** Only `Command::about` (short format) is used in completion
1722 /// script generation in order to be concise.
1723 ///
1724 /// See also [`crate_description!`](crate::crate_description!).
1725 ///
1726 /// # Examples
1727 ///
1728 /// ```rust
1729 /// # use clap_builder as clap;
1730 /// # use clap::Command;
1731 /// Command::new("myprog")
1732 /// .about("Does really amazing things for great people")
1733 /// # ;
1734 /// ```
1735 #[must_use]
1736 pub fn about(mut self, about: impl IntoResettable<StyledStr>) -> Self {
1737 self.about = about.into_resettable().into_option();
1738 self
1739 }
1740
1741 /// Sets the program's description for the long help (`--help`).
1742 ///
1743 /// If [`Command::about`] is not specified, this message will be displayed for `-h`.
1744 ///
1745 /// **NOTE:** Only [`Command::about`] (short format) is used in completion
1746 /// script generation in order to be concise.
1747 ///
1748 /// # Examples
1749 ///
1750 /// ```rust
1751 /// # use clap_builder as clap;
1752 /// # use clap::Command;
1753 /// Command::new("myprog")
1754 /// .long_about(
1755 /// "Does really amazing things to great people. Now let's talk a little
1756 /// more in depth about how this subcommand really works. It may take about
1757 /// a few lines of text, but that's ok!")
1758 /// # ;
1759 /// ```
1760 /// [`Command::about`]: Command::about()
1761 #[must_use]
1762 pub fn long_about(mut self, long_about: impl IntoResettable<StyledStr>) -> Self {
1763 self.long_about = long_about.into_resettable().into_option();
1764 self
1765 }
1766
1767 /// Free-form help text for after auto-generated short help (`-h`).
1768 ///
1769 /// This is often used to describe how to use the arguments, caveats to be noted, or license
1770 /// and contact information.
1771 ///
1772 /// If [`Command::after_long_help`] is not specified, this message will be displayed for `--help`.
1773 ///
1774 /// # Examples
1775 ///
1776 /// ```rust
1777 /// # use clap_builder as clap;
1778 /// # use clap::Command;
1779 /// Command::new("myprog")
1780 /// .after_help("Does really amazing things for great people... but be careful with -R!")
1781 /// # ;
1782 /// ```
1783 ///
1784 #[must_use]
1785 pub fn after_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
1786 self.after_help = help.into_resettable().into_option();
1787 self
1788 }
1789
1790 /// Free-form help text for after auto-generated long help (`--help`).
1791 ///
1792 /// This is often used to describe how to use the arguments, caveats to be noted, or license
1793 /// and contact information.
1794 ///
1795 /// If [`Command::after_help`] is not specified, this message will be displayed for `-h`.
1796 ///
1797 /// # Examples
1798 ///
1799 /// ```rust
1800 /// # use clap_builder as clap;
1801 /// # use clap::Command;
1802 /// Command::new("myprog")
1803 /// .after_long_help("Does really amazing things to great people... but be careful with -R, \
1804 /// like, for real, be careful with this!")
1805 /// # ;
1806 /// ```
1807 #[must_use]
1808 pub fn after_long_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
1809 self.after_long_help = help.into_resettable().into_option();
1810 self
1811 }
1812
1813 /// Free-form help text for before auto-generated short help (`-h`).
1814 ///
1815 /// This is often used for header, copyright, or license information.
1816 ///
1817 /// If [`Command::before_long_help`] is not specified, this message will be displayed for `--help`.
1818 ///
1819 /// # Examples
1820 ///
1821 /// ```rust
1822 /// # use clap_builder as clap;
1823 /// # use clap::Command;
1824 /// Command::new("myprog")
1825 /// .before_help("Some info I'd like to appear before the help info")
1826 /// # ;
1827 /// ```
1828 #[must_use]
1829 pub fn before_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
1830 self.before_help = help.into_resettable().into_option();
1831 self
1832 }
1833
1834 /// Free-form help text for before auto-generated long help (`--help`).
1835 ///
1836 /// This is often used for header, copyright, or license information.
1837 ///
1838 /// If [`Command::before_help`] is not specified, this message will be displayed for `-h`.
1839 ///
1840 /// # Examples
1841 ///
1842 /// ```rust
1843 /// # use clap_builder as clap;
1844 /// # use clap::Command;
1845 /// Command::new("myprog")
1846 /// .before_long_help("Some verbose and long info I'd like to appear before the help info")
1847 /// # ;
1848 /// ```
1849 #[must_use]
1850 pub fn before_long_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
1851 self.before_long_help = help.into_resettable().into_option();
1852 self
1853 }
1854
1855 /// Sets the version for the short version (`-V`) and help messages.
1856 ///
1857 /// If [`Command::long_version`] is not specified, this message will be displayed for `--version`.
1858 ///
1859 /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to
1860 /// automatically set your application's version to the same thing as your
1861 /// crate at compile time.
1862 ///
1863 /// # Examples
1864 ///
1865 /// ```rust
1866 /// # use clap_builder as clap;
1867 /// # use clap::Command;
1868 /// Command::new("myprog")
1869 /// .version("v0.1.24")
1870 /// # ;
1871 /// ```
1872 #[must_use]
1873 pub fn version(mut self, ver: impl IntoResettable<Str>) -> Self {
1874 self.version = ver.into_resettable().into_option();
1875 self
1876 }
1877
1878 /// Sets the version for the long version (`--version`) and help messages.
1879 ///
1880 /// If [`Command::version`] is not specified, this message will be displayed for `-V`.
1881 ///
1882 /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to
1883 /// automatically set your application's version to the same thing as your
1884 /// crate at compile time.
1885 ///
1886 /// # Examples
1887 ///
1888 /// ```rust
1889 /// # use clap_builder as clap;
1890 /// # use clap::Command;
1891 /// Command::new("myprog")
1892 /// .long_version(
1893 /// "v0.1.24
1894 /// commit: abcdef89726d
1895 /// revision: 123
1896 /// release: 2
1897 /// binary: myprog")
1898 /// # ;
1899 /// ```
1900 #[must_use]
1901 pub fn long_version(mut self, ver: impl IntoResettable<Str>) -> Self {
1902 self.long_version = ver.into_resettable().into_option();
1903 self
1904 }
1905
1906 /// Overrides the `clap` generated usage string for help and error messages.
1907 ///
1908 /// **NOTE:** Using this setting disables `clap`s "context-aware" usage
1909 /// strings. After this setting is set, this will be *the only* usage string
1910 /// displayed to the user!
1911 ///
1912 /// **NOTE:** Multiple usage lines may be present in the usage argument, but
1913 /// some rules need to be followed to ensure the usage lines are formatted
1914 /// correctly by the default help formatter:
1915 ///
1916 /// - Do not indent the first usage line.
1917 /// - Indent all subsequent usage lines with seven spaces.
1918 /// - The last line must not end with a newline.
1919 ///
1920 /// # Examples
1921 ///
1922 /// ```rust
1923 /// # use clap_builder as clap;
1924 /// # use clap::{Command, Arg};
1925 /// Command::new("myprog")
1926 /// .override_usage("myapp [-clDas] <some_file>")
1927 /// # ;
1928 /// ```
1929 ///
1930 /// Or for multiple usage lines:
1931 ///
1932 /// ```rust
1933 /// # use clap_builder as clap;
1934 /// # use clap::{Command, Arg};
1935 /// Command::new("myprog")
1936 /// .override_usage(
1937 /// "myapp -X [-a] [-b] <file>\n \
1938 /// myapp -Y [-c] <file1> <file2>\n \
1939 /// myapp -Z [-d|-e]"
1940 /// )
1941 /// # ;
1942 /// ```
1943 ///
1944 /// [`ArgMatches::usage`]: ArgMatches::usage()
1945 #[must_use]
1946 pub fn override_usage(mut self, usage: impl IntoResettable<StyledStr>) -> Self {
1947 self.usage_str = usage.into_resettable().into_option();
1948 self
1949 }
1950
1951 /// Overrides the `clap` generated help message (both `-h` and `--help`).
1952 ///
1953 /// This should only be used when the auto-generated message does not suffice.
1954 ///
1955 /// **NOTE:** This **only** replaces the help message for the current
1956 /// command, meaning if you are using subcommands, those help messages will
1957 /// still be auto-generated unless you specify a [`Command::override_help`] for
1958 /// them as well.
1959 ///
1960 /// # Examples
1961 ///
1962 /// ```rust
1963 /// # use clap_builder as clap;
1964 /// # use clap::{Command, Arg};
1965 /// Command::new("myapp")
1966 /// .override_help("myapp v1.0\n\
1967 /// Does awesome things\n\
1968 /// (C) me@mail.com\n\n\
1969 ///
1970 /// Usage: myapp <opts> <command>\n\n\
1971 ///
1972 /// Options:\n\
1973 /// -h, --help Display this message\n\
1974 /// -V, --version Display version info\n\
1975 /// -s <stuff> Do something with stuff\n\
1976 /// -v Be verbose\n\n\
1977 ///
1978 /// Commands:\n\
1979 /// help Print this message\n\
1980 /// work Do some work")
1981 /// # ;
1982 /// ```
1983 #[must_use]
1984 pub fn override_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
1985 self.help_str = help.into_resettable().into_option();
1986 self
1987 }
1988
1989 /// Sets the help template to be used, overriding the default format.
1990 ///
1991 /// **NOTE:** The template system is by design very simple. Therefore, the
1992 /// tags have to be written in the lowercase and without spacing.
1993 ///
1994 /// Tags are given inside curly brackets.
1995 ///
1996 /// Valid tags are:
1997 ///
1998 /// * `{name}` - Display name for the (sub-)command.
1999 /// * `{bin}` - Binary name.(deprecated)
2000 /// * `{version}` - Version number.
2001 /// * `{author}` - Author information.
2002 /// * `{author-with-newline}` - Author followed by `\n`.
2003 /// * `{author-section}` - Author preceded and followed by `\n`.
2004 /// * `{about}` - General description (from [`Command::about`] or
2005 /// [`Command::long_about`]).
2006 /// * `{about-with-newline}` - About followed by `\n`.
2007 /// * `{about-section}` - About preceded and followed by '\n'.
2008 /// * `{usage-heading}` - Automatically generated usage heading.
2009 /// * `{usage}` - Automatically generated or given usage string.
2010 /// * `{all-args}` - Help for all arguments (options, flags, positional
2011 /// arguments, and subcommands) including titles.
2012 /// * `{options}` - Help for options.
2013 /// * `{positionals}` - Help for positional arguments.
2014 /// * `{subcommands}` - Help for subcommands.
2015 /// * `{tab}` - Standard tab sized used within clap
2016 /// * `{after-help}` - Help from [`Command::after_help`] or [`Command::after_long_help`].
2017 /// * `{before-help}` - Help from [`Command::before_help`] or [`Command::before_long_help`].
2018 ///
2019 /// # Examples
2020 ///
2021 /// For a very brief help:
2022 ///
2023 /// ```rust
2024 /// # use clap_builder as clap;
2025 /// # use clap::Command;
2026 /// Command::new("myprog")
2027 /// .version("1.0")
2028 /// .help_template("{name} ({version}) - {usage}")
2029 /// # ;
2030 /// ```
2031 ///
2032 /// For showing more application context:
2033 ///
2034 /// ```rust
2035 /// # use clap_builder as clap;
2036 /// # use clap::Command;
2037 /// Command::new("myprog")
2038 /// .version("1.0")
2039 /// .help_template("\
2040 /// {before-help}{name} {version}
2041 /// {author-with-newline}{about-with-newline}
2042 /// {usage-heading} {usage}
2043 ///
2044 /// {all-args}{after-help}
2045 /// ")
2046 /// # ;
2047 /// ```
2048 /// [`Command::about`]: Command::about()
2049 /// [`Command::long_about`]: Command::long_about()
2050 /// [`Command::after_help`]: Command::after_help()
2051 /// [`Command::after_long_help`]: Command::after_long_help()
2052 /// [`Command::before_help`]: Command::before_help()
2053 /// [`Command::before_long_help`]: Command::before_long_help()
2054 #[must_use]
2055 #[cfg(feature = "help")]
2056 pub fn help_template(mut self, s: impl IntoResettable<StyledStr>) -> Self {
2057 self.template = s.into_resettable().into_option();
2058 self
2059 }
2060
2061 #[inline]
2062 #[must_use]
2063 pub(crate) fn setting(mut self, setting: AppSettings) -> Self {
2064 self.settings.set(setting);
2065 self
2066 }
2067
2068 #[inline]
2069 #[must_use]
2070 pub(crate) fn unset_setting(mut self, setting: AppSettings) -> Self {
2071 self.settings.unset(setting);
2072 self
2073 }
2074
2075 #[inline]
2076 #[must_use]
2077 pub(crate) fn global_setting(mut self, setting: AppSettings) -> Self {
2078 self.settings.set(setting);
2079 self.g_settings.set(setting);
2080 self
2081 }
2082
2083 #[inline]
2084 #[must_use]
2085 pub(crate) fn unset_global_setting(mut self, setting: AppSettings) -> Self {
2086 self.settings.unset(setting);
2087 self.g_settings.unset(setting);
2088 self
2089 }
2090
2091 /// Flatten subcommand help into the current command's help
2092 ///
2093 /// This shows a summary of subcommands within the usage and help for the current command, similar to
2094 /// `git stash --help` showing information on `push`, `pop`, etc.
2095 /// To see more information, a user can still pass `--help` to the individual subcommands.
2096 #[inline]
2097 #[must_use]
2098 pub fn flatten_help(self, yes: bool) -> Self {
2099 if yes {
2100 self.setting(AppSettings::FlattenHelp)
2101 } else {
2102 self.unset_setting(AppSettings::FlattenHelp)
2103 }
2104 }
2105
2106 /// Set the default section heading for future args.
2107 ///
2108 /// This will be used for any arg that hasn't had [`Arg::help_heading`] called.
2109 ///
2110 /// This is useful if the default `Options` or `Arguments` headings are
2111 /// not specific enough for one's use case.
2112 ///
2113 /// For subcommands, see [`Command::subcommand_help_heading`]
2114 ///
2115 /// [`Command::arg`]: Command::arg()
2116 /// [`Arg::help_heading`]: crate::Arg::help_heading()
2117 #[inline]
2118 #[must_use]
2119 pub fn next_help_heading(mut self, heading: impl IntoResettable<Str>) -> Self {
2120 self.current_help_heading = heading.into_resettable().into_option();
2121 self
2122 }
2123
2124 /// Change the starting value for assigning future display orders for args.
2125 ///
2126 /// This will be used for any arg that hasn't had [`Arg::display_order`] called.
2127 #[inline]
2128 #[must_use]
2129 pub fn next_display_order(mut self, disp_ord: impl IntoResettable<usize>) -> Self {
2130 self.current_disp_ord = disp_ord.into_resettable().into_option();
2131 self
2132 }
2133
2134 /// Exit gracefully if no arguments are present (e.g. `$ myprog`).
2135 ///
2136 /// **NOTE:** [`subcommands`] count as arguments
2137 ///
2138 /// # Examples
2139 ///
2140 /// ```rust
2141 /// # use clap_builder as clap;
2142 /// # use clap::{Command};
2143 /// Command::new("myprog")
2144 /// .arg_required_else_help(true);
2145 /// ```
2146 ///
2147 /// [`subcommands`]: crate::Command::subcommand()
2148 /// [`Arg::default_value`]: crate::Arg::default_value()
2149 #[inline]
2150 pub fn arg_required_else_help(self, yes: bool) -> Self {
2151 if yes {
2152 self.setting(AppSettings::ArgRequiredElseHelp)
2153 } else {
2154 self.unset_setting(AppSettings::ArgRequiredElseHelp)
2155 }
2156 }
2157
2158 #[doc(hidden)]
2159 #[cfg_attr(
2160 feature = "deprecated",
2161 deprecated(since = "4.0.0", note = "Replaced with `Arg::allow_hyphen_values`")
2162 )]
2163 pub fn allow_hyphen_values(self, yes: bool) -> Self {
2164 if yes {
2165 self.setting(AppSettings::AllowHyphenValues)
2166 } else {
2167 self.unset_setting(AppSettings::AllowHyphenValues)
2168 }
2169 }
2170
2171 #[doc(hidden)]
2172 #[cfg_attr(
2173 feature = "deprecated",
2174 deprecated(since = "4.0.0", note = "Replaced with `Arg::allow_negative_numbers`")
2175 )]
2176 pub fn allow_negative_numbers(self, yes: bool) -> Self {
2177 if yes {
2178 self.setting(AppSettings::AllowNegativeNumbers)
2179 } else {
2180 self.unset_setting(AppSettings::AllowNegativeNumbers)
2181 }
2182 }
2183
2184 #[doc(hidden)]
2185 #[cfg_attr(
2186 feature = "deprecated",
2187 deprecated(since = "4.0.0", note = "Replaced with `Arg::trailing_var_arg`")
2188 )]
2189 pub fn trailing_var_arg(self, yes: bool) -> Self {
2190 if yes {
2191 self.setting(AppSettings::TrailingVarArg)
2192 } else {
2193 self.unset_setting(AppSettings::TrailingVarArg)
2194 }
2195 }
2196
2197 /// Allows one to implement two styles of CLIs where positionals can be used out of order.
2198 ///
2199 /// The first example is a CLI where the second to last positional argument is optional, but
2200 /// the final positional argument is required. Such as `$ prog [optional] <required>` where one
2201 /// of the two following usages is allowed:
2202 ///
2203 /// * `$ prog [optional] <required>`
2204 /// * `$ prog <required>`
2205 ///
2206 /// This would otherwise not be allowed. This is useful when `[optional]` has a default value.
2207 ///
2208 /// **Note:** when using this style of "missing positionals" the final positional *must* be
2209 /// [required] if `--` will not be used to skip to the final positional argument.
2210 ///
2211 /// **Note:** This style also only allows a single positional argument to be "skipped" without
2212 /// the use of `--`. To skip more than one, see the second example.
2213 ///
2214 /// The second example is when one wants to skip multiple optional positional arguments, and use
2215 /// of the `--` operator is OK (but not required if all arguments will be specified anyways).
2216 ///
2217 /// For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where
2218 /// `baz` accepts multiple values (similar to man `ARGS...` style training arguments).
2219 ///
2220 /// With this setting the following invocations are posisble:
2221 ///
2222 /// * `$ prog foo bar baz1 baz2 baz3`
2223 /// * `$ prog foo -- baz1 baz2 baz3`
2224 /// * `$ prog -- baz1 baz2 baz3`
2225 ///
2226 /// # Examples
2227 ///
2228 /// Style number one from above:
2229 ///
2230 /// ```rust
2231 /// # use clap_builder as clap;
2232 /// # use clap::{Command, Arg};
2233 /// // Assume there is an external subcommand named "subcmd"
2234 /// let m = Command::new("myprog")
2235 /// .allow_missing_positional(true)
2236 /// .arg(Arg::new("arg1"))
2237 /// .arg(Arg::new("arg2")
2238 /// .required(true))
2239 /// .get_matches_from(vec![
2240 /// "prog", "other"
2241 /// ]);
2242 ///
2243 /// assert_eq!(m.get_one::<String>("arg1"), None);
2244 /// assert_eq!(m.get_one::<String>("arg2").unwrap(), "other");
2245 /// ```
2246 ///
2247 /// Now the same example, but using a default value for the first optional positional argument
2248 ///
2249 /// ```rust
2250 /// # use clap_builder as clap;
2251 /// # use clap::{Command, Arg};
2252 /// // Assume there is an external subcommand named "subcmd"
2253 /// let m = Command::new("myprog")
2254 /// .allow_missing_positional(true)
2255 /// .arg(Arg::new("arg1")
2256 /// .default_value("something"))
2257 /// .arg(Arg::new("arg2")
2258 /// .required(true))
2259 /// .get_matches_from(vec![
2260 /// "prog", "other"
2261 /// ]);
2262 ///
2263 /// assert_eq!(m.get_one::<String>("arg1").unwrap(), "something");
2264 /// assert_eq!(m.get_one::<String>("arg2").unwrap(), "other");
2265 /// ```
2266 ///
2267 /// Style number two from above:
2268 ///
2269 /// ```rust
2270 /// # use clap_builder as clap;
2271 /// # use clap::{Command, Arg, ArgAction};
2272 /// // Assume there is an external subcommand named "subcmd"
2273 /// let m = Command::new("myprog")
2274 /// .allow_missing_positional(true)
2275 /// .arg(Arg::new("foo"))
2276 /// .arg(Arg::new("bar"))
2277 /// .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..))
2278 /// .get_matches_from(vec![
2279 /// "prog", "foo", "bar", "baz1", "baz2", "baz3"
2280 /// ]);
2281 ///
2282 /// assert_eq!(m.get_one::<String>("foo").unwrap(), "foo");
2283 /// assert_eq!(m.get_one::<String>("bar").unwrap(), "bar");
2284 /// assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
2285 /// ```
2286 ///
2287 /// Now nofice if we don't specify `foo` or `baz` but use the `--` operator.
2288 ///
2289 /// ```rust
2290 /// # use clap_builder as clap;
2291 /// # use clap::{Command, Arg, ArgAction};
2292 /// // Assume there is an external subcommand named "subcmd"
2293 /// let m = Command::new("myprog")
2294 /// .allow_missing_positional(true)
2295 /// .arg(Arg::new("foo"))
2296 /// .arg(Arg::new("bar"))
2297 /// .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..))
2298 /// .get_matches_from(vec![
2299 /// "prog", "--", "baz1", "baz2", "baz3"
2300 /// ]);
2301 ///
2302 /// assert_eq!(m.get_one::<String>("foo"), None);
2303 /// assert_eq!(m.get_one::<String>("bar"), None);
2304 /// assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
2305 /// ```
2306 ///
2307 /// [required]: crate::Arg::required()
2308 #[inline]
2309 pub fn allow_missing_positional(self, yes: bool) -> Self {
2310 if yes {
2311 self.setting(AppSettings::AllowMissingPositional)
2312 } else {
2313 self.unset_setting(AppSettings::AllowMissingPositional)
2314 }
2315 }
2316}
2317
2318/// # Subcommand-specific Settings
2319impl Command {
2320 /// Sets the short version of the subcommand flag without the preceding `-`.
2321 ///
2322 /// Allows the subcommand to be used as if it were an [`Arg::short`].
2323 ///
2324 /// # Examples
2325 ///
2326 /// ```
2327 /// # use clap_builder as clap;
2328 /// # use clap::{Command, Arg, ArgAction};
2329 /// let matches = Command::new("pacman")
2330 /// .subcommand(
2331 /// Command::new("sync").short_flag('S').arg(
2332 /// Arg::new("search")
2333 /// .short('s')
2334 /// .long("search")
2335 /// .action(ArgAction::SetTrue)
2336 /// .help("search remote repositories for matching strings"),
2337 /// ),
2338 /// )
2339 /// .get_matches_from(vec!["pacman", "-Ss"]);
2340 ///
2341 /// assert_eq!(matches.subcommand_name().unwrap(), "sync");
2342 /// let sync_matches = matches.subcommand_matches("sync").unwrap();
2343 /// assert!(sync_matches.get_flag("search"));
2344 /// ```
2345 /// [`Arg::short`]: Arg::short()
2346 #[must_use]
2347 pub fn short_flag(mut self, short: impl IntoResettable<char>) -> Self {
2348 self.short_flag = short.into_resettable().into_option();
2349 self
2350 }
2351
2352 /// Sets the long version of the subcommand flag without the preceding `--`.
2353 ///
2354 /// Allows the subcommand to be used as if it were an [`Arg::long`].
2355 ///
2356 /// **NOTE:** Any leading `-` characters will be stripped.
2357 ///
2358 /// # Examples
2359 ///
2360 /// To set `long_flag` use a word containing valid UTF-8 codepoints. If you supply a double leading
2361 /// `--` such as `--sync` they will be stripped. Hyphens in the middle of the word; however,
2362 /// will *not* be stripped (i.e. `sync-file` is allowed).
2363 ///
2364 /// ```rust
2365 /// # use clap_builder as clap;
2366 /// # use clap::{Command, Arg, ArgAction};
2367 /// let matches = Command::new("pacman")
2368 /// .subcommand(
2369 /// Command::new("sync").long_flag("sync").arg(
2370 /// Arg::new("search")
2371 /// .short('s')
2372 /// .long("search")
2373 /// .action(ArgAction::SetTrue)
2374 /// .help("search remote repositories for matching strings"),
2375 /// ),
2376 /// )
2377 /// .get_matches_from(vec!["pacman", "--sync", "--search"]);
2378 ///
2379 /// assert_eq!(matches.subcommand_name().unwrap(), "sync");
2380 /// let sync_matches = matches.subcommand_matches("sync").unwrap();
2381 /// assert!(sync_matches.get_flag("search"));
2382 /// ```
2383 ///
2384 /// [`Arg::long`]: Arg::long()
2385 #[must_use]
2386 pub fn long_flag(mut self, long: impl Into<Str>) -> Self {
2387 self.long_flag = Some(long.into());
2388 self
2389 }
2390
2391 /// Sets a hidden alias to this subcommand.
2392 ///
2393 /// This allows the subcommand to be accessed via *either* the original name, or this given
2394 /// alias. This is more efficient and easier than creating multiple hidden subcommands as one
2395 /// only needs to check for the existence of this command, and not all aliased variants.
2396 ///
2397 /// **NOTE:** Aliases defined with this method are *hidden* from the help
2398 /// message. If you're looking for aliases that will be displayed in the help
2399 /// message, see [`Command::visible_alias`].
2400 ///
2401 /// **NOTE:** When using aliases and checking for the existence of a
2402 /// particular subcommand within an [`ArgMatches`] struct, one only needs to
2403 /// search for the original name and not all aliases.
2404 ///
2405 /// # Examples
2406 ///
2407 /// ```rust
2408 /// # use clap_builder as clap;
2409 /// # use clap::{Command, Arg, };
2410 /// let m = Command::new("myprog")
2411 /// .subcommand(Command::new("test")
2412 /// .alias("do-stuff"))
2413 /// .get_matches_from(vec!["myprog", "do-stuff"]);
2414 /// assert_eq!(m.subcommand_name(), Some("test"));
2415 /// ```
2416 /// [`Command::visible_alias`]: Command::visible_alias()
2417 #[must_use]
2418 pub fn alias(mut self, name: impl IntoResettable<Str>) -> Self {
2419 if let Some(name) = name.into_resettable().into_option() {
2420 self.aliases.push((name, false));
2421 } else {
2422 self.aliases.clear();
2423 }
2424 self
2425 }
2426
2427 /// Add an alias, which functions as "hidden" short flag subcommand
2428 ///
2429 /// This will automatically dispatch as if this subcommand was used. This is more efficient,
2430 /// and easier than creating multiple hidden subcommands as one only needs to check for the
2431 /// existence of this command, and not all variants.
2432 ///
2433 /// # Examples
2434 ///
2435 /// ```rust
2436 /// # use clap_builder as clap;
2437 /// # use clap::{Command, Arg, };
2438 /// let m = Command::new("myprog")
2439 /// .subcommand(Command::new("test").short_flag('t')
2440 /// .short_flag_alias('d'))
2441 /// .get_matches_from(vec!["myprog", "-d"]);
2442 /// assert_eq!(m.subcommand_name(), Some("test"));
2443 /// ```
2444 #[must_use]
2445 pub fn short_flag_alias(mut self, name: impl IntoResettable<char>) -> Self {
2446 if let Some(name) = name.into_resettable().into_option() {
2447 debug_assert!(name != '-', "short alias name cannot be `-`");
2448 self.short_flag_aliases.push((name, false));
2449 } else {
2450 self.short_flag_aliases.clear();
2451 }
2452 self
2453 }
2454
2455 /// Add an alias, which functions as a "hidden" long flag subcommand.
2456 ///
2457 /// This will automatically dispatch as if this subcommand was used. This is more efficient,
2458 /// and easier than creating multiple hidden subcommands as one only needs to check for the
2459 /// existence of this command, and not all variants.
2460 ///
2461 /// # Examples
2462 ///
2463 /// ```rust
2464 /// # use clap_builder as clap;
2465 /// # use clap::{Command, Arg, };
2466 /// let m = Command::new("myprog")
2467 /// .subcommand(Command::new("test").long_flag("test")
2468 /// .long_flag_alias("testing"))
2469 /// .get_matches_from(vec!["myprog", "--testing"]);
2470 /// assert_eq!(m.subcommand_name(), Some("test"));
2471 /// ```
2472 #[must_use]
2473 pub fn long_flag_alias(mut self, name: impl IntoResettable<Str>) -> Self {
2474 if let Some(name) = name.into_resettable().into_option() {
2475 self.long_flag_aliases.push((name, false));
2476 } else {
2477 self.long_flag_aliases.clear();
2478 }
2479 self
2480 }
2481
2482 /// Sets multiple hidden aliases to this subcommand.
2483 ///
2484 /// This allows the subcommand to be accessed via *either* the original name or any of the
2485 /// given aliases. This is more efficient, and easier than creating multiple hidden subcommands
2486 /// as one only needs to check for the existence of this command and not all aliased variants.
2487 ///
2488 /// **NOTE:** Aliases defined with this method are *hidden* from the help
2489 /// message. If looking for aliases that will be displayed in the help
2490 /// message, see [`Command::visible_aliases`].
2491 ///
2492 /// **NOTE:** When using aliases and checking for the existence of a
2493 /// particular subcommand within an [`ArgMatches`] struct, one only needs to
2494 /// search for the original name and not all aliases.
2495 ///
2496 /// # Examples
2497 ///
2498 /// ```rust
2499 /// # use clap_builder as clap;
2500 /// # use clap::{Command, Arg};
2501 /// let m = Command::new("myprog")
2502 /// .subcommand(Command::new("test")
2503 /// .aliases(["do-stuff", "do-tests", "tests"]))
2504 /// .arg(Arg::new("input")
2505 /// .help("the file to add")
2506 /// .required(false))
2507 /// .get_matches_from(vec!["myprog", "do-tests"]);
2508 /// assert_eq!(m.subcommand_name(), Some("test"));
2509 /// ```
2510 /// [`Command::visible_aliases`]: Command::visible_aliases()
2511 #[must_use]
2512 pub fn aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self {
2513 self.aliases
2514 .extend(names.into_iter().map(|n| (n.into(), false)));
2515 self
2516 }
2517
2518 /// Add aliases, which function as "hidden" short flag subcommands.
2519 ///
2520 /// These will automatically dispatch as if this subcommand was used. This is more efficient,
2521 /// and easier than creating multiple hidden subcommands as one only needs to check for the
2522 /// existence of this command, and not all variants.
2523 ///
2524 /// # Examples
2525 ///
2526 /// ```rust
2527 /// # use clap_builder as clap;
2528 /// # use clap::{Command, Arg, };
2529 /// let m = Command::new("myprog")
2530 /// .subcommand(Command::new("test").short_flag('t')
2531 /// .short_flag_aliases(['a', 'b', 'c']))
2532 /// .arg(Arg::new("input")
2533 /// .help("the file to add")
2534 /// .required(false))
2535 /// .get_matches_from(vec!["myprog", "-a"]);
2536 /// assert_eq!(m.subcommand_name(), Some("test"));
2537 /// ```
2538 #[must_use]
2539 pub fn short_flag_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self {
2540 for s in names {
2541 debug_assert!(s != '-', "short alias name cannot be `-`");
2542 self.short_flag_aliases.push((s, false));
2543 }
2544 self
2545 }
2546
2547 /// Add aliases, which function as "hidden" long flag subcommands.
2548 ///
2549 /// These will automatically dispatch as if this subcommand was used. This is more efficient,
2550 /// and easier than creating multiple hidden subcommands as one only needs to check for the
2551 /// existence of this command, and not all variants.
2552 ///
2553 /// # Examples
2554 ///
2555 /// ```rust
2556 /// # use clap_builder as clap;
2557 /// # use clap::{Command, Arg, };
2558 /// let m = Command::new("myprog")
2559 /// .subcommand(Command::new("test").long_flag("test")
2560 /// .long_flag_aliases(["testing", "testall", "test_all"]))
2561 /// .arg(Arg::new("input")
2562 /// .help("the file to add")
2563 /// .required(false))
2564 /// .get_matches_from(vec!["myprog", "--testing"]);
2565 /// assert_eq!(m.subcommand_name(), Some("test"));
2566 /// ```
2567 #[must_use]
2568 pub fn long_flag_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self {
2569 for s in names {
2570 self = self.long_flag_alias(s)
2571 }
2572 self
2573 }
2574
2575 /// Sets a visible alias to this subcommand.
2576 ///
2577 /// This allows the subcommand to be accessed via *either* the
2578 /// original name or the given alias. This is more efficient and easier
2579 /// than creating hidden subcommands as one only needs to check for
2580 /// the existence of this command and not all aliased variants.
2581 ///
2582 /// **NOTE:** The alias defined with this method is *visible* from the help
2583 /// message and displayed as if it were just another regular subcommand. If
2584 /// looking for an alias that will not be displayed in the help message, see
2585 /// [`Command::alias`].
2586 ///
2587 /// **NOTE:** When using aliases and checking for the existence of a
2588 /// particular subcommand within an [`ArgMatches`] struct, one only needs to
2589 /// search for the original name and not all aliases.
2590 ///
2591 /// # Examples
2592 ///
2593 /// ```rust
2594 /// # use clap_builder as clap;
2595 /// # use clap::{Command, Arg};
2596 /// let m = Command::new("myprog")
2597 /// .subcommand(Command::new("test")
2598 /// .visible_alias("do-stuff"))
2599 /// .get_matches_from(vec!["myprog", "do-stuff"]);
2600 /// assert_eq!(m.subcommand_name(), Some("test"));
2601 /// ```
2602 /// [`Command::alias`]: Command::alias()
2603 #[must_use]
2604 pub fn visible_alias(mut self, name: impl IntoResettable<Str>) -> Self {
2605 if let Some(name) = name.into_resettable().into_option() {
2606 self.aliases.push((name, true));
2607 } else {
2608 self.aliases.clear();
2609 }
2610 self
2611 }
2612
2613 /// Add an alias, which functions as "visible" short flag subcommand
2614 ///
2615 /// This will automatically dispatch as if this subcommand was used. This is more efficient,
2616 /// and easier than creating multiple hidden subcommands as one only needs to check for the
2617 /// existence of this command, and not all variants.
2618 ///
2619 /// See also [`Command::short_flag_alias`].
2620 ///
2621 /// # Examples
2622 ///
2623 /// ```rust
2624 /// # use clap_builder as clap;
2625 /// # use clap::{Command, Arg, };
2626 /// let m = Command::new("myprog")
2627 /// .subcommand(Command::new("test").short_flag('t')
2628 /// .visible_short_flag_alias('d'))
2629 /// .get_matches_from(vec!["myprog", "-d"]);
2630 /// assert_eq!(m.subcommand_name(), Some("test"));
2631 /// ```
2632 /// [`Command::short_flag_alias`]: Command::short_flag_alias()
2633 #[must_use]
2634 pub fn visible_short_flag_alias(mut self, name: impl IntoResettable<char>) -> Self {
2635 if let Some(name) = name.into_resettable().into_option() {
2636 debug_assert!(name != '-', "short alias name cannot be `-`");
2637 self.short_flag_aliases.push((name, true));
2638 } else {
2639 self.short_flag_aliases.clear();
2640 }
2641 self
2642 }
2643
2644 /// Add an alias, which functions as a "visible" long flag subcommand.
2645 ///
2646 /// This will automatically dispatch as if this subcommand was used. This is more efficient,
2647 /// and easier than creating multiple hidden subcommands as one only needs to check for the
2648 /// existence of this command, and not all variants.
2649 ///
2650 /// See also [`Command::long_flag_alias`].
2651 ///
2652 /// # Examples
2653 ///
2654 /// ```rust
2655 /// # use clap_builder as clap;
2656 /// # use clap::{Command, Arg, };
2657 /// let m = Command::new("myprog")
2658 /// .subcommand(Command::new("test").long_flag("test")
2659 /// .visible_long_flag_alias("testing"))
2660 /// .get_matches_from(vec!["myprog", "--testing"]);
2661 /// assert_eq!(m.subcommand_name(), Some("test"));
2662 /// ```
2663 /// [`Command::long_flag_alias`]: Command::long_flag_alias()
2664 #[must_use]
2665 pub fn visible_long_flag_alias(mut self, name: impl IntoResettable<Str>) -> Self {
2666 if let Some(name) = name.into_resettable().into_option() {
2667 self.long_flag_aliases.push((name, true));
2668 } else {
2669 self.long_flag_aliases.clear();
2670 }
2671 self
2672 }
2673
2674 /// Sets multiple visible aliases to this subcommand.
2675 ///
2676 /// This allows the subcommand to be accessed via *either* the
2677 /// original name or any of the given aliases. This is more efficient and easier
2678 /// than creating multiple hidden subcommands as one only needs to check for
2679 /// the existence of this command and not all aliased variants.
2680 ///
2681 /// **NOTE:** The alias defined with this method is *visible* from the help
2682 /// message and displayed as if it were just another regular subcommand. If
2683 /// looking for an alias that will not be displayed in the help message, see
2684 /// [`Command::alias`].
2685 ///
2686 /// **NOTE:** When using aliases, and checking for the existence of a
2687 /// particular subcommand within an [`ArgMatches`] struct, one only needs to
2688 /// search for the original name and not all aliases.
2689 ///
2690 /// # Examples
2691 ///
2692 /// ```rust
2693 /// # use clap_builder as clap;
2694 /// # use clap::{Command, Arg, };
2695 /// let m = Command::new("myprog")
2696 /// .subcommand(Command::new("test")
2697 /// .visible_aliases(["do-stuff", "tests"]))
2698 /// .get_matches_from(vec!["myprog", "do-stuff"]);
2699 /// assert_eq!(m.subcommand_name(), Some("test"));
2700 /// ```
2701 /// [`Command::alias`]: Command::alias()
2702 #[must_use]
2703 pub fn visible_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self {
2704 self.aliases
2705 .extend(names.into_iter().map(|n| (n.into(), true)));
2706 self
2707 }
2708
2709 /// Add aliases, which function as *visible* short flag subcommands.
2710 ///
2711 /// See [`Command::short_flag_aliases`].
2712 ///
2713 /// # Examples
2714 ///
2715 /// ```rust
2716 /// # use clap_builder as clap;
2717 /// # use clap::{Command, Arg, };
2718 /// let m = Command::new("myprog")
2719 /// .subcommand(Command::new("test").short_flag('b')
2720 /// .visible_short_flag_aliases(['t']))
2721 /// .get_matches_from(vec!["myprog", "-t"]);
2722 /// assert_eq!(m.subcommand_name(), Some("test"));
2723 /// ```
2724 /// [`Command::short_flag_aliases`]: Command::short_flag_aliases()
2725 #[must_use]
2726 pub fn visible_short_flag_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self {
2727 for s in names {
2728 debug_assert!(s != '-', "short alias name cannot be `-`");
2729 self.short_flag_aliases.push((s, true));
2730 }
2731 self
2732 }
2733
2734 /// Add aliases, which function as *visible* long flag subcommands.
2735 ///
2736 /// See [`Command::long_flag_aliases`].
2737 ///
2738 /// # Examples
2739 ///
2740 /// ```rust
2741 /// # use clap_builder as clap;
2742 /// # use clap::{Command, Arg, };
2743 /// let m = Command::new("myprog")
2744 /// .subcommand(Command::new("test").long_flag("test")
2745 /// .visible_long_flag_aliases(["testing", "testall", "test_all"]))
2746 /// .get_matches_from(vec!["myprog", "--testing"]);
2747 /// assert_eq!(m.subcommand_name(), Some("test"));
2748 /// ```
2749 /// [`Command::long_flag_aliases`]: Command::long_flag_aliases()
2750 #[must_use]
2751 pub fn visible_long_flag_aliases(
2752 mut self,
2753 names: impl IntoIterator<Item = impl Into<Str>>,
2754 ) -> Self {
2755 for s in names {
2756 self = self.visible_long_flag_alias(s);
2757 }
2758 self
2759 }
2760
2761 /// Set the placement of this subcommand within the help.
2762 ///
2763 /// Subcommands with a lower value will be displayed first in the help message.
2764 /// Those with the same display order will be sorted.
2765 ///
2766 /// `Command`s are automatically assigned a display order based on the order they are added to
2767 /// their parent [`Command`].
2768 /// Overriding this is helpful when the order commands are added in isn't the same as the
2769 /// display order, whether in one-off cases or to automatically sort commands.
2770 ///
2771 /// # Examples
2772 ///
2773 /// ```rust
2774 /// # #[cfg(feature = "help")] {
2775 /// # use clap_builder as clap;
2776 /// # use clap::{Command, };
2777 /// let m = Command::new("cust-ord")
2778 /// .subcommand(Command::new("beta")
2779 /// .display_order(0) // Sort
2780 /// .about("Some help and text"))
2781 /// .subcommand(Command::new("alpha")
2782 /// .display_order(0) // Sort
2783 /// .about("I should be first!"))
2784 /// .get_matches_from(vec![
2785 /// "cust-ord", "--help"
2786 /// ]);
2787 /// # }
2788 /// ```
2789 ///
2790 /// The above example displays the following help message
2791 ///
2792 /// ```text
2793 /// cust-ord
2794 ///
2795 /// Usage: cust-ord [OPTIONS]
2796 ///
2797 /// Commands:
2798 /// alpha I should be first!
2799 /// beta Some help and text
2800 /// help Print help for the subcommand(s)
2801 ///
2802 /// Options:
2803 /// -h, --help Print help
2804 /// -V, --version Print version
2805 /// ```
2806 #[inline]
2807 #[must_use]
2808 pub fn display_order(mut self, ord: impl IntoResettable<usize>) -> Self {
2809 self.disp_ord = ord.into_resettable().into_option();
2810 self
2811 }
2812
2813 /// Specifies that this [`subcommand`] should be hidden from help messages
2814 ///
2815 /// # Examples
2816 ///
2817 /// ```rust
2818 /// # use clap_builder as clap;
2819 /// # use clap::{Command, Arg};
2820 /// Command::new("myprog")
2821 /// .subcommand(
2822 /// Command::new("test").hide(true)
2823 /// )
2824 /// # ;
2825 /// ```
2826 ///
2827 /// [`subcommand`]: crate::Command::subcommand()
2828 #[inline]
2829 pub fn hide(self, yes: bool) -> Self {
2830 if yes {
2831 self.setting(AppSettings::Hidden)
2832 } else {
2833 self.unset_setting(AppSettings::Hidden)
2834 }
2835 }
2836
2837 /// If no [`subcommand`] is present at runtime, error and exit gracefully.
2838 ///
2839 /// # Examples
2840 ///
2841 /// ```rust
2842 /// # use clap_builder as clap;
2843 /// # use clap::{Command, error::ErrorKind};
2844 /// let err = Command::new("myprog")
2845 /// .subcommand_required(true)
2846 /// .subcommand(Command::new("test"))
2847 /// .try_get_matches_from(vec![
2848 /// "myprog",
2849 /// ]);
2850 /// assert!(err.is_err());
2851 /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand);
2852 /// # ;
2853 /// ```
2854 ///
2855 /// [`subcommand`]: crate::Command::subcommand()
2856 pub fn subcommand_required(self, yes: bool) -> Self {
2857 if yes {
2858 self.setting(AppSettings::SubcommandRequired)
2859 } else {
2860 self.unset_setting(AppSettings::SubcommandRequired)
2861 }
2862 }
2863
2864 /// Assume unexpected positional arguments are a [`subcommand`].
2865 ///
2866 /// Arguments will be stored in the `""` argument in the [`ArgMatches`]
2867 ///
2868 /// **NOTE:** Use this setting with caution,
2869 /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand)
2870 /// will **not** cause an error and instead be treated as a potential subcommand.
2871 /// One should check for such cases manually and inform the user appropriately.
2872 ///
2873 /// **NOTE:** A built-in subcommand will be parsed as an external subcommand when escaped with
2874 /// `--`.
2875 ///
2876 /// # Examples
2877 ///
2878 /// ```rust
2879 /// # use clap_builder as clap;
2880 /// # use std::ffi::OsString;
2881 /// # use clap::Command;
2882 /// // Assume there is an external subcommand named "subcmd"
2883 /// let m = Command::new("myprog")
2884 /// .allow_external_subcommands(true)
2885 /// .get_matches_from(vec![
2886 /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
2887 /// ]);
2888 ///
2889 /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
2890 /// // string argument name
2891 /// match m.subcommand() {
2892 /// Some((external, ext_m)) => {
2893 /// let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect();
2894 /// assert_eq!(external, "subcmd");
2895 /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
2896 /// },
2897 /// _ => {},
2898 /// }
2899 /// ```
2900 ///
2901 /// [`subcommand`]: crate::Command::subcommand()
2902 /// [`ArgMatches`]: crate::ArgMatches
2903 /// [`ErrorKind::UnknownArgument`]: crate::error::ErrorKind::UnknownArgument
2904 pub fn allow_external_subcommands(self, yes: bool) -> Self {
2905 if yes {
2906 self.setting(AppSettings::AllowExternalSubcommands)
2907 } else {
2908 self.unset_setting(AppSettings::AllowExternalSubcommands)
2909 }
2910 }
2911
2912 /// Specifies how to parse external subcommand arguments.
2913 ///
2914 /// The default parser is for `OsString`. This can be used to switch it to `String` or another
2915 /// type.
2916 ///
2917 /// **NOTE:** Setting this requires [`Command::allow_external_subcommands`]
2918 ///
2919 /// # Examples
2920 ///
2921 /// ```rust
2922 /// # #[cfg(unix)] {
2923 /// # use clap_builder as clap;
2924 /// # use std::ffi::OsString;
2925 /// # use clap::Command;
2926 /// # use clap::value_parser;
2927 /// // Assume there is an external subcommand named "subcmd"
2928 /// let m = Command::new("myprog")
2929 /// .allow_external_subcommands(true)
2930 /// .get_matches_from(vec![
2931 /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
2932 /// ]);
2933 ///
2934 /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
2935 /// // string argument name
2936 /// match m.subcommand() {
2937 /// Some((external, ext_m)) => {
2938 /// let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect();
2939 /// assert_eq!(external, "subcmd");
2940 /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
2941 /// },
2942 /// _ => {},
2943 /// }
2944 /// # }
2945 /// ```
2946 ///
2947 /// ```rust
2948 /// # use clap_builder as clap;
2949 /// # use clap::Command;
2950 /// # use clap::value_parser;
2951 /// // Assume there is an external subcommand named "subcmd"
2952 /// let m = Command::new("myprog")
2953 /// .external_subcommand_value_parser(value_parser!(String))
2954 /// .get_matches_from(vec![
2955 /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
2956 /// ]);
2957 ///
2958 /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
2959 /// // string argument name
2960 /// match m.subcommand() {
2961 /// Some((external, ext_m)) => {
2962 /// let ext_args: Vec<_> = ext_m.get_many::<String>("").unwrap().collect();
2963 /// assert_eq!(external, "subcmd");
2964 /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
2965 /// },
2966 /// _ => {},
2967 /// }
2968 /// ```
2969 ///
2970 /// [`subcommands`]: crate::Command::subcommand()
2971 pub fn external_subcommand_value_parser(
2972 mut self,
2973 parser: impl IntoResettable<super::ValueParser>,
2974 ) -> Self {
2975 self.external_value_parser = parser.into_resettable().into_option();
2976 self
2977 }
2978
2979 /// Specifies that use of an argument prevents the use of [`subcommands`].
2980 ///
2981 /// By default `clap` allows arguments between subcommands such
2982 /// as `<cmd> [cmd_args] <subcmd> [subcmd_args] <subsubcmd> [subsubcmd_args]`.
2983 ///
2984 /// This setting disables that functionality and says that arguments can
2985 /// only follow the *final* subcommand. For instance using this setting
2986 /// makes only the following invocations possible:
2987 ///
2988 /// * `<cmd> <subcmd> <subsubcmd> [subsubcmd_args]`
2989 /// * `<cmd> <subcmd> [subcmd_args]`
2990 /// * `<cmd> [cmd_args]`
2991 ///
2992 /// # Examples
2993 ///
2994 /// ```rust
2995 /// # use clap_builder as clap;
2996 /// # use clap::Command;
2997 /// Command::new("myprog")
2998 /// .args_conflicts_with_subcommands(true);
2999 /// ```
3000 ///
3001 /// [`subcommands`]: crate::Command::subcommand()
3002 pub fn args_conflicts_with_subcommands(self, yes: bool) -> Self {
3003 if yes {
3004 self.setting(AppSettings::ArgsNegateSubcommands)
3005 } else {
3006 self.unset_setting(AppSettings::ArgsNegateSubcommands)
3007 }
3008 }
3009
3010 /// Prevent subcommands from being consumed as an arguments value.
3011 ///
3012 /// By default, if an option taking multiple values is followed by a subcommand, the
3013 /// subcommand will be parsed as another value.
3014 ///
3015 /// ```text
3016 /// cmd --foo val1 val2 subcommand
3017 /// --------- ----------
3018 /// values another value
3019 /// ```
3020 ///
3021 /// This setting instructs the parser to stop when encountering a subcommand instead of
3022 /// greedily consuming arguments.
3023 ///
3024 /// ```text
3025 /// cmd --foo val1 val2 subcommand
3026 /// --------- ----------
3027 /// values subcommand
3028 /// ```
3029 ///
3030 /// # Examples
3031 ///
3032 /// ```rust
3033 /// # use clap_builder as clap;
3034 /// # use clap::{Command, Arg, ArgAction};
3035 /// let cmd = Command::new("cmd").subcommand(Command::new("sub")).arg(
3036 /// Arg::new("arg")
3037 /// .long("arg")
3038 /// .num_args(1..)
3039 /// .action(ArgAction::Set),
3040 /// );
3041 ///
3042 /// let matches = cmd
3043 /// .clone()
3044 /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
3045 /// .unwrap();
3046 /// assert_eq!(
3047 /// matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(),
3048 /// &["1", "2", "3", "sub"]
3049 /// );
3050 /// assert!(matches.subcommand_matches("sub").is_none());
3051 ///
3052 /// let matches = cmd
3053 /// .subcommand_precedence_over_arg(true)
3054 /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
3055 /// .unwrap();
3056 /// assert_eq!(
3057 /// matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(),
3058 /// &["1", "2", "3"]
3059 /// );
3060 /// assert!(matches.subcommand_matches("sub").is_some());
3061 /// ```
3062 pub fn subcommand_precedence_over_arg(self, yes: bool) -> Self {
3063 if yes {
3064 self.setting(AppSettings::SubcommandPrecedenceOverArg)
3065 } else {
3066 self.unset_setting(AppSettings::SubcommandPrecedenceOverArg)
3067 }
3068 }
3069
3070 /// Allows [`subcommands`] to override all requirements of the parent command.
3071 ///
3072 /// For example, if you had a subcommand or top level application with a required argument
3073 /// that is only required as long as there is no subcommand present,
3074 /// using this setting would allow you to set those arguments to [`Arg::required(true)`]
3075 /// and yet receive no error so long as the user uses a valid subcommand instead.
3076 ///
3077 /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements)
3078 ///
3079 /// # Examples
3080 ///
3081 /// This first example shows that it is an error to not use a required argument
3082 ///
3083 /// ```rust
3084 /// # use clap_builder as clap;
3085 /// # use clap::{Command, Arg, error::ErrorKind};
3086 /// let err = Command::new("myprog")
3087 /// .subcommand_negates_reqs(true)
3088 /// .arg(Arg::new("opt").required(true))
3089 /// .subcommand(Command::new("test"))
3090 /// .try_get_matches_from(vec![
3091 /// "myprog"
3092 /// ]);
3093 /// assert!(err.is_err());
3094 /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3095 /// # ;
3096 /// ```
3097 ///
3098 /// This next example shows that it is no longer error to not use a required argument if a
3099 /// valid subcommand is used.
3100 ///
3101 /// ```rust
3102 /// # use clap_builder as clap;
3103 /// # use clap::{Command, Arg, error::ErrorKind};
3104 /// let noerr = Command::new("myprog")
3105 /// .subcommand_negates_reqs(true)
3106 /// .arg(Arg::new("opt").required(true))
3107 /// .subcommand(Command::new("test"))
3108 /// .try_get_matches_from(vec![
3109 /// "myprog", "test"
3110 /// ]);
3111 /// assert!(noerr.is_ok());
3112 /// # ;
3113 /// ```
3114 ///
3115 /// [`Arg::required(true)`]: crate::Arg::required()
3116 /// [`subcommands`]: crate::Command::subcommand()
3117 pub fn subcommand_negates_reqs(self, yes: bool) -> Self {
3118 if yes {
3119 self.setting(AppSettings::SubcommandsNegateReqs)
3120 } else {
3121 self.unset_setting(AppSettings::SubcommandsNegateReqs)
3122 }
3123 }
3124
3125 /// Multiple-personality program dispatched on the binary name (`argv[0]`)
3126 ///
3127 /// A "multicall" executable is a single executable
3128 /// that contains a variety of applets,
3129 /// and decides which applet to run based on the name of the file.
3130 /// The executable can be called from different names by creating hard links
3131 /// or symbolic links to it.
3132 ///
3133 /// This is desirable for:
3134 /// - Easy distribution, a single binary that can install hardlinks to access the different
3135 /// personalities.
3136 /// - Minimal binary size by sharing common code (e.g. standard library, clap)
3137 /// - Custom shells or REPLs where there isn't a single top-level command
3138 ///
3139 /// Setting `multicall` will cause
3140 /// - `argv[0]` to be stripped to the base name and parsed as the first argument, as if
3141 /// [`Command::no_binary_name`][Command::no_binary_name] was set.
3142 /// - Help and errors to report subcommands as if they were the top-level command
3143 ///
3144 /// When the subcommand is not present, there are several strategies you may employ, depending
3145 /// on your needs:
3146 /// - Let the error percolate up normally
3147 /// - Print a specialized error message using the
3148 /// [`Error::context`][crate::Error::context]
3149 /// - Print the [help][Command::write_help] but this might be ambiguous
3150 /// - Disable `multicall` and re-parse it
3151 /// - Disable `multicall` and re-parse it with a specific subcommand
3152 ///
3153 /// When detecting the error condition, the [`ErrorKind`] isn't sufficient as a sub-subcommand
3154 /// might report the same error. Enable
3155 /// [`allow_external_subcommands`][Command::allow_external_subcommands] if you want to specifically
3156 /// get the unrecognized binary name.
3157 ///
3158 /// **NOTE:** Multicall can't be used with [`no_binary_name`] since they interpret
3159 /// the command name in incompatible ways.
3160 ///
3161 /// **NOTE:** The multicall command cannot have arguments.
3162 ///
3163 /// **NOTE:** Applets are slightly semantically different from subcommands,
3164 /// so it's recommended to use [`Command::subcommand_help_heading`] and
3165 /// [`Command::subcommand_value_name`] to change the descriptive text as above.
3166 ///
3167 /// # Examples
3168 ///
3169 /// `hostname` is an example of a multicall executable.
3170 /// Both `hostname` and `dnsdomainname` are provided by the same executable
3171 /// and which behaviour to use is based on the executable file name.
3172 ///
3173 /// This is desirable when the executable has a primary purpose
3174 /// but there is related functionality that would be convenient to provide
3175 /// and implement it to be in the same executable.
3176 ///
3177 /// The name of the cmd is essentially unused
3178 /// and may be the same as the name of a subcommand.
3179 ///
3180 /// The names of the immediate subcommands of the Command
3181 /// are matched against the basename of the first argument,
3182 /// which is conventionally the path of the executable.
3183 ///
3184 /// This does not allow the subcommand to be passed as the first non-path argument.
3185 ///
3186 /// ```rust
3187 /// # use clap_builder as clap;
3188 /// # use clap::{Command, error::ErrorKind};
3189 /// let mut cmd = Command::new("hostname")
3190 /// .multicall(true)
3191 /// .subcommand(Command::new("hostname"))
3192 /// .subcommand(Command::new("dnsdomainname"));
3193 /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/hostname", "dnsdomainname"]);
3194 /// assert!(m.is_err());
3195 /// assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument);
3196 /// let m = cmd.get_matches_from(&["/usr/bin/dnsdomainname"]);
3197 /// assert_eq!(m.subcommand_name(), Some("dnsdomainname"));
3198 /// ```
3199 ///
3200 /// Busybox is another common example of a multicall executable
3201 /// with a subcommmand for each applet that can be run directly,
3202 /// e.g. with the `cat` applet being run by running `busybox cat`,
3203 /// or with `cat` as a link to the `busybox` binary.
3204 ///
3205 /// This is desirable when the launcher program has additional options
3206 /// or it is useful to run the applet without installing a symlink
3207 /// e.g. to test the applet without installing it
3208 /// or there may already be a command of that name installed.
3209 ///
3210 /// To make an applet usable as both a multicall link and a subcommand
3211 /// the subcommands must be defined both in the top-level Command
3212 /// and as subcommands of the "main" applet.
3213 ///
3214 /// ```rust
3215 /// # use clap_builder as clap;
3216 /// # use clap::Command;
3217 /// fn applet_commands() -> [Command; 2] {
3218 /// [Command::new("true"), Command::new("false")]
3219 /// }
3220 /// let mut cmd = Command::new("busybox")
3221 /// .multicall(true)
3222 /// .subcommand(
3223 /// Command::new("busybox")
3224 /// .subcommand_value_name("APPLET")
3225 /// .subcommand_help_heading("APPLETS")
3226 /// .subcommands(applet_commands()),
3227 /// )
3228 /// .subcommands(applet_commands());
3229 /// // When called from the executable's canonical name
3230 /// // its applets can be matched as subcommands.
3231 /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/busybox", "true"]).unwrap();
3232 /// assert_eq!(m.subcommand_name(), Some("busybox"));
3233 /// assert_eq!(m.subcommand().unwrap().1.subcommand_name(), Some("true"));
3234 /// // When called from a link named after an applet that applet is matched.
3235 /// let m = cmd.get_matches_from(&["/usr/bin/true"]);
3236 /// assert_eq!(m.subcommand_name(), Some("true"));
3237 /// ```
3238 ///
3239 /// [`no_binary_name`]: crate::Command::no_binary_name
3240 /// [`Command::subcommand_value_name`]: crate::Command::subcommand_value_name
3241 /// [`Command::subcommand_help_heading`]: crate::Command::subcommand_help_heading
3242 #[inline]
3243 pub fn multicall(self, yes: bool) -> Self {
3244 if yes {
3245 self.setting(AppSettings::Multicall)
3246 } else {
3247 self.unset_setting(AppSettings::Multicall)
3248 }
3249 }
3250
3251 /// Sets the value name used for subcommands when printing usage and help.
3252 ///
3253 /// By default, this is "COMMAND".
3254 ///
3255 /// See also [`Command::subcommand_help_heading`]
3256 ///
3257 /// # Examples
3258 ///
3259 /// ```rust
3260 /// # use clap_builder as clap;
3261 /// # use clap::{Command, Arg};
3262 /// Command::new("myprog")
3263 /// .subcommand(Command::new("sub1"))
3264 /// .print_help()
3265 /// # ;
3266 /// ```
3267 ///
3268 /// will produce
3269 ///
3270 /// ```text
3271 /// myprog
3272 ///
3273 /// Usage: myprog [COMMAND]
3274 ///
3275 /// Commands:
3276 /// help Print this message or the help of the given subcommand(s)
3277 /// sub1
3278 ///
3279 /// Options:
3280 /// -h, --help Print help
3281 /// -V, --version Print version
3282 /// ```
3283 ///
3284 /// but usage of `subcommand_value_name`
3285 ///
3286 /// ```rust
3287 /// # use clap_builder as clap;
3288 /// # use clap::{Command, Arg};
3289 /// Command::new("myprog")
3290 /// .subcommand(Command::new("sub1"))
3291 /// .subcommand_value_name("THING")
3292 /// .print_help()
3293 /// # ;
3294 /// ```
3295 ///
3296 /// will produce
3297 ///
3298 /// ```text
3299 /// myprog
3300 ///
3301 /// Usage: myprog [THING]
3302 ///
3303 /// Commands:
3304 /// help Print this message or the help of the given subcommand(s)
3305 /// sub1
3306 ///
3307 /// Options:
3308 /// -h, --help Print help
3309 /// -V, --version Print version
3310 /// ```
3311 #[must_use]
3312 pub fn subcommand_value_name(mut self, value_name: impl IntoResettable<Str>) -> Self {
3313 self.subcommand_value_name = value_name.into_resettable().into_option();
3314 self
3315 }
3316
3317 /// Sets the help heading used for subcommands when printing usage and help.
3318 ///
3319 /// By default, this is "Commands".
3320 ///
3321 /// See also [`Command::subcommand_value_name`]
3322 ///
3323 /// # Examples
3324 ///
3325 /// ```rust
3326 /// # use clap_builder as clap;
3327 /// # use clap::{Command, Arg};
3328 /// Command::new("myprog")
3329 /// .subcommand(Command::new("sub1"))
3330 /// .print_help()
3331 /// # ;
3332 /// ```
3333 ///
3334 /// will produce
3335 ///
3336 /// ```text
3337 /// myprog
3338 ///
3339 /// Usage: myprog [COMMAND]
3340 ///
3341 /// Commands:
3342 /// help Print this message or the help of the given subcommand(s)
3343 /// sub1
3344 ///
3345 /// Options:
3346 /// -h, --help Print help
3347 /// -V, --version Print version
3348 /// ```
3349 ///
3350 /// but usage of `subcommand_help_heading`
3351 ///
3352 /// ```rust
3353 /// # use clap_builder as clap;
3354 /// # use clap::{Command, Arg};
3355 /// Command::new("myprog")
3356 /// .subcommand(Command::new("sub1"))
3357 /// .subcommand_help_heading("Things")
3358 /// .print_help()
3359 /// # ;
3360 /// ```
3361 ///
3362 /// will produce
3363 ///
3364 /// ```text
3365 /// myprog
3366 ///
3367 /// Usage: myprog [COMMAND]
3368 ///
3369 /// Things:
3370 /// help Print this message or the help of the given subcommand(s)
3371 /// sub1
3372 ///
3373 /// Options:
3374 /// -h, --help Print help
3375 /// -V, --version Print version
3376 /// ```
3377 #[must_use]
3378 pub fn subcommand_help_heading(mut self, heading: impl IntoResettable<Str>) -> Self {
3379 self.subcommand_heading = heading.into_resettable().into_option();
3380 self
3381 }
3382}
3383
3384/// # Reflection
3385impl Command {
3386 #[inline]
3387 #[cfg(feature = "usage")]
3388 pub(crate) fn get_usage_name(&self) -> Option<&str> {
3389 self.usage_name.as_deref()
3390 }
3391
3392 #[inline]
3393 #[cfg(feature = "usage")]
3394 pub(crate) fn get_usage_name_fallback(&self) -> &str {
3395 self.get_usage_name()
3396 .unwrap_or_else(|| self.get_bin_name_fallback())
3397 }
3398
3399 #[inline]
3400 #[cfg(not(feature = "usage"))]
3401 #[allow(dead_code)]
3402 pub(crate) fn get_usage_name_fallback(&self) -> &str {
3403 self.get_bin_name_fallback()
3404 }
3405
3406 /// Get the name of the binary.
3407 #[inline]
3408 pub fn get_display_name(&self) -> Option<&str> {
3409 self.display_name.as_deref()
3410 }
3411
3412 /// Get the name of the binary.
3413 #[inline]
3414 pub fn get_bin_name(&self) -> Option<&str> {
3415 self.bin_name.as_deref()
3416 }
3417
3418 /// Get the name of the binary.
3419 #[inline]
3420 pub(crate) fn get_bin_name_fallback(&self) -> &str {
3421 self.bin_name.as_deref().unwrap_or_else(|| self.get_name())
3422 }
3423
3424 /// Set binary name. Uses `&mut self` instead of `self`.
3425 pub fn set_bin_name(&mut self, name: impl Into<String>) {
3426 self.bin_name = Some(name.into());
3427 }
3428
3429 /// Get the name of the cmd.
3430 #[inline]
3431 pub fn get_name(&self) -> &str {
3432 self.name.as_str()
3433 }
3434
3435 #[inline]
3436 #[cfg(debug_assertions)]
3437 pub(crate) fn get_name_str(&self) -> &Str {
3438 &self.name
3439 }
3440
3441 /// Get the version of the cmd.
3442 #[inline]
3443 pub fn get_version(&self) -> Option<&str> {
3444 self.version.as_deref()
3445 }
3446
3447 /// Get the long version of the cmd.
3448 #[inline]
3449 pub fn get_long_version(&self) -> Option<&str> {
3450 self.long_version.as_deref()
3451 }
3452
3453 /// Get the authors of the cmd.
3454 #[inline]
3455 pub fn get_author(&self) -> Option<&str> {
3456 self.author.as_deref()
3457 }
3458
3459 /// Get the short flag of the subcommand.
3460 #[inline]
3461 pub fn get_short_flag(&self) -> Option<char> {
3462 self.short_flag
3463 }
3464
3465 /// Get the long flag of the subcommand.
3466 #[inline]
3467 pub fn get_long_flag(&self) -> Option<&str> {
3468 self.long_flag.as_deref()
3469 }
3470
3471 /// Get the help message specified via [`Command::about`].
3472 ///
3473 /// [`Command::about`]: Command::about()
3474 #[inline]
3475 pub fn get_about(&self) -> Option<&StyledStr> {
3476 self.about.as_ref()
3477 }
3478
3479 /// Get the help message specified via [`Command::long_about`].
3480 ///
3481 /// [`Command::long_about`]: Command::long_about()
3482 #[inline]
3483 pub fn get_long_about(&self) -> Option<&StyledStr> {
3484 self.long_about.as_ref()
3485 }
3486
3487 /// Get the custom section heading specified via [`Command::flatten_help`].
3488 #[inline]
3489 pub fn is_flatten_help_set(&self) -> bool {
3490 self.is_set(AppSettings::FlattenHelp)
3491 }
3492
3493 /// Get the custom section heading specified via [`Command::next_help_heading`].
3494 ///
3495 /// [`Command::help_heading`]: Command::help_heading()
3496 #[inline]
3497 pub fn get_next_help_heading(&self) -> Option<&str> {
3498 self.current_help_heading.as_deref()
3499 }
3500
3501 /// Iterate through the *visible* aliases for this subcommand.
3502 #[inline]
3503 pub fn get_visible_aliases(&self) -> impl Iterator<Item = &str> + '_ {
3504 self.aliases
3505 .iter()
3506 .filter(|(_, vis)| *vis)
3507 .map(|a| a.0.as_str())
3508 }
3509
3510 /// Iterate through the *visible* short aliases for this subcommand.
3511 #[inline]
3512 pub fn get_visible_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ {
3513 self.short_flag_aliases
3514 .iter()
3515 .filter(|(_, vis)| *vis)
3516 .map(|a| a.0)
3517 }
3518
3519 /// Iterate through the *visible* long aliases for this subcommand.
3520 #[inline]
3521 pub fn get_visible_long_flag_aliases(&self) -> impl Iterator<Item = &str> + '_ {
3522 self.long_flag_aliases
3523 .iter()
3524 .filter(|(_, vis)| *vis)
3525 .map(|a| a.0.as_str())
3526 }
3527
3528 /// Iterate through the set of *all* the aliases for this subcommand, both visible and hidden.
3529 #[inline]
3530 pub fn get_all_aliases(&self) -> impl Iterator<Item = &str> + '_ {
3531 self.aliases.iter().map(|a| a.0.as_str())
3532 }
3533
3534 /// Iterate through the set of *all* the short aliases for this subcommand, both visible and hidden.
3535 #[inline]
3536 pub fn get_all_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ {
3537 self.short_flag_aliases.iter().map(|a| a.0)
3538 }
3539
3540 /// Iterate through the set of *all* the long aliases for this subcommand, both visible and hidden.
3541 #[inline]
3542 pub fn get_all_long_flag_aliases(&self) -> impl Iterator<Item = &str> + '_ {
3543 self.long_flag_aliases.iter().map(|a| a.0.as_str())
3544 }
3545
3546 #[inline]
3547 pub(crate) fn is_set(&self, s: AppSettings) -> bool {
3548 self.settings.is_set(s) || self.g_settings.is_set(s)
3549 }
3550
3551 /// Should we color the output?
3552 pub fn get_color(&self) -> ColorChoice {
3553 debug!("Command::color: Color setting...");
3554
3555 if cfg!(feature = "color") {
3556 if self.is_set(AppSettings::ColorNever) {
3557 debug!("Never");
3558 ColorChoice::Never
3559 } else if self.is_set(AppSettings::ColorAlways) {
3560 debug!("Always");
3561 ColorChoice::Always
3562 } else {
3563 debug!("Auto");
3564 ColorChoice::Auto
3565 }
3566 } else {
3567 ColorChoice::Never
3568 }
3569 }
3570
3571 /// Return the current `Styles` for the `Command`
3572 #[inline]
3573 pub fn get_styles(&self) -> &Styles {
3574 self.app_ext.get().unwrap_or_default()
3575 }
3576
3577 /// Iterate through the set of subcommands, getting a reference to each.
3578 #[inline]
3579 pub fn get_subcommands(&self) -> impl Iterator<Item = &Command> {
3580 self.subcommands.iter()
3581 }
3582
3583 /// Iterate through the set of subcommands, getting a mutable reference to each.
3584 #[inline]
3585 pub fn get_subcommands_mut(&mut self) -> impl Iterator<Item = &mut Command> {
3586 self.subcommands.iter_mut()
3587 }
3588
3589 /// Returns `true` if this `Command` has subcommands.
3590 #[inline]
3591 pub fn has_subcommands(&self) -> bool {
3592 !self.subcommands.is_empty()
3593 }
3594
3595 /// Returns the help heading for listing subcommands.
3596 #[inline]
3597 pub fn get_subcommand_help_heading(&self) -> Option<&str> {
3598 self.subcommand_heading.as_deref()
3599 }
3600
3601 /// Returns the subcommand value name.
3602 #[inline]
3603 pub fn get_subcommand_value_name(&self) -> Option<&str> {
3604 self.subcommand_value_name.as_deref()
3605 }
3606
3607 /// Returns the help heading for listing subcommands.
3608 #[inline]
3609 pub fn get_before_help(&self) -> Option<&StyledStr> {
3610 self.before_help.as_ref()
3611 }
3612
3613 /// Returns the help heading for listing subcommands.
3614 #[inline]
3615 pub fn get_before_long_help(&self) -> Option<&StyledStr> {
3616 self.before_long_help.as_ref()
3617 }
3618
3619 /// Returns the help heading for listing subcommands.
3620 #[inline]
3621 pub fn get_after_help(&self) -> Option<&StyledStr> {
3622 self.after_help.as_ref()
3623 }
3624
3625 /// Returns the help heading for listing subcommands.
3626 #[inline]
3627 pub fn get_after_long_help(&self) -> Option<&StyledStr> {
3628 self.after_long_help.as_ref()
3629 }
3630
3631 /// Find subcommand such that its name or one of aliases equals `name`.
3632 ///
3633 /// This does not recurse through subcommands of subcommands.
3634 #[inline]
3635 pub fn find_subcommand(&self, name: impl AsRef<std::ffi::OsStr>) -> Option<&Command> {
3636 let name = name.as_ref();
3637 self.get_subcommands().find(|s| s.aliases_to(name))
3638 }
3639
3640 /// Find subcommand such that its name or one of aliases equals `name`, returning
3641 /// a mutable reference to the subcommand.
3642 ///
3643 /// This does not recurse through subcommands of subcommands.
3644 #[inline]
3645 pub fn find_subcommand_mut(
3646 &mut self,
3647 name: impl AsRef<std::ffi::OsStr>,
3648 ) -> Option<&mut Command> {
3649 let name = name.as_ref();
3650 self.get_subcommands_mut().find(|s| s.aliases_to(name))
3651 }
3652
3653 /// Iterate through the set of groups.
3654 #[inline]
3655 pub fn get_groups(&self) -> impl Iterator<Item = &ArgGroup> {
3656 self.groups.iter()
3657 }
3658
3659 /// Iterate through the set of arguments.
3660 #[inline]
3661 pub fn get_arguments(&self) -> impl Iterator<Item = &Arg> {
3662 self.args.args()
3663 }
3664
3665 /// Iterate through the *positionals* arguments.
3666 #[inline]
3667 pub fn get_positionals(&self) -> impl Iterator<Item = &Arg> {
3668 self.get_arguments().filter(|a| a.is_positional())
3669 }
3670
3671 /// Iterate through the *options*.
3672 pub fn get_opts(&self) -> impl Iterator<Item = &Arg> {
3673 self.get_arguments()
3674 .filter(|a| a.is_takes_value_set() && !a.is_positional())
3675 }
3676
3677 /// Get a list of all arguments the given argument conflicts with.
3678 ///
3679 /// If the provided argument is declared as global, the conflicts will be determined
3680 /// based on the propagation rules of global arguments.
3681 ///
3682 /// ### Panics
3683 ///
3684 /// If the given arg contains a conflict with an argument that is unknown to
3685 /// this `Command`.
3686 pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator
3687 {
3688 if arg.is_global_set() {
3689 self.get_global_arg_conflicts_with(arg)
3690 } else {
3691 let mut result = Vec::new();
3692 for id in arg.blacklist.iter() {
3693 if let Some(arg) = self.find(id) {
3694 result.push(arg);
3695 } else if let Some(group) = self.find_group(id) {
3696 result.extend(
3697 self.unroll_args_in_group(&group.id)
3698 .iter()
3699 .map(|id| self.find(id).expect(INTERNAL_ERROR_MSG)),
3700 );
3701 } else {
3702 panic!("Command::get_arg_conflicts_with: The passed arg conflicts with an arg unknown to the cmd");
3703 }
3704 }
3705 result
3706 }
3707 }
3708
3709 // Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with.
3710 //
3711 // This behavior follows the propagation rules of global arguments.
3712 // It is useful for finding conflicts for arguments declared as global.
3713 //
3714 // ### Panics
3715 //
3716 // If the given arg contains a conflict with an argument that is unknown to
3717 // this `Command`.
3718 fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator
3719 {
3720 arg.blacklist
3721 .iter()
3722 .map(|id| {
3723 self.args
3724 .args()
3725 .chain(
3726 self.get_subcommands_containing(arg)
3727 .iter()
3728 .flat_map(|x| x.args.args()),
3729 )
3730 .find(|arg| arg.get_id() == id)
3731 .expect(
3732 "Command::get_arg_conflicts_with: \
3733 The passed arg conflicts with an arg unknown to the cmd",
3734 )
3735 })
3736 .collect()
3737 }
3738
3739 // Get a list of subcommands which contain the provided Argument
3740 //
3741 // This command will only include subcommands in its list for which the subcommands
3742 // parent also contains the Argument.
3743 //
3744 // This search follows the propagation rules of global arguments.
3745 // It is useful to finding subcommands, that have inherited a global argument.
3746 //
3747 // **NOTE:** In this case only Sucommand_1 will be included
3748 // Subcommand_1 (contains Arg)
3749 // Subcommand_1.1 (doesn't contain Arg)
3750 // Subcommand_1.1.1 (contains Arg)
3751 //
3752 fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&Self> {
3753 let mut vec = std::vec::Vec::new();
3754 for idx in 0..self.subcommands.len() {
3755 if self.subcommands[idx]
3756 .args
3757 .args()
3758 .any(|ar| ar.get_id() == arg.get_id())
3759 {
3760 vec.push(&self.subcommands[idx]);
3761 vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg));
3762 }
3763 }
3764 vec
3765 }
3766
3767 /// Report whether [`Command::no_binary_name`] is set
3768 pub fn is_no_binary_name_set(&self) -> bool {
3769 self.is_set(AppSettings::NoBinaryName)
3770 }
3771
3772 /// Report whether [`Command::ignore_errors`] is set
3773 pub(crate) fn is_ignore_errors_set(&self) -> bool {
3774 self.is_set(AppSettings::IgnoreErrors)
3775 }
3776
3777 /// Report whether [`Command::dont_delimit_trailing_values`] is set
3778 pub fn is_dont_delimit_trailing_values_set(&self) -> bool {
3779 self.is_set(AppSettings::DontDelimitTrailingValues)
3780 }
3781
3782 /// Report whether [`Command::disable_version_flag`] is set
3783 pub fn is_disable_version_flag_set(&self) -> bool {
3784 self.is_set(AppSettings::DisableVersionFlag)
3785 || (self.version.is_none() && self.long_version.is_none())
3786 }
3787
3788 /// Report whether [`Command::propagate_version`] is set
3789 pub fn is_propagate_version_set(&self) -> bool {
3790 self.is_set(AppSettings::PropagateVersion)
3791 }
3792
3793 /// Report whether [`Command::next_line_help`] is set
3794 pub fn is_next_line_help_set(&self) -> bool {
3795 self.is_set(AppSettings::NextLineHelp)
3796 }
3797
3798 /// Report whether [`Command::disable_help_flag`] is set
3799 pub fn is_disable_help_flag_set(&self) -> bool {
3800 self.is_set(AppSettings::DisableHelpFlag)
3801 }
3802
3803 /// Report whether [`Command::disable_help_subcommand`] is set
3804 pub fn is_disable_help_subcommand_set(&self) -> bool {
3805 self.is_set(AppSettings::DisableHelpSubcommand)
3806 }
3807
3808 /// Report whether [`Command::disable_colored_help`] is set
3809 pub fn is_disable_colored_help_set(&self) -> bool {
3810 self.is_set(AppSettings::DisableColoredHelp)
3811 }
3812
3813 /// Report whether [`Command::help_expected`] is set
3814 #[cfg(debug_assertions)]
3815 pub(crate) fn is_help_expected_set(&self) -> bool {
3816 self.is_set(AppSettings::HelpExpected)
3817 }
3818
3819 #[doc(hidden)]
3820 #[cfg_attr(
3821 feature = "deprecated",
3822 deprecated(since = "4.0.0", note = "This is now the default")
3823 )]
3824 pub fn is_dont_collapse_args_in_usage_set(&self) -> bool {
3825 true
3826 }
3827
3828 /// Report whether [`Command::infer_long_args`] is set
3829 pub(crate) fn is_infer_long_args_set(&self) -> bool {
3830 self.is_set(AppSettings::InferLongArgs)
3831 }
3832
3833 /// Report whether [`Command::infer_subcommands`] is set
3834 pub(crate) fn is_infer_subcommands_set(&self) -> bool {
3835 self.is_set(AppSettings::InferSubcommands)
3836 }
3837
3838 /// Report whether [`Command::arg_required_else_help`] is set
3839 pub fn is_arg_required_else_help_set(&self) -> bool {
3840 self.is_set(AppSettings::ArgRequiredElseHelp)
3841 }
3842
3843 #[doc(hidden)]
3844 #[cfg_attr(
3845 feature = "deprecated",
3846 deprecated(
3847 since = "4.0.0",
3848 note = "Replaced with `Arg::is_allow_hyphen_values_set`"
3849 )
3850 )]
3851 pub(crate) fn is_allow_hyphen_values_set(&self) -> bool {
3852 self.is_set(AppSettings::AllowHyphenValues)
3853 }
3854
3855 #[doc(hidden)]
3856 #[cfg_attr(
3857 feature = "deprecated",
3858 deprecated(
3859 since = "4.0.0",
3860 note = "Replaced with `Arg::is_allow_negative_numbers_set`"
3861 )
3862 )]
3863 pub fn is_allow_negative_numbers_set(&self) -> bool {
3864 self.is_set(AppSettings::AllowNegativeNumbers)
3865 }
3866
3867 #[doc(hidden)]
3868 #[cfg_attr(
3869 feature = "deprecated",
3870 deprecated(since = "4.0.0", note = "Replaced with `Arg::is_trailing_var_arg_set`")
3871 )]
3872 pub fn is_trailing_var_arg_set(&self) -> bool {
3873 self.is_set(AppSettings::TrailingVarArg)
3874 }
3875
3876 /// Report whether [`Command::allow_missing_positional`] is set
3877 pub fn is_allow_missing_positional_set(&self) -> bool {
3878 self.is_set(AppSettings::AllowMissingPositional)
3879 }
3880
3881 /// Report whether [`Command::hide`] is set
3882 pub fn is_hide_set(&self) -> bool {
3883 self.is_set(AppSettings::Hidden)
3884 }
3885
3886 /// Report whether [`Command::subcommand_required`] is set
3887 pub fn is_subcommand_required_set(&self) -> bool {
3888 self.is_set(AppSettings::SubcommandRequired)
3889 }
3890
3891 /// Report whether [`Command::allow_external_subcommands`] is set
3892 pub fn is_allow_external_subcommands_set(&self) -> bool {
3893 self.is_set(AppSettings::AllowExternalSubcommands)
3894 }
3895
3896 /// Configured parser for values passed to an external subcommand
3897 ///
3898 /// # Example
3899 ///
3900 /// ```rust
3901 /// # use clap_builder as clap;
3902 /// let cmd = clap::Command::new("raw")
3903 /// .external_subcommand_value_parser(clap::value_parser!(String));
3904 /// let value_parser = cmd.get_external_subcommand_value_parser();
3905 /// println!("{value_parser:?}");
3906 /// ```
3907 pub fn get_external_subcommand_value_parser(&self) -> Option<&super::ValueParser> {
3908 if !self.is_allow_external_subcommands_set() {
3909 None
3910 } else {
3911 static DEFAULT: super::ValueParser = super::ValueParser::os_string();
3912 Some(self.external_value_parser.as_ref().unwrap_or(&DEFAULT))
3913 }
3914 }
3915
3916 /// Report whether [`Command::args_conflicts_with_subcommands`] is set
3917 pub fn is_args_conflicts_with_subcommands_set(&self) -> bool {
3918 self.is_set(AppSettings::ArgsNegateSubcommands)
3919 }
3920
3921 #[doc(hidden)]
3922 pub fn is_args_override_self(&self) -> bool {
3923 self.is_set(AppSettings::AllArgsOverrideSelf)
3924 }
3925
3926 /// Report whether [`Command::subcommand_precedence_over_arg`] is set
3927 pub fn is_subcommand_precedence_over_arg_set(&self) -> bool {
3928 self.is_set(AppSettings::SubcommandPrecedenceOverArg)
3929 }
3930
3931 /// Report whether [`Command::subcommand_negates_reqs`] is set
3932 pub fn is_subcommand_negates_reqs_set(&self) -> bool {
3933 self.is_set(AppSettings::SubcommandsNegateReqs)
3934 }
3935
3936 /// Report whether [`Command::multicall`] is set
3937 pub fn is_multicall_set(&self) -> bool {
3938 self.is_set(AppSettings::Multicall)
3939 }
3940}
3941
3942// Internally used only
3943impl Command {
3944 pub(crate) fn get_override_usage(&self) -> Option<&StyledStr> {
3945 self.usage_str.as_ref()
3946 }
3947
3948 pub(crate) fn get_override_help(&self) -> Option<&StyledStr> {
3949 self.help_str.as_ref()
3950 }
3951
3952 #[cfg(feature = "help")]
3953 pub(crate) fn get_help_template(&self) -> Option<&StyledStr> {
3954 self.template.as_ref()
3955 }
3956
3957 #[cfg(feature = "help")]
3958 pub(crate) fn get_term_width(&self) -> Option<usize> {
3959 self.app_ext.get::<TermWidth>().map(|e| e.0)
3960 }
3961
3962 #[cfg(feature = "help")]
3963 pub(crate) fn get_max_term_width(&self) -> Option<usize> {
3964 self.app_ext.get::<MaxTermWidth>().map(|e| e.0)
3965 }
3966
3967 pub(crate) fn get_keymap(&self) -> &MKeyMap {
3968 &self.args
3969 }
3970
3971 fn get_used_global_args(&self, matches: &ArgMatches, global_arg_vec: &mut Vec<Id>) {
3972 global_arg_vec.extend(
3973 self.args
3974 .args()
3975 .filter(|a| a.is_global_set())
3976 .map(|ga| ga.id.clone()),
3977 );
3978 if let Some((id, matches)) = matches.subcommand() {
3979 if let Some(used_sub) = self.find_subcommand(id) {
3980 used_sub.get_used_global_args(matches, global_arg_vec);
3981 }
3982 }
3983 }
3984
3985 fn _do_parse(
3986 &mut self,
3987 raw_args: &mut clap_lex::RawArgs,
3988 args_cursor: clap_lex::ArgCursor,
3989 ) -> ClapResult<ArgMatches> {
3990 debug!("Command::_do_parse");
3991
3992 // If there are global arguments, or settings we need to propagate them down to subcommands
3993 // before parsing in case we run into a subcommand
3994 self._build_self(false);
3995
3996 let mut matcher = ArgMatcher::new(self);
3997
3998 // do the real parsing
3999 let mut parser = Parser::new(self);
4000 if let Err(error) = parser.get_matches_with(&mut matcher, raw_args, args_cursor) {
4001 if self.is_set(AppSettings::IgnoreErrors) && error.use_stderr() {
4002 debug!("Command::_do_parse: ignoring error: {error}");
4003 } else {
4004 return Err(error);
4005 }
4006 }
4007
4008 let mut global_arg_vec = Default::default();
4009 self.get_used_global_args(&matcher, &mut global_arg_vec);
4010
4011 matcher.propagate_globals(&global_arg_vec);
4012
4013 Ok(matcher.into_inner())
4014 }
4015
4016 /// Prepare for introspecting on all included [`Command`]s
4017 ///
4018 /// Call this on the top-level [`Command`] when done building and before reading state for
4019 /// cases like completions, custom help output, etc.
4020 pub fn build(&mut self) {
4021 self._build_recursive(true);
4022 self._build_bin_names_internal();
4023 }
4024
4025 pub(crate) fn _build_recursive(&mut self, expand_help_tree: bool) {
4026 self._build_self(expand_help_tree);
4027 for subcmd in self.get_subcommands_mut() {
4028 subcmd._build_recursive(expand_help_tree);
4029 }
4030 }
4031
4032 pub(crate) fn _build_self(&mut self, expand_help_tree: bool) {
4033 debug!("Command::_build: name={:?}", self.get_name());
4034 if !self.settings.is_set(AppSettings::Built) {
4035 if let Some(deferred) = self.deferred.take() {
4036 *self = (deferred)(std::mem::take(self));
4037 }
4038
4039 // Make sure all the globally set flags apply to us as well
4040 self.settings = self.settings | self.g_settings;
4041
4042 if self.is_multicall_set() {
4043 self.settings.set(AppSettings::SubcommandRequired);
4044 self.settings.set(AppSettings::DisableHelpFlag);
4045 self.settings.set(AppSettings::DisableVersionFlag);
4046 }
4047 if !cfg!(feature = "help") && self.get_override_help().is_none() {
4048 self.settings.set(AppSettings::DisableHelpFlag);
4049 self.settings.set(AppSettings::DisableHelpSubcommand);
4050 }
4051 if self.is_set(AppSettings::ArgsNegateSubcommands) {
4052 self.settings.set(AppSettings::SubcommandsNegateReqs);
4053 }
4054 if self.external_value_parser.is_some() {
4055 self.settings.set(AppSettings::AllowExternalSubcommands);
4056 }
4057 if !self.has_subcommands() {
4058 self.settings.set(AppSettings::DisableHelpSubcommand);
4059 }
4060
4061 self._propagate();
4062 self._check_help_and_version(expand_help_tree);
4063 self._propagate_global_args();
4064
4065 let mut pos_counter = 1;
4066 let hide_pv = self.is_set(AppSettings::HidePossibleValues);
4067 for a in self.args.args_mut() {
4068 // Fill in the groups
4069 for g in &a.groups {
4070 if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) {
4071 ag.args.push(a.get_id().clone());
4072 } else {
4073 let mut ag = ArgGroup::new(g);
4074 ag.args.push(a.get_id().clone());
4075 self.groups.push(ag);
4076 }
4077 }
4078
4079 // Figure out implied settings
4080 a._build();
4081 if hide_pv && a.is_takes_value_set() {
4082 a.settings.set(ArgSettings::HidePossibleValues);
4083 }
4084 if a.is_positional() && a.index.is_none() {
4085 a.index = Some(pos_counter);
4086 pos_counter += 1;
4087 }
4088 }
4089
4090 self.args._build();
4091
4092 #[allow(deprecated)]
4093 {
4094 let highest_idx = self
4095 .get_keymap()
4096 .keys()
4097 .filter_map(|x| {
4098 if let crate::mkeymap::KeyType::Position(n) = x {
4099 Some(*n)
4100 } else {
4101 None
4102 }
4103 })
4104 .max()
4105 .unwrap_or(0);
4106 let is_trailing_var_arg_set = self.is_trailing_var_arg_set();
4107 let is_allow_hyphen_values_set = self.is_allow_hyphen_values_set();
4108 let is_allow_negative_numbers_set = self.is_allow_negative_numbers_set();
4109 for arg in self.args.args_mut() {
4110 if is_allow_hyphen_values_set && arg.is_takes_value_set() {
4111 arg.settings.set(ArgSettings::AllowHyphenValues);
4112 }
4113 if is_allow_negative_numbers_set && arg.is_takes_value_set() {
4114 arg.settings.set(ArgSettings::AllowNegativeNumbers);
4115 }
4116 if is_trailing_var_arg_set && arg.get_index() == Some(highest_idx) {
4117 arg.settings.set(ArgSettings::TrailingVarArg);
4118 }
4119 }
4120 }
4121
4122 #[cfg(debug_assertions)]
4123 assert_app(self);
4124 self.settings.set(AppSettings::Built);
4125 } else {
4126 debug!("Command::_build: already built");
4127 }
4128 }
4129
4130 pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> {
4131 use std::fmt::Write;
4132
4133 let mut mid_string = String::from(" ");
4134 #[cfg(feature = "usage")]
4135 if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set()
4136 {
4137 let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)
4138
4139 for s in &reqs {
4140 mid_string.push_str(&s.to_string());
4141 mid_string.push(' ');
4142 }
4143 }
4144 let is_multicall_set = self.is_multicall_set();
4145
4146 let sc = some!(self.subcommands.iter_mut().find(|s| s.name == name));
4147
4148 // Display subcommand name, short and long in usage
4149 let mut sc_names = String::new();
4150 sc_names.push_str(sc.name.as_str());
4151 let mut flag_subcmd = false;
4152 if let Some(l) = sc.get_long_flag() {
4153 write!(sc_names, "|--{l}").unwrap();
4154 flag_subcmd = true;
4155 }
4156 if let Some(s) = sc.get_short_flag() {
4157 write!(sc_names, "|-{s}").unwrap();
4158 flag_subcmd = true;
4159 }
4160
4161 if flag_subcmd {
4162 sc_names = format!("{{{sc_names}}}");
4163 }
4164
4165 let usage_name = self
4166 .bin_name
4167 .as_ref()
4168 .map(|bin_name| format!("{bin_name}{mid_string}{sc_names}"))
4169 .unwrap_or(sc_names);
4170 sc.usage_name = Some(usage_name);
4171
4172 // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by
4173 // a space
4174 let bin_name = format!(
4175 "{}{}{}",
4176 self.bin_name.as_deref().unwrap_or_default(),
4177 if self.bin_name.is_some() { " " } else { "" },
4178 &*sc.name
4179 );
4180 debug!(
4181 "Command::_build_subcommand Setting bin_name of {} to {:?}",
4182 sc.name, bin_name
4183 );
4184 sc.bin_name = Some(bin_name);
4185
4186 if sc.display_name.is_none() {
4187 let self_display_name = if is_multicall_set {
4188 self.display_name.as_deref().unwrap_or("")
4189 } else {
4190 self.display_name.as_deref().unwrap_or(&self.name)
4191 };
4192 let display_name = format!(
4193 "{}{}{}",
4194 self_display_name,
4195 if !self_display_name.is_empty() {
4196 "-"
4197 } else {
4198 ""
4199 },
4200 &*sc.name
4201 );
4202 debug!(
4203 "Command::_build_subcommand Setting display_name of {} to {:?}",
4204 sc.name, display_name
4205 );
4206 sc.display_name = Some(display_name);
4207 }
4208
4209 // Ensure all args are built and ready to parse
4210 sc._build_self(false);
4211
4212 Some(sc)
4213 }
4214
4215 fn _build_bin_names_internal(&mut self) {
4216 debug!("Command::_build_bin_names");
4217
4218 if !self.is_set(AppSettings::BinNameBuilt) {
4219 let mut mid_string = String::from(" ");
4220 #[cfg(feature = "usage")]
4221 if !self.is_subcommand_negates_reqs_set()
4222 && !self.is_args_conflicts_with_subcommands_set()
4223 {
4224 let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)
4225
4226 for s in &reqs {
4227 mid_string.push_str(&s.to_string());
4228 mid_string.push(' ');
4229 }
4230 }
4231 let is_multicall_set = self.is_multicall_set();
4232
4233 let self_bin_name = if is_multicall_set {
4234 self.bin_name.as_deref().unwrap_or("")
4235 } else {
4236 self.bin_name.as_deref().unwrap_or(&self.name)
4237 }
4238 .to_owned();
4239
4240 for sc in &mut self.subcommands {
4241 debug!("Command::_build_bin_names:iter: bin_name set...");
4242
4243 if sc.usage_name.is_none() {
4244 use std::fmt::Write;
4245 // Display subcommand name, short and long in usage
4246 let mut sc_names = String::new();
4247 sc_names.push_str(sc.name.as_str());
4248 let mut flag_subcmd = false;
4249 if let Some(l) = sc.get_long_flag() {
4250 write!(sc_names, "|--{l}").unwrap();
4251 flag_subcmd = true;
4252 }
4253 if let Some(s) = sc.get_short_flag() {
4254 write!(sc_names, "|-{s}").unwrap();
4255 flag_subcmd = true;
4256 }
4257
4258 if flag_subcmd {
4259 sc_names = format!("{{{sc_names}}}");
4260 }
4261
4262 let usage_name = format!("{self_bin_name}{mid_string}{sc_names}");
4263 debug!(
4264 "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}",
4265 sc.name, usage_name
4266 );
4267 sc.usage_name = Some(usage_name);
4268 } else {
4269 debug!(
4270 "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})",
4271 sc.name, sc.usage_name
4272 );
4273 }
4274
4275 if sc.bin_name.is_none() {
4276 let bin_name = format!(
4277 "{}{}{}",
4278 self_bin_name,
4279 if !self_bin_name.is_empty() { " " } else { "" },
4280 &*sc.name
4281 );
4282 debug!(
4283 "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}",
4284 sc.name, bin_name
4285 );
4286 sc.bin_name = Some(bin_name);
4287 } else {
4288 debug!(
4289 "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})",
4290 sc.name, sc.bin_name
4291 );
4292 }
4293
4294 if sc.display_name.is_none() {
4295 let self_display_name = if is_multicall_set {
4296 self.display_name.as_deref().unwrap_or("")
4297 } else {
4298 self.display_name.as_deref().unwrap_or(&self.name)
4299 };
4300 let display_name = format!(
4301 "{}{}{}",
4302 self_display_name,
4303 if !self_display_name.is_empty() {
4304 "-"
4305 } else {
4306 ""
4307 },
4308 &*sc.name
4309 );
4310 debug!(
4311 "Command::_build_bin_names:iter: Setting display_name of {} to {:?}",
4312 sc.name, display_name
4313 );
4314 sc.display_name = Some(display_name);
4315 } else {
4316 debug!(
4317 "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})",
4318 sc.name, sc.display_name
4319 );
4320 }
4321
4322 sc._build_bin_names_internal();
4323 }
4324 self.set(AppSettings::BinNameBuilt);
4325 } else {
4326 debug!("Command::_build_bin_names: already built");
4327 }
4328 }
4329
4330 pub(crate) fn _panic_on_missing_help(&self, help_required_globally: bool) {
4331 if self.is_set(AppSettings::HelpExpected) || help_required_globally {
4332 let args_missing_help: Vec<Id> = self
4333 .args
4334 .args()
4335 .filter(|arg| arg.get_help().is_none() && arg.get_long_help().is_none())
4336 .map(|arg| arg.get_id().clone())
4337 .collect();
4338
4339 debug_assert!(args_missing_help.is_empty(),
4340 "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: {}",
4341 self.name,
4342 args_missing_help.join(", ")
4343 );
4344 }
4345
4346 for sub_app in &self.subcommands {
4347 sub_app._panic_on_missing_help(help_required_globally);
4348 }
4349 }
4350
4351 #[cfg(debug_assertions)]
4352 pub(crate) fn two_args_of<F>(&self, condition: F) -> Option<(&Arg, &Arg)>
4353 where
4354 F: Fn(&Arg) -> bool,
4355 {
4356 two_elements_of(self.args.args().filter(|a: &&Arg| condition(a)))
4357 }
4358
4359 // just in case
4360 #[allow(unused)]
4361 fn two_groups_of<F>(&self, condition: F) -> Option<(&ArgGroup, &ArgGroup)>
4362 where
4363 F: Fn(&ArgGroup) -> bool,
4364 {
4365 two_elements_of(self.groups.iter().filter(|a| condition(a)))
4366 }
4367
4368 /// Propagate global args
4369 pub(crate) fn _propagate_global_args(&mut self) {
4370 debug!("Command::_propagate_global_args:{}", self.name);
4371
4372 let autogenerated_help_subcommand = !self.is_disable_help_subcommand_set();
4373
4374 for sc in &mut self.subcommands {
4375 if sc.get_name() == "help" && autogenerated_help_subcommand {
4376 // Avoid propagating args to the autogenerated help subtrees used in completion.
4377 // This prevents args from showing up during help completions like
4378 // `myapp help subcmd <TAB>`, which should only suggest subcommands and not args,
4379 // while still allowing args to show up properly on the generated help message.
4380 continue;
4381 }
4382
4383 for a in self.args.args().filter(|a| a.is_global_set()) {
4384 if sc.find(&a.id).is_some() {
4385 debug!(
4386 "Command::_propagate skipping {:?} to {}, already exists",
4387 a.id,
4388 sc.get_name(),
4389 );
4390 continue;
4391 }
4392
4393 debug!(
4394 "Command::_propagate pushing {:?} to {}",
4395 a.id,
4396 sc.get_name(),
4397 );
4398 sc.args.push(a.clone());
4399 }
4400 }
4401 }
4402
4403 /// Propagate settings
4404 pub(crate) fn _propagate(&mut self) {
4405 debug!("Command::_propagate:{}", self.name);
4406 let mut subcommands = std::mem::take(&mut self.subcommands);
4407 for sc in &mut subcommands {
4408 self._propagate_subcommand(sc);
4409 }
4410 self.subcommands = subcommands;
4411 }
4412
4413 fn _propagate_subcommand(&self, sc: &mut Self) {
4414 // We have to create a new scope in order to tell rustc the borrow of `sc` is
4415 // done and to recursively call this method
4416 {
4417 if self.settings.is_set(AppSettings::PropagateVersion) {
4418 if let Some(version) = self.version.as_ref() {
4419 sc.version.get_or_insert_with(|| version.clone());
4420 }
4421 if let Some(long_version) = self.long_version.as_ref() {
4422 sc.long_version.get_or_insert_with(|| long_version.clone());
4423 }
4424 }
4425
4426 sc.settings = sc.settings | self.g_settings;
4427 sc.g_settings = sc.g_settings | self.g_settings;
4428 sc.app_ext.update(&self.app_ext);
4429 }
4430 }
4431
4432 pub(crate) fn _check_help_and_version(&mut self, expand_help_tree: bool) {
4433 debug!(
4434 "Command::_check_help_and_version:{} expand_help_tree={}",
4435 self.name, expand_help_tree
4436 );
4437
4438 self.long_help_exists = self.long_help_exists_();
4439
4440 if !self.is_disable_help_flag_set() {
4441 debug!("Command::_check_help_and_version: Building default --help");
4442 let mut arg = Arg::new(Id::HELP)
4443 .short('h')
4444 .long("help")
4445 .action(ArgAction::Help);
4446 if self.long_help_exists {
4447 arg = arg
4448 .help("Print help (see more with '--help')")
4449 .long_help("Print help (see a summary with '-h')");
4450 } else {
4451 arg = arg.help("Print help");
4452 }
4453 // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
4454 // `next_display_order`
4455 self.args.push(arg);
4456 }
4457 if !self.is_disable_version_flag_set() {
4458 debug!("Command::_check_help_and_version: Building default --version");
4459 let arg = Arg::new(Id::VERSION)
4460 .short('V')
4461 .long("version")
4462 .action(ArgAction::Version)
4463 .help("Print version");
4464 // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
4465 // `next_display_order`
4466 self.args.push(arg);
4467 }
4468
4469 if !self.is_set(AppSettings::DisableHelpSubcommand) {
4470 debug!("Command::_check_help_and_version: Building help subcommand");
4471 let help_about = "Print this message or the help of the given subcommand(s)";
4472
4473 let mut help_subcmd = if expand_help_tree {
4474 // Slow code path to recursively clone all other subcommand subtrees under help
4475 let help_subcmd = Command::new("help")
4476 .about(help_about)
4477 .global_setting(AppSettings::DisableHelpSubcommand)
4478 .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));
4479
4480 let mut help_help_subcmd = Command::new("help").about(help_about);
4481 help_help_subcmd.version = None;
4482 help_help_subcmd.long_version = None;
4483 help_help_subcmd = help_help_subcmd
4484 .setting(AppSettings::DisableHelpFlag)
4485 .setting(AppSettings::DisableVersionFlag);
4486
4487 help_subcmd.subcommand(help_help_subcmd)
4488 } else {
4489 Command::new("help").about(help_about).arg(
4490 Arg::new("subcommand")
4491 .action(ArgAction::Append)
4492 .num_args(..)
4493 .value_name("COMMAND")
4494 .help("Print help for the subcommand(s)"),
4495 )
4496 };
4497 self._propagate_subcommand(&mut help_subcmd);
4498
4499 // The parser acts like this is set, so let's set it so we don't falsely
4500 // advertise it to the user
4501 help_subcmd.version = None;
4502 help_subcmd.long_version = None;
4503 help_subcmd = help_subcmd
4504 .setting(AppSettings::DisableHelpFlag)
4505 .setting(AppSettings::DisableVersionFlag)
4506 .unset_global_setting(AppSettings::PropagateVersion);
4507
4508 self.subcommands.push(help_subcmd);
4509 }
4510 }
4511
4512 fn _copy_subtree_for_help(&self) -> Command {
4513 let mut cmd = Command::new(self.name.clone())
4514 .hide(self.is_hide_set())
4515 .global_setting(AppSettings::DisableHelpFlag)
4516 .global_setting(AppSettings::DisableVersionFlag)
4517 .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));
4518 if self.get_about().is_some() {
4519 cmd = cmd.about(self.get_about().unwrap().clone());
4520 }
4521 cmd
4522 }
4523
4524 pub(crate) fn _render_version(&self, use_long: bool) -> String {
4525 debug!("Command::_render_version");
4526
4527 let ver = if use_long {
4528 self.long_version
4529 .as_deref()
4530 .or(self.version.as_deref())
4531 .unwrap_or_default()
4532 } else {
4533 self.version
4534 .as_deref()
4535 .or(self.long_version.as_deref())
4536 .unwrap_or_default()
4537 };
4538 let display_name = self.get_display_name().unwrap_or_else(|| self.get_name());
4539 format!("{display_name} {ver}\n")
4540 }
4541
4542 pub(crate) fn format_group(&self, g: &Id) -> StyledStr {
4543 let g_string = self
4544 .unroll_args_in_group(g)
4545 .iter()
4546 .filter_map(|x| self.find(x))
4547 .map(|x| {
4548 if x.is_positional() {
4549 // Print val_name for positional arguments. e.g. <file_name>
4550 x.name_no_brackets()
4551 } else {
4552 // Print usage string for flags arguments, e.g. <--help>
4553 x.to_string()
4554 }
4555 })
4556 .collect::<Vec<_>>()
4557 .join("|");
4558 let mut styled = StyledStr::new();
4559 styled.push_str("<");
4560 styled.push_string(g_string);
4561 styled.push_str(">");
4562 styled
4563 }
4564}
4565
4566/// A workaround:
4567/// <https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999>
4568pub(crate) trait Captures<'a> {}
4569impl<'a, T> Captures<'a> for T {}
4570
4571// Internal Query Methods
4572impl Command {
4573 /// Iterate through the *flags* & *options* arguments.
4574 #[cfg(any(feature = "usage", feature = "help"))]
4575 pub(crate) fn get_non_positionals(&self) -> impl Iterator<Item = &Arg> {
4576 self.get_arguments().filter(|a| !a.is_positional())
4577 }
4578
4579 pub(crate) fn find(&self, arg_id: &Id) -> Option<&Arg> {
4580 self.args.args().find(|a| a.get_id() == arg_id)
4581 }
4582
4583 #[inline]
4584 pub(crate) fn contains_short(&self, s: char) -> bool {
4585 debug_assert!(
4586 self.is_set(AppSettings::Built),
4587 "If Command::_build hasn't been called, manually search through Arg shorts"
4588 );
4589
4590 self.args.contains(s)
4591 }
4592
4593 #[inline]
4594 pub(crate) fn set(&mut self, s: AppSettings) {
4595 self.settings.set(s)
4596 }
4597
4598 #[inline]
4599 pub(crate) fn has_positionals(&self) -> bool {
4600 self.get_positionals().next().is_some()
4601 }
4602
4603 #[cfg(any(feature = "usage", feature = "help"))]
4604 pub(crate) fn has_visible_subcommands(&self) -> bool {
4605 self.subcommands
4606 .iter()
4607 .any(|sc| sc.name != "help" && !sc.is_set(AppSettings::Hidden))
4608 }
4609
4610 /// Check if this subcommand can be referred to as `name`. In other words,
4611 /// check if `name` is the name of this subcommand or is one of its aliases.
4612 #[inline]
4613 pub(crate) fn aliases_to(&self, name: impl AsRef<std::ffi::OsStr>) -> bool {
4614 let name = name.as_ref();
4615 self.get_name() == name || self.get_all_aliases().any(|alias| alias == name)
4616 }
4617
4618 /// Check if this subcommand can be referred to as `name`. In other words,
4619 /// check if `name` is the name of this short flag subcommand or is one of its short flag aliases.
4620 #[inline]
4621 pub(crate) fn short_flag_aliases_to(&self, flag: char) -> bool {
4622 Some(flag) == self.short_flag
4623 || self.get_all_short_flag_aliases().any(|alias| flag == alias)
4624 }
4625
4626 /// Check if this subcommand can be referred to as `name`. In other words,
4627 /// check if `name` is the name of this long flag subcommand or is one of its long flag aliases.
4628 #[inline]
4629 pub(crate) fn long_flag_aliases_to(&self, flag: &str) -> bool {
4630 match self.long_flag.as_ref() {
4631 Some(long_flag) => {
4632 long_flag == flag || self.get_all_long_flag_aliases().any(|alias| alias == flag)
4633 }
4634 None => self.get_all_long_flag_aliases().any(|alias| alias == flag),
4635 }
4636 }
4637
4638 #[cfg(debug_assertions)]
4639 pub(crate) fn id_exists(&self, id: &Id) -> bool {
4640 self.args.args().any(|x| x.get_id() == id) || self.groups.iter().any(|x| x.id == *id)
4641 }
4642
4643 /// Iterate through the groups this arg is member of.
4644 pub(crate) fn groups_for_arg<'a>(&'a self, arg: &Id) -> impl Iterator<Item = Id> + 'a {
4645 debug!("Command::groups_for_arg: id={arg:?}");
4646 let arg = arg.clone();
4647 self.groups
4648 .iter()
4649 .filter(move |grp| grp.args.iter().any(|a| a == &arg))
4650 .map(|grp| grp.id.clone())
4651 }
4652
4653 pub(crate) fn find_group(&self, group_id: &Id) -> Option<&ArgGroup> {
4654 self.groups.iter().find(|g| g.id == *group_id)
4655 }
4656
4657 /// Iterate through all the names of all subcommands (not recursively), including aliases.
4658 /// Used for suggestions.
4659 pub(crate) fn all_subcommand_names(&self) -> impl Iterator<Item = &str> + Captures {
4660 self.get_subcommands().flat_map(|sc| {
4661 let name = sc.get_name();
4662 let aliases = sc.get_all_aliases();
4663 std::iter::once(name).chain(aliases)
4664 })
4665 }
4666
4667 pub(crate) fn required_graph(&self) -> ChildGraph<Id> {
4668 let mut reqs = ChildGraph::with_capacity(5);
4669 for a in self.args.args().filter(|a| a.is_required_set()) {
4670 reqs.insert(a.get_id().clone());
4671 }
4672 for group in &self.groups {
4673 if group.required {
4674 let idx = reqs.insert(group.id.clone());
4675 for a in &group.requires {
4676 reqs.insert_child(idx, a.clone());
4677 }
4678 }
4679 }
4680
4681 reqs
4682 }
4683
4684 pub(crate) fn unroll_args_in_group(&self, group: &Id) -> Vec<Id> {
4685 debug!("Command::unroll_args_in_group: group={group:?}");
4686 let mut g_vec = vec![group];
4687 let mut args = vec![];
4688
4689 while let Some(g) = g_vec.pop() {
4690 for n in self
4691 .groups
4692 .iter()
4693 .find(|grp| grp.id == *g)
4694 .expect(INTERNAL_ERROR_MSG)
4695 .args
4696 .iter()
4697 {
4698 debug!("Command::unroll_args_in_group:iter: entity={n:?}");
4699 if !args.contains(n) {
4700 if self.find(n).is_some() {
4701 debug!("Command::unroll_args_in_group:iter: this is an arg");
4702 args.push(n.clone())
4703 } else {
4704 debug!("Command::unroll_args_in_group:iter: this is a group");
4705 g_vec.push(n);
4706 }
4707 }
4708 }
4709 }
4710
4711 args
4712 }
4713
4714 pub(crate) fn unroll_arg_requires<F>(&self, func: F, arg: &Id) -> Vec<Id>
4715 where
4716 F: Fn(&(ArgPredicate, Id)) -> Option<Id>,
4717 {
4718 let mut processed = vec![];
4719 let mut r_vec = vec![arg];
4720 let mut args = vec![];
4721
4722 while let Some(a) = r_vec.pop() {
4723 if processed.contains(&a) {
4724 continue;
4725 }
4726
4727 processed.push(a);
4728
4729 if let Some(arg) = self.find(a) {
4730 for r in arg.requires.iter().filter_map(&func) {
4731 if let Some(req) = self.find(&r) {
4732 if !req.requires.is_empty() {
4733 r_vec.push(req.get_id())
4734 }
4735 }
4736 args.push(r);
4737 }
4738 }
4739 }
4740
4741 args
4742 }
4743
4744 /// Find a flag subcommand name by short flag or an alias
4745 pub(crate) fn find_short_subcmd(&self, c: char) -> Option<&str> {
4746 self.get_subcommands()
4747 .find(|sc| sc.short_flag_aliases_to(c))
4748 .map(|sc| sc.get_name())
4749 }
4750
4751 /// Find a flag subcommand name by long flag or an alias
4752 pub(crate) fn find_long_subcmd(&self, long: &str) -> Option<&str> {
4753 self.get_subcommands()
4754 .find(|sc| sc.long_flag_aliases_to(long))
4755 .map(|sc| sc.get_name())
4756 }
4757
4758 #[cfg(feature = "help")]
4759 pub(crate) fn get_display_order(&self) -> usize {
4760 self.disp_ord.unwrap_or(999)
4761 }
4762
4763 pub(crate) fn write_help_err(&self, mut use_long: bool) -> StyledStr {
4764 debug!(
4765 "Command::write_help_err: {}, use_long={:?}",
4766 self.get_display_name().unwrap_or_else(|| self.get_name()),
4767 use_long && self.long_help_exists(),
4768 );
4769
4770 use_long = use_long && self.long_help_exists();
4771 let usage = Usage::new(self);
4772
4773 let mut styled = StyledStr::new();
4774 write_help(&mut styled, self, &usage, use_long);
4775
4776 styled
4777 }
4778
4779 pub(crate) fn write_version_err(&self, use_long: bool) -> StyledStr {
4780 let msg = self._render_version(use_long);
4781 StyledStr::from(msg)
4782 }
4783
4784 pub(crate) fn long_help_exists(&self) -> bool {
4785 debug!("Command::long_help_exists: {}", self.long_help_exists);
4786 self.long_help_exists
4787 }
4788
4789 fn long_help_exists_(&self) -> bool {
4790 debug!("Command::long_help_exists");
4791 // In this case, both must be checked. This allows the retention of
4792 // original formatting, but also ensures that the actual -h or --help
4793 // specified by the user is sent through. If hide_short_help is not included,
4794 // then items specified with hidden_short_help will also be hidden.
4795 let should_long = |v: &Arg| {
4796 !v.is_hide_set()
4797 && (v.get_long_help().is_some()
4798 || v.is_hide_long_help_set()
4799 || v.is_hide_short_help_set()
4800 || (!v.is_hide_possible_values_set()
4801 && v.get_possible_values()
4802 .iter()
4803 .any(PossibleValue::should_show_help)))
4804 };
4805
4806 // Subcommands aren't checked because we prefer short help for them, deferring to
4807 // `cmd subcmd --help` for more.
4808 self.get_long_about().is_some()
4809 || self.get_before_long_help().is_some()
4810 || self.get_after_long_help().is_some()
4811 || self.get_arguments().any(should_long)
4812 }
4813
4814 // Should we color the help?
4815 pub(crate) fn color_help(&self) -> ColorChoice {
4816 #[cfg(feature = "color")]
4817 if self.is_disable_colored_help_set() {
4818 return ColorChoice::Never;
4819 }
4820
4821 self.get_color()
4822 }
4823}
4824
4825impl Default for Command {
4826 fn default() -> Self {
4827 Self {
4828 name: Default::default(),
4829 long_flag: Default::default(),
4830 short_flag: Default::default(),
4831 display_name: Default::default(),
4832 bin_name: Default::default(),
4833 author: Default::default(),
4834 version: Default::default(),
4835 long_version: Default::default(),
4836 about: Default::default(),
4837 long_about: Default::default(),
4838 before_help: Default::default(),
4839 before_long_help: Default::default(),
4840 after_help: Default::default(),
4841 after_long_help: Default::default(),
4842 aliases: Default::default(),
4843 short_flag_aliases: Default::default(),
4844 long_flag_aliases: Default::default(),
4845 usage_str: Default::default(),
4846 usage_name: Default::default(),
4847 help_str: Default::default(),
4848 disp_ord: Default::default(),
4849 #[cfg(feature = "help")]
4850 template: Default::default(),
4851 settings: Default::default(),
4852 g_settings: Default::default(),
4853 args: Default::default(),
4854 subcommands: Default::default(),
4855 groups: Default::default(),
4856 current_help_heading: Default::default(),
4857 current_disp_ord: Some(0),
4858 subcommand_value_name: Default::default(),
4859 subcommand_heading: Default::default(),
4860 external_value_parser: Default::default(),
4861 long_help_exists: false,
4862 deferred: None,
4863 app_ext: Default::default(),
4864 }
4865 }
4866}
4867
4868impl Index<&'_ Id> for Command {
4869 type Output = Arg;
4870
4871 fn index(&self, key: &Id) -> &Self::Output {
4872 self.find(key).expect(INTERNAL_ERROR_MSG)
4873 }
4874}
4875
4876impl From<&'_ Command> for Command {
4877 fn from(cmd: &'_ Command) -> Self {
4878 cmd.clone()
4879 }
4880}
4881
4882impl fmt::Display for Command {
4883 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4884 write!(f, "{}", self.name)
4885 }
4886}
4887
4888pub(crate) trait AppTag: crate::builder::ext::Extension {}
4889
4890#[derive(Default, Copy, Clone, Debug)]
4891struct TermWidth(usize);
4892
4893impl AppTag for TermWidth {}
4894
4895#[derive(Default, Copy, Clone, Debug)]
4896struct MaxTermWidth(usize);
4897
4898impl AppTag for MaxTermWidth {}
4899
4900fn two_elements_of<I, T>(mut iter: I) -> Option<(T, T)>
4901where
4902 I: Iterator<Item = T>,
4903{
4904 let first = iter.next();
4905 let second = iter.next();
4906
4907 match (first, second) {
4908 (Some(first), Some(second)) => Some((first, second)),
4909 _ => None,
4910 }
4911}
4912
4913#[test]
4914fn check_auto_traits() {
4915 static_assertions::assert_impl_all!(Command: Send, Sync, Unpin);
4916}
4917