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