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