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