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