1 | #![cfg_attr (not(feature = "usage" ), allow(unused_mut))] |
2 | |
3 | // Std |
4 | use std::env; |
5 | use std::ffi::OsString; |
6 | use std::fmt; |
7 | use std::io; |
8 | use std::ops::Index; |
9 | use std::path::Path; |
10 | |
11 | // Internal |
12 | use crate::builder::app_settings::{AppFlags, AppSettings}; |
13 | use crate::builder::arg_settings::ArgSettings; |
14 | use crate::builder::ext::Extension; |
15 | use crate::builder::ext::Extensions; |
16 | use crate::builder::ArgAction; |
17 | use crate::builder::IntoResettable; |
18 | use crate::builder::PossibleValue; |
19 | use crate::builder::Str; |
20 | use crate::builder::StyledStr; |
21 | use crate::builder::Styles; |
22 | use crate::builder::{Arg, ArgGroup, ArgPredicate}; |
23 | use crate::error::ErrorKind; |
24 | use crate::error::Result as ClapResult; |
25 | use crate::mkeymap::MKeyMap; |
26 | use crate::output::fmt::Stream; |
27 | use crate::output::{fmt::Colorizer, write_help, Usage}; |
28 | use crate::parser::{ArgMatcher, ArgMatches, Parser}; |
29 | use crate::util::ChildGraph; |
30 | use crate::util::{color::ColorChoice, Id}; |
31 | use crate::{Error, INTERNAL_ERROR_MSG}; |
32 | |
33 | #[cfg (debug_assertions)] |
34 | use 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)] |
74 | pub 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 |
116 | impl 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. |
1083 | impl 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. |
1767 | impl 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 | /// |
2117 | /// [`ArgMatches::usage`]: ArgMatches::usage() |
2118 | #[must_use ] |
2119 | pub fn override_usage(mut self, usage: impl IntoResettable<StyledStr>) -> Self { |
2120 | self.usage_str = usage.into_resettable().into_option(); |
2121 | self |
2122 | } |
2123 | |
2124 | /// Overrides the `clap` generated help message (both `-h` and `--help`). |
2125 | /// |
2126 | /// This should only be used when the auto-generated message does not suffice. |
2127 | /// |
2128 | /// <div class="warning"> |
2129 | /// |
2130 | /// **NOTE:** This **only** replaces the help message for the current |
2131 | /// command, meaning if you are using subcommands, those help messages will |
2132 | /// still be auto-generated unless you specify a [`Command::override_help`] for |
2133 | /// them as well. |
2134 | /// |
2135 | /// </div> |
2136 | /// |
2137 | /// # Examples |
2138 | /// |
2139 | /// ```rust |
2140 | /// # use clap_builder as clap; |
2141 | /// # use clap::{Command, Arg}; |
2142 | /// Command::new("myapp" ) |
2143 | /// .override_help("myapp v1.0 \n\ |
2144 | /// Does awesome things \n\ |
2145 | /// (C) me@mail.com \n\n\ |
2146 | /// |
2147 | /// Usage: myapp <opts> <command> \n\n\ |
2148 | /// |
2149 | /// Options: \n\ |
2150 | /// -h, --help Display this message \n\ |
2151 | /// -V, --version Display version info \n\ |
2152 | /// -s <stuff> Do something with stuff \n\ |
2153 | /// -v Be verbose \n\n\ |
2154 | /// |
2155 | /// Commands: \n\ |
2156 | /// help Print this message \n\ |
2157 | /// work Do some work" ) |
2158 | /// # ; |
2159 | /// ``` |
2160 | #[must_use ] |
2161 | pub fn override_help(mut self, help: impl IntoResettable<StyledStr>) -> Self { |
2162 | self.help_str = help.into_resettable().into_option(); |
2163 | self |
2164 | } |
2165 | |
2166 | /// Sets the help template to be used, overriding the default format. |
2167 | /// |
2168 | /// Tags are given inside curly brackets. |
2169 | /// |
2170 | /// Valid tags are: |
2171 | /// |
2172 | /// * `{name}` - Display name for the (sub-)command. |
2173 | /// * `{bin}` - Binary name.(deprecated) |
2174 | /// * `{version}` - Version number. |
2175 | /// * `{author}` - Author information. |
2176 | /// * `{author-with-newline}` - Author followed by `\n`. |
2177 | /// * `{author-section}` - Author preceded and followed by `\n`. |
2178 | /// * `{about}` - General description (from [`Command::about`] or |
2179 | /// [`Command::long_about`]). |
2180 | /// * `{about-with-newline}` - About followed by `\n`. |
2181 | /// * `{about-section}` - About preceded and followed by '\n'. |
2182 | /// * `{usage-heading}` - Automatically generated usage heading. |
2183 | /// * `{usage}` - Automatically generated or given usage string. |
2184 | /// * `{all-args}` - Help for all arguments (options, flags, positional |
2185 | /// arguments, and subcommands) including titles. |
2186 | /// * `{options}` - Help for options. |
2187 | /// * `{positionals}` - Help for positional arguments. |
2188 | /// * `{subcommands}` - Help for subcommands. |
2189 | /// * `{tab}` - Standard tab sized used within clap |
2190 | /// * `{after-help}` - Help from [`Command::after_help`] or [`Command::after_long_help`]. |
2191 | /// * `{before-help}` - Help from [`Command::before_help`] or [`Command::before_long_help`]. |
2192 | /// |
2193 | /// # Examples |
2194 | /// |
2195 | /// For a very brief help: |
2196 | /// |
2197 | /// ```rust |
2198 | /// # use clap_builder as clap; |
2199 | /// # use clap::Command; |
2200 | /// Command::new("myprog" ) |
2201 | /// .version("1.0" ) |
2202 | /// .help_template("{name} ({version}) - {usage}" ) |
2203 | /// # ; |
2204 | /// ``` |
2205 | /// |
2206 | /// For showing more application context: |
2207 | /// |
2208 | /// ```rust |
2209 | /// # use clap_builder as clap; |
2210 | /// # use clap::Command; |
2211 | /// Command::new("myprog" ) |
2212 | /// .version("1.0" ) |
2213 | /// .help_template("\ |
2214 | /// {before-help}{name} {version} |
2215 | /// {author-with-newline}{about-with-newline} |
2216 | /// {usage-heading} {usage} |
2217 | /// |
2218 | /// {all-args}{after-help} |
2219 | /// " ) |
2220 | /// # ; |
2221 | /// ``` |
2222 | /// [`Command::about`]: Command::about() |
2223 | /// [`Command::long_about`]: Command::long_about() |
2224 | /// [`Command::after_help`]: Command::after_help() |
2225 | /// [`Command::after_long_help`]: Command::after_long_help() |
2226 | /// [`Command::before_help`]: Command::before_help() |
2227 | /// [`Command::before_long_help`]: Command::before_long_help() |
2228 | #[must_use ] |
2229 | #[cfg (feature = "help" )] |
2230 | pub fn help_template(mut self, s: impl IntoResettable<StyledStr>) -> Self { |
2231 | self.template = s.into_resettable().into_option(); |
2232 | self |
2233 | } |
2234 | |
2235 | #[inline ] |
2236 | #[must_use ] |
2237 | pub(crate) fn setting(mut self, setting: AppSettings) -> Self { |
2238 | self.settings.set(setting); |
2239 | self |
2240 | } |
2241 | |
2242 | #[inline ] |
2243 | #[must_use ] |
2244 | pub(crate) fn unset_setting(mut self, setting: AppSettings) -> Self { |
2245 | self.settings.unset(setting); |
2246 | self |
2247 | } |
2248 | |
2249 | #[inline ] |
2250 | #[must_use ] |
2251 | pub(crate) fn global_setting(mut self, setting: AppSettings) -> Self { |
2252 | self.settings.set(setting); |
2253 | self.g_settings.set(setting); |
2254 | self |
2255 | } |
2256 | |
2257 | #[inline ] |
2258 | #[must_use ] |
2259 | pub(crate) fn unset_global_setting(mut self, setting: AppSettings) -> Self { |
2260 | self.settings.unset(setting); |
2261 | self.g_settings.unset(setting); |
2262 | self |
2263 | } |
2264 | |
2265 | /// Flatten subcommand help into the current command's help |
2266 | /// |
2267 | /// This shows a summary of subcommands within the usage and help for the current command, similar to |
2268 | /// `git stash --help` showing information on `push`, `pop`, etc. |
2269 | /// To see more information, a user can still pass `--help` to the individual subcommands. |
2270 | #[inline ] |
2271 | #[must_use ] |
2272 | pub fn flatten_help(self, yes: bool) -> Self { |
2273 | if yes { |
2274 | self.setting(AppSettings::FlattenHelp) |
2275 | } else { |
2276 | self.unset_setting(AppSettings::FlattenHelp) |
2277 | } |
2278 | } |
2279 | |
2280 | /// Set the default section heading for future args. |
2281 | /// |
2282 | /// This will be used for any arg that hasn't had [`Arg::help_heading`] called. |
2283 | /// |
2284 | /// This is useful if the default `Options` or `Arguments` headings are |
2285 | /// not specific enough for one's use case. |
2286 | /// |
2287 | /// For subcommands, see [`Command::subcommand_help_heading`] |
2288 | /// |
2289 | /// [`Command::arg`]: Command::arg() |
2290 | /// [`Arg::help_heading`]: crate::Arg::help_heading() |
2291 | #[inline ] |
2292 | #[must_use ] |
2293 | pub fn next_help_heading(mut self, heading: impl IntoResettable<Str>) -> Self { |
2294 | self.current_help_heading = heading.into_resettable().into_option(); |
2295 | self |
2296 | } |
2297 | |
2298 | /// Change the starting value for assigning future display orders for args. |
2299 | /// |
2300 | /// This will be used for any arg that hasn't had [`Arg::display_order`] called. |
2301 | #[inline ] |
2302 | #[must_use ] |
2303 | pub fn next_display_order(mut self, disp_ord: impl IntoResettable<usize>) -> Self { |
2304 | self.current_disp_ord = disp_ord.into_resettable().into_option(); |
2305 | self |
2306 | } |
2307 | |
2308 | /// Exit gracefully if no arguments are present (e.g. `$ myprog`). |
2309 | /// |
2310 | /// <div class="warning"> |
2311 | /// |
2312 | /// **NOTE:** [`subcommands`] count as arguments |
2313 | /// |
2314 | /// </div> |
2315 | /// |
2316 | /// # Examples |
2317 | /// |
2318 | /// ```rust |
2319 | /// # use clap_builder as clap; |
2320 | /// # use clap::{Command}; |
2321 | /// Command::new("myprog" ) |
2322 | /// .arg_required_else_help(true); |
2323 | /// ``` |
2324 | /// |
2325 | /// [`subcommands`]: crate::Command::subcommand() |
2326 | /// [`Arg::default_value`]: crate::Arg::default_value() |
2327 | #[inline ] |
2328 | pub fn arg_required_else_help(self, yes: bool) -> Self { |
2329 | if yes { |
2330 | self.setting(AppSettings::ArgRequiredElseHelp) |
2331 | } else { |
2332 | self.unset_setting(AppSettings::ArgRequiredElseHelp) |
2333 | } |
2334 | } |
2335 | |
2336 | #[doc (hidden)] |
2337 | #[cfg_attr ( |
2338 | feature = "deprecated" , |
2339 | deprecated(since = "4.0.0" , note = "Replaced with `Arg::allow_hyphen_values`" ) |
2340 | )] |
2341 | pub fn allow_hyphen_values(self, yes: bool) -> Self { |
2342 | if yes { |
2343 | self.setting(AppSettings::AllowHyphenValues) |
2344 | } else { |
2345 | self.unset_setting(AppSettings::AllowHyphenValues) |
2346 | } |
2347 | } |
2348 | |
2349 | #[doc (hidden)] |
2350 | #[cfg_attr ( |
2351 | feature = "deprecated" , |
2352 | deprecated(since = "4.0.0" , note = "Replaced with `Arg::allow_negative_numbers`" ) |
2353 | )] |
2354 | pub fn allow_negative_numbers(self, yes: bool) -> Self { |
2355 | if yes { |
2356 | self.setting(AppSettings::AllowNegativeNumbers) |
2357 | } else { |
2358 | self.unset_setting(AppSettings::AllowNegativeNumbers) |
2359 | } |
2360 | } |
2361 | |
2362 | #[doc (hidden)] |
2363 | #[cfg_attr ( |
2364 | feature = "deprecated" , |
2365 | deprecated(since = "4.0.0" , note = "Replaced with `Arg::trailing_var_arg`" ) |
2366 | )] |
2367 | pub fn trailing_var_arg(self, yes: bool) -> Self { |
2368 | if yes { |
2369 | self.setting(AppSettings::TrailingVarArg) |
2370 | } else { |
2371 | self.unset_setting(AppSettings::TrailingVarArg) |
2372 | } |
2373 | } |
2374 | |
2375 | /// Allows one to implement two styles of CLIs where positionals can be used out of order. |
2376 | /// |
2377 | /// The first example is a CLI where the second to last positional argument is optional, but |
2378 | /// the final positional argument is required. Such as `$ prog [optional] <required>` where one |
2379 | /// of the two following usages is allowed: |
2380 | /// |
2381 | /// * `$ prog [optional] <required>` |
2382 | /// * `$ prog <required>` |
2383 | /// |
2384 | /// This would otherwise not be allowed. This is useful when `[optional]` has a default value. |
2385 | /// |
2386 | /// **Note:** when using this style of "missing positionals" the final positional *must* be |
2387 | /// [required] if `--` will not be used to skip to the final positional argument. |
2388 | /// |
2389 | /// **Note:** This style also only allows a single positional argument to be "skipped" without |
2390 | /// the use of `--`. To skip more than one, see the second example. |
2391 | /// |
2392 | /// The second example is when one wants to skip multiple optional positional arguments, and use |
2393 | /// of the `--` operator is OK (but not required if all arguments will be specified anyways). |
2394 | /// |
2395 | /// For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where |
2396 | /// `baz` accepts multiple values (similar to man `ARGS...` style training arguments). |
2397 | /// |
2398 | /// With this setting the following invocations are possible: |
2399 | /// |
2400 | /// * `$ prog foo bar baz1 baz2 baz3` |
2401 | /// * `$ prog foo -- baz1 baz2 baz3` |
2402 | /// * `$ prog -- baz1 baz2 baz3` |
2403 | /// |
2404 | /// # Examples |
2405 | /// |
2406 | /// Style number one from above: |
2407 | /// |
2408 | /// ```rust |
2409 | /// # use clap_builder as clap; |
2410 | /// # use clap::{Command, Arg}; |
2411 | /// // Assume there is an external subcommand named "subcmd" |
2412 | /// let m = Command::new("myprog" ) |
2413 | /// .allow_missing_positional(true) |
2414 | /// .arg(Arg::new("arg1" )) |
2415 | /// .arg(Arg::new("arg2" ) |
2416 | /// .required(true)) |
2417 | /// .get_matches_from(vec![ |
2418 | /// "prog" , "other" |
2419 | /// ]); |
2420 | /// |
2421 | /// assert_eq!(m.get_one::<String>("arg1" ), None); |
2422 | /// assert_eq!(m.get_one::<String>("arg2" ).unwrap(), "other" ); |
2423 | /// ``` |
2424 | /// |
2425 | /// Now the same example, but using a default value for the first optional positional argument |
2426 | /// |
2427 | /// ```rust |
2428 | /// # use clap_builder as clap; |
2429 | /// # use clap::{Command, Arg}; |
2430 | /// // Assume there is an external subcommand named "subcmd" |
2431 | /// let m = Command::new("myprog" ) |
2432 | /// .allow_missing_positional(true) |
2433 | /// .arg(Arg::new("arg1" ) |
2434 | /// .default_value("something" )) |
2435 | /// .arg(Arg::new("arg2" ) |
2436 | /// .required(true)) |
2437 | /// .get_matches_from(vec![ |
2438 | /// "prog" , "other" |
2439 | /// ]); |
2440 | /// |
2441 | /// assert_eq!(m.get_one::<String>("arg1" ).unwrap(), "something" ); |
2442 | /// assert_eq!(m.get_one::<String>("arg2" ).unwrap(), "other" ); |
2443 | /// ``` |
2444 | /// |
2445 | /// Style number two from above: |
2446 | /// |
2447 | /// ```rust |
2448 | /// # use clap_builder as clap; |
2449 | /// # use clap::{Command, Arg, ArgAction}; |
2450 | /// // Assume there is an external subcommand named "subcmd" |
2451 | /// let m = Command::new("myprog" ) |
2452 | /// .allow_missing_positional(true) |
2453 | /// .arg(Arg::new("foo" )) |
2454 | /// .arg(Arg::new("bar" )) |
2455 | /// .arg(Arg::new("baz" ).action(ArgAction::Set).num_args(1..)) |
2456 | /// .get_matches_from(vec![ |
2457 | /// "prog" , "foo" , "bar" , "baz1" , "baz2" , "baz3" |
2458 | /// ]); |
2459 | /// |
2460 | /// assert_eq!(m.get_one::<String>("foo" ).unwrap(), "foo" ); |
2461 | /// assert_eq!(m.get_one::<String>("bar" ).unwrap(), "bar" ); |
2462 | /// assert_eq!(m.get_many::<String>("baz" ).unwrap().collect::<Vec<_>>(), &["baz1" , "baz2" , "baz3" ]); |
2463 | /// ``` |
2464 | /// |
2465 | /// Now nofice if we don't specify `foo` or `baz` but use the `--` operator. |
2466 | /// |
2467 | /// ```rust |
2468 | /// # use clap_builder as clap; |
2469 | /// # use clap::{Command, Arg, ArgAction}; |
2470 | /// // Assume there is an external subcommand named "subcmd" |
2471 | /// let m = Command::new("myprog" ) |
2472 | /// .allow_missing_positional(true) |
2473 | /// .arg(Arg::new("foo" )) |
2474 | /// .arg(Arg::new("bar" )) |
2475 | /// .arg(Arg::new("baz" ).action(ArgAction::Set).num_args(1..)) |
2476 | /// .get_matches_from(vec![ |
2477 | /// "prog" , "--" , "baz1" , "baz2" , "baz3" |
2478 | /// ]); |
2479 | /// |
2480 | /// assert_eq!(m.get_one::<String>("foo" ), None); |
2481 | /// assert_eq!(m.get_one::<String>("bar" ), None); |
2482 | /// assert_eq!(m.get_many::<String>("baz" ).unwrap().collect::<Vec<_>>(), &["baz1" , "baz2" , "baz3" ]); |
2483 | /// ``` |
2484 | /// |
2485 | /// [required]: crate::Arg::required() |
2486 | #[inline ] |
2487 | pub fn allow_missing_positional(self, yes: bool) -> Self { |
2488 | if yes { |
2489 | self.setting(AppSettings::AllowMissingPositional) |
2490 | } else { |
2491 | self.unset_setting(AppSettings::AllowMissingPositional) |
2492 | } |
2493 | } |
2494 | } |
2495 | |
2496 | /// # Subcommand-specific Settings |
2497 | impl Command { |
2498 | /// Sets the short version of the subcommand flag without the preceding `-`. |
2499 | /// |
2500 | /// Allows the subcommand to be used as if it were an [`Arg::short`]. |
2501 | /// |
2502 | /// # Examples |
2503 | /// |
2504 | /// ``` |
2505 | /// # use clap_builder as clap; |
2506 | /// # use clap::{Command, Arg, ArgAction}; |
2507 | /// let matches = Command::new("pacman" ) |
2508 | /// .subcommand( |
2509 | /// Command::new("sync" ).short_flag('S' ).arg( |
2510 | /// Arg::new("search" ) |
2511 | /// .short('s' ) |
2512 | /// .long("search" ) |
2513 | /// .action(ArgAction::SetTrue) |
2514 | /// .help("search remote repositories for matching strings" ), |
2515 | /// ), |
2516 | /// ) |
2517 | /// .get_matches_from(vec!["pacman" , "-Ss" ]); |
2518 | /// |
2519 | /// assert_eq!(matches.subcommand_name().unwrap(), "sync" ); |
2520 | /// let sync_matches = matches.subcommand_matches("sync" ).unwrap(); |
2521 | /// assert!(sync_matches.get_flag("search" )); |
2522 | /// ``` |
2523 | /// [`Arg::short`]: Arg::short() |
2524 | #[must_use ] |
2525 | pub fn short_flag(mut self, short: impl IntoResettable<char>) -> Self { |
2526 | self.short_flag = short.into_resettable().into_option(); |
2527 | self |
2528 | } |
2529 | |
2530 | /// Sets the long version of the subcommand flag without the preceding `--`. |
2531 | /// |
2532 | /// Allows the subcommand to be used as if it were an [`Arg::long`]. |
2533 | /// |
2534 | /// <div class="warning"> |
2535 | /// |
2536 | /// **NOTE:** Any leading `-` characters will be stripped. |
2537 | /// |
2538 | /// </div> |
2539 | /// |
2540 | /// # Examples |
2541 | /// |
2542 | /// To set `long_flag` use a word containing valid UTF-8 codepoints. If you supply a double leading |
2543 | /// `--` such as `--sync` they will be stripped. Hyphens in the middle of the word; however, |
2544 | /// will *not* be stripped (i.e. `sync-file` is allowed). |
2545 | /// |
2546 | /// ```rust |
2547 | /// # use clap_builder as clap; |
2548 | /// # use clap::{Command, Arg, ArgAction}; |
2549 | /// let matches = Command::new("pacman" ) |
2550 | /// .subcommand( |
2551 | /// Command::new("sync" ).long_flag("sync" ).arg( |
2552 | /// Arg::new("search" ) |
2553 | /// .short('s' ) |
2554 | /// .long("search" ) |
2555 | /// .action(ArgAction::SetTrue) |
2556 | /// .help("search remote repositories for matching strings" ), |
2557 | /// ), |
2558 | /// ) |
2559 | /// .get_matches_from(vec!["pacman" , "--sync" , "--search" ]); |
2560 | /// |
2561 | /// assert_eq!(matches.subcommand_name().unwrap(), "sync" ); |
2562 | /// let sync_matches = matches.subcommand_matches("sync" ).unwrap(); |
2563 | /// assert!(sync_matches.get_flag("search" )); |
2564 | /// ``` |
2565 | /// |
2566 | /// [`Arg::long`]: Arg::long() |
2567 | #[must_use ] |
2568 | pub fn long_flag(mut self, long: impl Into<Str>) -> Self { |
2569 | self.long_flag = Some(long.into()); |
2570 | self |
2571 | } |
2572 | |
2573 | /// Sets a hidden alias to this subcommand. |
2574 | /// |
2575 | /// This allows the subcommand to be accessed via *either* the original name, or this given |
2576 | /// alias. This is more efficient and easier than creating multiple hidden subcommands as one |
2577 | /// only needs to check for the existence of this command, and not all aliased variants. |
2578 | /// |
2579 | /// <div class="warning"> |
2580 | /// |
2581 | /// **NOTE:** Aliases defined with this method are *hidden* from the help |
2582 | /// message. If you're looking for aliases that will be displayed in the help |
2583 | /// message, see [`Command::visible_alias`]. |
2584 | /// |
2585 | /// </div> |
2586 | /// |
2587 | /// <div class="warning"> |
2588 | /// |
2589 | /// **NOTE:** When using aliases and checking for the existence of a |
2590 | /// particular subcommand within an [`ArgMatches`] struct, one only needs to |
2591 | /// search for the original name and not all aliases. |
2592 | /// |
2593 | /// </div> |
2594 | /// |
2595 | /// # Examples |
2596 | /// |
2597 | /// ```rust |
2598 | /// # use clap_builder as clap; |
2599 | /// # use clap::{Command, Arg, }; |
2600 | /// let m = Command::new("myprog" ) |
2601 | /// .subcommand(Command::new("test" ) |
2602 | /// .alias("do-stuff" )) |
2603 | /// .get_matches_from(vec!["myprog" , "do-stuff" ]); |
2604 | /// assert_eq!(m.subcommand_name(), Some("test" )); |
2605 | /// ``` |
2606 | /// [`Command::visible_alias`]: Command::visible_alias() |
2607 | #[must_use ] |
2608 | pub fn alias(mut self, name: impl IntoResettable<Str>) -> Self { |
2609 | if let Some(name) = name.into_resettable().into_option() { |
2610 | self.aliases.push((name, false)); |
2611 | } else { |
2612 | self.aliases.clear(); |
2613 | } |
2614 | self |
2615 | } |
2616 | |
2617 | /// Add an alias, which functions as "hidden" short flag subcommand |
2618 | /// |
2619 | /// This will automatically dispatch as if this subcommand was used. This is more efficient, |
2620 | /// and easier than creating multiple hidden subcommands as one only needs to check for the |
2621 | /// existence of this command, and not all variants. |
2622 | /// |
2623 | /// # Examples |
2624 | /// |
2625 | /// ```rust |
2626 | /// # use clap_builder as clap; |
2627 | /// # use clap::{Command, Arg, }; |
2628 | /// let m = Command::new("myprog" ) |
2629 | /// .subcommand(Command::new("test" ).short_flag('t' ) |
2630 | /// .short_flag_alias('d' )) |
2631 | /// .get_matches_from(vec!["myprog" , "-d" ]); |
2632 | /// assert_eq!(m.subcommand_name(), Some("test" )); |
2633 | /// ``` |
2634 | #[must_use ] |
2635 | pub fn short_flag_alias(mut self, name: impl IntoResettable<char>) -> Self { |
2636 | if let Some(name) = name.into_resettable().into_option() { |
2637 | debug_assert!(name != '-' , "short alias name cannot be `-`" ); |
2638 | self.short_flag_aliases.push((name, false)); |
2639 | } else { |
2640 | self.short_flag_aliases.clear(); |
2641 | } |
2642 | self |
2643 | } |
2644 | |
2645 | /// Add an alias, which functions as a "hidden" long flag subcommand. |
2646 | /// |
2647 | /// This will automatically dispatch as if this subcommand was used. This is more efficient, |
2648 | /// and easier than creating multiple hidden subcommands as one only needs to check for the |
2649 | /// existence of this command, and not all variants. |
2650 | /// |
2651 | /// # Examples |
2652 | /// |
2653 | /// ```rust |
2654 | /// # use clap_builder as clap; |
2655 | /// # use clap::{Command, Arg, }; |
2656 | /// let m = Command::new("myprog" ) |
2657 | /// .subcommand(Command::new("test" ).long_flag("test" ) |
2658 | /// .long_flag_alias("testing" )) |
2659 | /// .get_matches_from(vec!["myprog" , "--testing" ]); |
2660 | /// assert_eq!(m.subcommand_name(), Some("test" )); |
2661 | /// ``` |
2662 | #[must_use ] |
2663 | pub fn long_flag_alias(mut self, name: impl IntoResettable<Str>) -> Self { |
2664 | if let Some(name) = name.into_resettable().into_option() { |
2665 | self.long_flag_aliases.push((name, false)); |
2666 | } else { |
2667 | self.long_flag_aliases.clear(); |
2668 | } |
2669 | self |
2670 | } |
2671 | |
2672 | /// Sets multiple hidden aliases to this subcommand. |
2673 | /// |
2674 | /// This allows the subcommand to be accessed via *either* the original name or any of the |
2675 | /// given aliases. This is more efficient, and easier than creating multiple hidden subcommands |
2676 | /// as one only needs to check for the existence of this command and not all aliased variants. |
2677 | /// |
2678 | /// <div class="warning"> |
2679 | /// |
2680 | /// **NOTE:** Aliases defined with this method are *hidden* from the help |
2681 | /// message. If looking for aliases that will be displayed in the help |
2682 | /// message, see [`Command::visible_aliases`]. |
2683 | /// |
2684 | /// </div> |
2685 | /// |
2686 | /// <div class="warning"> |
2687 | /// |
2688 | /// **NOTE:** When using aliases and checking for the existence of a |
2689 | /// particular subcommand within an [`ArgMatches`] struct, one only needs to |
2690 | /// search for the original name and not all aliases. |
2691 | /// |
2692 | /// </div> |
2693 | /// |
2694 | /// # Examples |
2695 | /// |
2696 | /// ```rust |
2697 | /// # use clap_builder as clap; |
2698 | /// # use clap::{Command, Arg}; |
2699 | /// let m = Command::new("myprog" ) |
2700 | /// .subcommand(Command::new("test" ) |
2701 | /// .aliases(["do-stuff" , "do-tests" , "tests" ])) |
2702 | /// .arg(Arg::new("input" ) |
2703 | /// .help("the file to add" ) |
2704 | /// .required(false)) |
2705 | /// .get_matches_from(vec!["myprog" , "do-tests" ]); |
2706 | /// assert_eq!(m.subcommand_name(), Some("test" )); |
2707 | /// ``` |
2708 | /// [`Command::visible_aliases`]: Command::visible_aliases() |
2709 | #[must_use ] |
2710 | pub fn aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { |
2711 | self.aliases |
2712 | .extend(names.into_iter().map(|n| (n.into(), false))); |
2713 | self |
2714 | } |
2715 | |
2716 | /// Add aliases, which function as "hidden" short flag subcommands. |
2717 | /// |
2718 | /// These will automatically dispatch as if this subcommand was used. This is more efficient, |
2719 | /// and easier than creating multiple hidden subcommands as one only needs to check for the |
2720 | /// existence of this command, and not all variants. |
2721 | /// |
2722 | /// # Examples |
2723 | /// |
2724 | /// ```rust |
2725 | /// # use clap_builder as clap; |
2726 | /// # use clap::{Command, Arg, }; |
2727 | /// let m = Command::new("myprog" ) |
2728 | /// .subcommand(Command::new("test" ).short_flag('t' ) |
2729 | /// .short_flag_aliases(['a' , 'b' , 'c' ])) |
2730 | /// .arg(Arg::new("input" ) |
2731 | /// .help("the file to add" ) |
2732 | /// .required(false)) |
2733 | /// .get_matches_from(vec!["myprog" , "-a" ]); |
2734 | /// assert_eq!(m.subcommand_name(), Some("test" )); |
2735 | /// ``` |
2736 | #[must_use ] |
2737 | pub fn short_flag_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self { |
2738 | for s in names { |
2739 | debug_assert!(s != '-' , "short alias name cannot be `-`" ); |
2740 | self.short_flag_aliases.push((s, false)); |
2741 | } |
2742 | self |
2743 | } |
2744 | |
2745 | /// Add aliases, which function as "hidden" long flag subcommands. |
2746 | /// |
2747 | /// These will automatically dispatch as if this subcommand was used. This is more efficient, |
2748 | /// and easier than creating multiple hidden subcommands as one only needs to check for the |
2749 | /// existence of this command, and not all variants. |
2750 | /// |
2751 | /// # Examples |
2752 | /// |
2753 | /// ```rust |
2754 | /// # use clap_builder as clap; |
2755 | /// # use clap::{Command, Arg, }; |
2756 | /// let m = Command::new("myprog" ) |
2757 | /// .subcommand(Command::new("test" ).long_flag("test" ) |
2758 | /// .long_flag_aliases(["testing" , "testall" , "test_all" ])) |
2759 | /// .arg(Arg::new("input" ) |
2760 | /// .help("the file to add" ) |
2761 | /// .required(false)) |
2762 | /// .get_matches_from(vec!["myprog" , "--testing" ]); |
2763 | /// assert_eq!(m.subcommand_name(), Some("test" )); |
2764 | /// ``` |
2765 | #[must_use ] |
2766 | pub fn long_flag_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { |
2767 | for s in names { |
2768 | self = self.long_flag_alias(s); |
2769 | } |
2770 | self |
2771 | } |
2772 | |
2773 | /// Sets a visible alias to this subcommand. |
2774 | /// |
2775 | /// This allows the subcommand to be accessed via *either* the |
2776 | /// original name or the given alias. This is more efficient and easier |
2777 | /// than creating hidden subcommands as one only needs to check for |
2778 | /// the existence of this command and not all aliased variants. |
2779 | /// |
2780 | /// <div class="warning"> |
2781 | /// |
2782 | /// **NOTE:** The alias defined with this method is *visible* from the help |
2783 | /// message and displayed as if it were just another regular subcommand. If |
2784 | /// looking for an alias that will not be displayed in the help message, see |
2785 | /// [`Command::alias`]. |
2786 | /// |
2787 | /// </div> |
2788 | /// |
2789 | /// <div class="warning"> |
2790 | /// |
2791 | /// **NOTE:** When using aliases and checking for the existence of a |
2792 | /// particular subcommand within an [`ArgMatches`] struct, one only needs to |
2793 | /// search for the original name and not all aliases. |
2794 | /// |
2795 | /// </div> |
2796 | /// |
2797 | /// # Examples |
2798 | /// |
2799 | /// ```rust |
2800 | /// # use clap_builder as clap; |
2801 | /// # use clap::{Command, Arg}; |
2802 | /// let m = Command::new("myprog" ) |
2803 | /// .subcommand(Command::new("test" ) |
2804 | /// .visible_alias("do-stuff" )) |
2805 | /// .get_matches_from(vec!["myprog" , "do-stuff" ]); |
2806 | /// assert_eq!(m.subcommand_name(), Some("test" )); |
2807 | /// ``` |
2808 | /// [`Command::alias`]: Command::alias() |
2809 | #[must_use ] |
2810 | pub fn visible_alias(mut self, name: impl IntoResettable<Str>) -> Self { |
2811 | if let Some(name) = name.into_resettable().into_option() { |
2812 | self.aliases.push((name, true)); |
2813 | } else { |
2814 | self.aliases.clear(); |
2815 | } |
2816 | self |
2817 | } |
2818 | |
2819 | /// Add an alias, which functions as "visible" short flag subcommand |
2820 | /// |
2821 | /// This will automatically dispatch as if this subcommand was used. This is more efficient, |
2822 | /// and easier than creating multiple hidden subcommands as one only needs to check for the |
2823 | /// existence of this command, and not all variants. |
2824 | /// |
2825 | /// See also [`Command::short_flag_alias`]. |
2826 | /// |
2827 | /// # Examples |
2828 | /// |
2829 | /// ```rust |
2830 | /// # use clap_builder as clap; |
2831 | /// # use clap::{Command, Arg, }; |
2832 | /// let m = Command::new("myprog" ) |
2833 | /// .subcommand(Command::new("test" ).short_flag('t' ) |
2834 | /// .visible_short_flag_alias('d' )) |
2835 | /// .get_matches_from(vec!["myprog" , "-d" ]); |
2836 | /// assert_eq!(m.subcommand_name(), Some("test" )); |
2837 | /// ``` |
2838 | /// [`Command::short_flag_alias`]: Command::short_flag_alias() |
2839 | #[must_use ] |
2840 | pub fn visible_short_flag_alias(mut self, name: impl IntoResettable<char>) -> Self { |
2841 | if let Some(name) = name.into_resettable().into_option() { |
2842 | debug_assert!(name != '-' , "short alias name cannot be `-`" ); |
2843 | self.short_flag_aliases.push((name, true)); |
2844 | } else { |
2845 | self.short_flag_aliases.clear(); |
2846 | } |
2847 | self |
2848 | } |
2849 | |
2850 | /// Add an alias, which functions as a "visible" long flag subcommand. |
2851 | /// |
2852 | /// This will automatically dispatch as if this subcommand was used. This is more efficient, |
2853 | /// and easier than creating multiple hidden subcommands as one only needs to check for the |
2854 | /// existence of this command, and not all variants. |
2855 | /// |
2856 | /// See also [`Command::long_flag_alias`]. |
2857 | /// |
2858 | /// # Examples |
2859 | /// |
2860 | /// ```rust |
2861 | /// # use clap_builder as clap; |
2862 | /// # use clap::{Command, Arg, }; |
2863 | /// let m = Command::new("myprog" ) |
2864 | /// .subcommand(Command::new("test" ).long_flag("test" ) |
2865 | /// .visible_long_flag_alias("testing" )) |
2866 | /// .get_matches_from(vec!["myprog" , "--testing" ]); |
2867 | /// assert_eq!(m.subcommand_name(), Some("test" )); |
2868 | /// ``` |
2869 | /// [`Command::long_flag_alias`]: Command::long_flag_alias() |
2870 | #[must_use ] |
2871 | pub fn visible_long_flag_alias(mut self, name: impl IntoResettable<Str>) -> Self { |
2872 | if let Some(name) = name.into_resettable().into_option() { |
2873 | self.long_flag_aliases.push((name, true)); |
2874 | } else { |
2875 | self.long_flag_aliases.clear(); |
2876 | } |
2877 | self |
2878 | } |
2879 | |
2880 | /// Sets multiple visible aliases to this subcommand. |
2881 | /// |
2882 | /// This allows the subcommand to be accessed via *either* the |
2883 | /// original name or any of the given aliases. This is more efficient and easier |
2884 | /// than creating multiple hidden subcommands as one only needs to check for |
2885 | /// the existence of this command and not all aliased variants. |
2886 | /// |
2887 | /// <div class="warning"> |
2888 | /// |
2889 | /// **NOTE:** The alias defined with this method is *visible* from the help |
2890 | /// message and displayed as if it were just another regular subcommand. If |
2891 | /// looking for an alias that will not be displayed in the help message, see |
2892 | /// [`Command::alias`]. |
2893 | /// |
2894 | /// </div> |
2895 | /// |
2896 | /// <div class="warning"> |
2897 | /// |
2898 | /// **NOTE:** When using aliases, and checking for the existence of a |
2899 | /// particular subcommand within an [`ArgMatches`] struct, one only needs to |
2900 | /// search for the original name and not all aliases. |
2901 | /// |
2902 | /// </div> |
2903 | /// |
2904 | /// # Examples |
2905 | /// |
2906 | /// ```rust |
2907 | /// # use clap_builder as clap; |
2908 | /// # use clap::{Command, Arg, }; |
2909 | /// let m = Command::new("myprog" ) |
2910 | /// .subcommand(Command::new("test" ) |
2911 | /// .visible_aliases(["do-stuff" , "tests" ])) |
2912 | /// .get_matches_from(vec!["myprog" , "do-stuff" ]); |
2913 | /// assert_eq!(m.subcommand_name(), Some("test" )); |
2914 | /// ``` |
2915 | /// [`Command::alias`]: Command::alias() |
2916 | #[must_use ] |
2917 | pub fn visible_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { |
2918 | self.aliases |
2919 | .extend(names.into_iter().map(|n| (n.into(), true))); |
2920 | self |
2921 | } |
2922 | |
2923 | /// Add aliases, which function as *visible* short flag subcommands. |
2924 | /// |
2925 | /// See [`Command::short_flag_aliases`]. |
2926 | /// |
2927 | /// # Examples |
2928 | /// |
2929 | /// ```rust |
2930 | /// # use clap_builder as clap; |
2931 | /// # use clap::{Command, Arg, }; |
2932 | /// let m = Command::new("myprog" ) |
2933 | /// .subcommand(Command::new("test" ).short_flag('b' ) |
2934 | /// .visible_short_flag_aliases(['t' ])) |
2935 | /// .get_matches_from(vec!["myprog" , "-t" ]); |
2936 | /// assert_eq!(m.subcommand_name(), Some("test" )); |
2937 | /// ``` |
2938 | /// [`Command::short_flag_aliases`]: Command::short_flag_aliases() |
2939 | #[must_use ] |
2940 | pub fn visible_short_flag_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self { |
2941 | for s in names { |
2942 | debug_assert!(s != '-' , "short alias name cannot be `-`" ); |
2943 | self.short_flag_aliases.push((s, true)); |
2944 | } |
2945 | self |
2946 | } |
2947 | |
2948 | /// Add aliases, which function as *visible* long flag subcommands. |
2949 | /// |
2950 | /// See [`Command::long_flag_aliases`]. |
2951 | /// |
2952 | /// # Examples |
2953 | /// |
2954 | /// ```rust |
2955 | /// # use clap_builder as clap; |
2956 | /// # use clap::{Command, Arg, }; |
2957 | /// let m = Command::new("myprog" ) |
2958 | /// .subcommand(Command::new("test" ).long_flag("test" ) |
2959 | /// .visible_long_flag_aliases(["testing" , "testall" , "test_all" ])) |
2960 | /// .get_matches_from(vec!["myprog" , "--testing" ]); |
2961 | /// assert_eq!(m.subcommand_name(), Some("test" )); |
2962 | /// ``` |
2963 | /// [`Command::long_flag_aliases`]: Command::long_flag_aliases() |
2964 | #[must_use ] |
2965 | pub fn visible_long_flag_aliases( |
2966 | mut self, |
2967 | names: impl IntoIterator<Item = impl Into<Str>>, |
2968 | ) -> Self { |
2969 | for s in names { |
2970 | self = self.visible_long_flag_alias(s); |
2971 | } |
2972 | self |
2973 | } |
2974 | |
2975 | /// Set the placement of this subcommand within the help. |
2976 | /// |
2977 | /// Subcommands with a lower value will be displayed first in the help message. |
2978 | /// Those with the same display order will be sorted. |
2979 | /// |
2980 | /// `Command`s are automatically assigned a display order based on the order they are added to |
2981 | /// their parent [`Command`]. |
2982 | /// Overriding this is helpful when the order commands are added in isn't the same as the |
2983 | /// display order, whether in one-off cases or to automatically sort commands. |
2984 | /// |
2985 | /// # Examples |
2986 | /// |
2987 | /// ```rust |
2988 | /// # #[cfg (feature = "help" )] { |
2989 | /// # use clap_builder as clap; |
2990 | /// # use clap::{Command, }; |
2991 | /// let m = Command::new("cust-ord" ) |
2992 | /// .subcommand(Command::new("beta" ) |
2993 | /// .display_order(0) // Sort |
2994 | /// .about("Some help and text" )) |
2995 | /// .subcommand(Command::new("alpha" ) |
2996 | /// .display_order(0) // Sort |
2997 | /// .about("I should be first!" )) |
2998 | /// .get_matches_from(vec![ |
2999 | /// "cust-ord" , "--help" |
3000 | /// ]); |
3001 | /// # } |
3002 | /// ``` |
3003 | /// |
3004 | /// The above example displays the following help message |
3005 | /// |
3006 | /// ```text |
3007 | /// cust-ord |
3008 | /// |
3009 | /// Usage: cust-ord [OPTIONS] |
3010 | /// |
3011 | /// Commands: |
3012 | /// alpha I should be first! |
3013 | /// beta Some help and text |
3014 | /// help Print help for the subcommand(s) |
3015 | /// |
3016 | /// Options: |
3017 | /// -h, --help Print help |
3018 | /// -V, --version Print version |
3019 | /// ``` |
3020 | #[inline ] |
3021 | #[must_use ] |
3022 | pub fn display_order(mut self, ord: impl IntoResettable<usize>) -> Self { |
3023 | self.disp_ord = ord.into_resettable().into_option(); |
3024 | self |
3025 | } |
3026 | |
3027 | /// Specifies that this [`subcommand`] should be hidden from help messages |
3028 | /// |
3029 | /// # Examples |
3030 | /// |
3031 | /// ```rust |
3032 | /// # use clap_builder as clap; |
3033 | /// # use clap::{Command, Arg}; |
3034 | /// Command::new("myprog" ) |
3035 | /// .subcommand( |
3036 | /// Command::new("test" ).hide(true) |
3037 | /// ) |
3038 | /// # ; |
3039 | /// ``` |
3040 | /// |
3041 | /// [`subcommand`]: crate::Command::subcommand() |
3042 | #[inline ] |
3043 | pub fn hide(self, yes: bool) -> Self { |
3044 | if yes { |
3045 | self.setting(AppSettings::Hidden) |
3046 | } else { |
3047 | self.unset_setting(AppSettings::Hidden) |
3048 | } |
3049 | } |
3050 | |
3051 | /// If no [`subcommand`] is present at runtime, error and exit gracefully. |
3052 | /// |
3053 | /// # Examples |
3054 | /// |
3055 | /// ```rust |
3056 | /// # use clap_builder as clap; |
3057 | /// # use clap::{Command, error::ErrorKind}; |
3058 | /// let err = Command::new("myprog" ) |
3059 | /// .subcommand_required(true) |
3060 | /// .subcommand(Command::new("test" )) |
3061 | /// .try_get_matches_from(vec![ |
3062 | /// "myprog" , |
3063 | /// ]); |
3064 | /// assert!(err.is_err()); |
3065 | /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand); |
3066 | /// # ; |
3067 | /// ``` |
3068 | /// |
3069 | /// [`subcommand`]: crate::Command::subcommand() |
3070 | pub fn subcommand_required(self, yes: bool) -> Self { |
3071 | if yes { |
3072 | self.setting(AppSettings::SubcommandRequired) |
3073 | } else { |
3074 | self.unset_setting(AppSettings::SubcommandRequired) |
3075 | } |
3076 | } |
3077 | |
3078 | /// Assume unexpected positional arguments are a [`subcommand`]. |
3079 | /// |
3080 | /// Arguments will be stored in the `""` argument in the [`ArgMatches`] |
3081 | /// |
3082 | /// <div class="warning"> |
3083 | /// |
3084 | /// **NOTE:** Use this setting with caution, |
3085 | /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand) |
3086 | /// will **not** cause an error and instead be treated as a potential subcommand. |
3087 | /// One should check for such cases manually and inform the user appropriately. |
3088 | /// |
3089 | /// </div> |
3090 | /// |
3091 | /// <div class="warning"> |
3092 | /// |
3093 | /// **NOTE:** A built-in subcommand will be parsed as an external subcommand when escaped with |
3094 | /// `--`. |
3095 | /// |
3096 | /// </div> |
3097 | /// |
3098 | /// # Examples |
3099 | /// |
3100 | /// ```rust |
3101 | /// # use clap_builder as clap; |
3102 | /// # use std::ffi::OsString; |
3103 | /// # use clap::Command; |
3104 | /// // Assume there is an external subcommand named "subcmd" |
3105 | /// let m = Command::new("myprog" ) |
3106 | /// .allow_external_subcommands(true) |
3107 | /// .get_matches_from(vec![ |
3108 | /// "myprog" , "subcmd" , "--option" , "value" , "-fff" , "--flag" |
3109 | /// ]); |
3110 | /// |
3111 | /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty |
3112 | /// // string argument name |
3113 | /// match m.subcommand() { |
3114 | /// Some((external, ext_m)) => { |
3115 | /// let ext_args: Vec<_> = ext_m.get_many::<OsString>("" ).unwrap().collect(); |
3116 | /// assert_eq!(external, "subcmd" ); |
3117 | /// assert_eq!(ext_args, ["--option" , "value" , "-fff" , "--flag" ]); |
3118 | /// }, |
3119 | /// _ => {}, |
3120 | /// } |
3121 | /// ``` |
3122 | /// |
3123 | /// [`subcommand`]: crate::Command::subcommand() |
3124 | /// [`ArgMatches`]: crate::ArgMatches |
3125 | /// [`ErrorKind::UnknownArgument`]: crate::error::ErrorKind::UnknownArgument |
3126 | pub fn allow_external_subcommands(self, yes: bool) -> Self { |
3127 | if yes { |
3128 | self.setting(AppSettings::AllowExternalSubcommands) |
3129 | } else { |
3130 | self.unset_setting(AppSettings::AllowExternalSubcommands) |
3131 | } |
3132 | } |
3133 | |
3134 | /// Specifies how to parse external subcommand arguments. |
3135 | /// |
3136 | /// The default parser is for `OsString`. This can be used to switch it to `String` or another |
3137 | /// type. |
3138 | /// |
3139 | /// <div class="warning"> |
3140 | /// |
3141 | /// **NOTE:** Setting this requires [`Command::allow_external_subcommands`] |
3142 | /// |
3143 | /// </div> |
3144 | /// |
3145 | /// # Examples |
3146 | /// |
3147 | /// ```rust |
3148 | /// # #[cfg (unix)] { |
3149 | /// # use clap_builder as clap; |
3150 | /// # use std::ffi::OsString; |
3151 | /// # use clap::Command; |
3152 | /// # use clap::value_parser; |
3153 | /// // Assume there is an external subcommand named "subcmd" |
3154 | /// let m = Command::new("myprog" ) |
3155 | /// .allow_external_subcommands(true) |
3156 | /// .get_matches_from(vec![ |
3157 | /// "myprog" , "subcmd" , "--option" , "value" , "-fff" , "--flag" |
3158 | /// ]); |
3159 | /// |
3160 | /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty |
3161 | /// // string argument name |
3162 | /// match m.subcommand() { |
3163 | /// Some((external, ext_m)) => { |
3164 | /// let ext_args: Vec<_> = ext_m.get_many::<OsString>("" ).unwrap().collect(); |
3165 | /// assert_eq!(external, "subcmd" ); |
3166 | /// assert_eq!(ext_args, ["--option" , "value" , "-fff" , "--flag" ]); |
3167 | /// }, |
3168 | /// _ => {}, |
3169 | /// } |
3170 | /// # } |
3171 | /// ``` |
3172 | /// |
3173 | /// ```rust |
3174 | /// # use clap_builder as clap; |
3175 | /// # use clap::Command; |
3176 | /// # use clap::value_parser; |
3177 | /// // Assume there is an external subcommand named "subcmd" |
3178 | /// let m = Command::new("myprog" ) |
3179 | /// .external_subcommand_value_parser(value_parser!(String)) |
3180 | /// .get_matches_from(vec![ |
3181 | /// "myprog" , "subcmd" , "--option" , "value" , "-fff" , "--flag" |
3182 | /// ]); |
3183 | /// |
3184 | /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty |
3185 | /// // string argument name |
3186 | /// match m.subcommand() { |
3187 | /// Some((external, ext_m)) => { |
3188 | /// let ext_args: Vec<_> = ext_m.get_many::<String>("" ).unwrap().collect(); |
3189 | /// assert_eq!(external, "subcmd" ); |
3190 | /// assert_eq!(ext_args, ["--option" , "value" , "-fff" , "--flag" ]); |
3191 | /// }, |
3192 | /// _ => {}, |
3193 | /// } |
3194 | /// ``` |
3195 | /// |
3196 | /// [`subcommands`]: crate::Command::subcommand() |
3197 | pub fn external_subcommand_value_parser( |
3198 | mut self, |
3199 | parser: impl IntoResettable<super::ValueParser>, |
3200 | ) -> Self { |
3201 | self.external_value_parser = parser.into_resettable().into_option(); |
3202 | self |
3203 | } |
3204 | |
3205 | /// Specifies that use of an argument prevents the use of [`subcommands`]. |
3206 | /// |
3207 | /// By default `clap` allows arguments between subcommands such |
3208 | /// as `<cmd> [cmd_args] <subcmd> [subcmd_args] <subsubcmd> [subsubcmd_args]`. |
3209 | /// |
3210 | /// This setting disables that functionality and says that arguments can |
3211 | /// only follow the *final* subcommand. For instance using this setting |
3212 | /// makes only the following invocations possible: |
3213 | /// |
3214 | /// * `<cmd> <subcmd> <subsubcmd> [subsubcmd_args]` |
3215 | /// * `<cmd> <subcmd> [subcmd_args]` |
3216 | /// * `<cmd> [cmd_args]` |
3217 | /// |
3218 | /// # Examples |
3219 | /// |
3220 | /// ```rust |
3221 | /// # use clap_builder as clap; |
3222 | /// # use clap::Command; |
3223 | /// Command::new("myprog" ) |
3224 | /// .args_conflicts_with_subcommands(true); |
3225 | /// ``` |
3226 | /// |
3227 | /// [`subcommands`]: crate::Command::subcommand() |
3228 | pub fn args_conflicts_with_subcommands(self, yes: bool) -> Self { |
3229 | if yes { |
3230 | self.setting(AppSettings::ArgsNegateSubcommands) |
3231 | } else { |
3232 | self.unset_setting(AppSettings::ArgsNegateSubcommands) |
3233 | } |
3234 | } |
3235 | |
3236 | /// Prevent subcommands from being consumed as an arguments value. |
3237 | /// |
3238 | /// By default, if an option taking multiple values is followed by a subcommand, the |
3239 | /// subcommand will be parsed as another value. |
3240 | /// |
3241 | /// ```text |
3242 | /// cmd --foo val1 val2 subcommand |
3243 | /// --------- ---------- |
3244 | /// values another value |
3245 | /// ``` |
3246 | /// |
3247 | /// This setting instructs the parser to stop when encountering a subcommand instead of |
3248 | /// greedily consuming arguments. |
3249 | /// |
3250 | /// ```text |
3251 | /// cmd --foo val1 val2 subcommand |
3252 | /// --------- ---------- |
3253 | /// values subcommand |
3254 | /// ``` |
3255 | /// |
3256 | /// # Examples |
3257 | /// |
3258 | /// ```rust |
3259 | /// # use clap_builder as clap; |
3260 | /// # use clap::{Command, Arg, ArgAction}; |
3261 | /// let cmd = Command::new("cmd" ).subcommand(Command::new("sub" )).arg( |
3262 | /// Arg::new("arg" ) |
3263 | /// .long("arg" ) |
3264 | /// .num_args(1..) |
3265 | /// .action(ArgAction::Set), |
3266 | /// ); |
3267 | /// |
3268 | /// let matches = cmd |
3269 | /// .clone() |
3270 | /// .try_get_matches_from(&["cmd" , "--arg" , "1" , "2" , "3" , "sub" ]) |
3271 | /// .unwrap(); |
3272 | /// assert_eq!( |
3273 | /// matches.get_many::<String>("arg" ).unwrap().collect::<Vec<_>>(), |
3274 | /// &["1" , "2" , "3" , "sub" ] |
3275 | /// ); |
3276 | /// assert!(matches.subcommand_matches("sub" ).is_none()); |
3277 | /// |
3278 | /// let matches = cmd |
3279 | /// .subcommand_precedence_over_arg(true) |
3280 | /// .try_get_matches_from(&["cmd" , "--arg" , "1" , "2" , "3" , "sub" ]) |
3281 | /// .unwrap(); |
3282 | /// assert_eq!( |
3283 | /// matches.get_many::<String>("arg" ).unwrap().collect::<Vec<_>>(), |
3284 | /// &["1" , "2" , "3" ] |
3285 | /// ); |
3286 | /// assert!(matches.subcommand_matches("sub" ).is_some()); |
3287 | /// ``` |
3288 | pub fn subcommand_precedence_over_arg(self, yes: bool) -> Self { |
3289 | if yes { |
3290 | self.setting(AppSettings::SubcommandPrecedenceOverArg) |
3291 | } else { |
3292 | self.unset_setting(AppSettings::SubcommandPrecedenceOverArg) |
3293 | } |
3294 | } |
3295 | |
3296 | /// Allows [`subcommands`] to override all requirements of the parent command. |
3297 | /// |
3298 | /// For example, if you had a subcommand or top level application with a required argument |
3299 | /// that is only required as long as there is no subcommand present, |
3300 | /// using this setting would allow you to set those arguments to [`Arg::required(true)`] |
3301 | /// and yet receive no error so long as the user uses a valid subcommand instead. |
3302 | /// |
3303 | /// <div class="warning"> |
3304 | /// |
3305 | /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements) |
3306 | /// |
3307 | /// </div> |
3308 | /// |
3309 | /// # Examples |
3310 | /// |
3311 | /// This first example shows that it is an error to not use a required argument |
3312 | /// |
3313 | /// ```rust |
3314 | /// # use clap_builder as clap; |
3315 | /// # use clap::{Command, Arg, error::ErrorKind}; |
3316 | /// let err = Command::new("myprog" ) |
3317 | /// .subcommand_negates_reqs(true) |
3318 | /// .arg(Arg::new("opt" ).required(true)) |
3319 | /// .subcommand(Command::new("test" )) |
3320 | /// .try_get_matches_from(vec![ |
3321 | /// "myprog" |
3322 | /// ]); |
3323 | /// assert!(err.is_err()); |
3324 | /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); |
3325 | /// # ; |
3326 | /// ``` |
3327 | /// |
3328 | /// This next example shows that it is no longer error to not use a required argument if a |
3329 | /// valid subcommand is used. |
3330 | /// |
3331 | /// ```rust |
3332 | /// # use clap_builder as clap; |
3333 | /// # use clap::{Command, Arg, error::ErrorKind}; |
3334 | /// let noerr = Command::new("myprog" ) |
3335 | /// .subcommand_negates_reqs(true) |
3336 | /// .arg(Arg::new("opt" ).required(true)) |
3337 | /// .subcommand(Command::new("test" )) |
3338 | /// .try_get_matches_from(vec![ |
3339 | /// "myprog" , "test" |
3340 | /// ]); |
3341 | /// assert!(noerr.is_ok()); |
3342 | /// # ; |
3343 | /// ``` |
3344 | /// |
3345 | /// [`Arg::required(true)`]: crate::Arg::required() |
3346 | /// [`subcommands`]: crate::Command::subcommand() |
3347 | pub fn subcommand_negates_reqs(self, yes: bool) -> Self { |
3348 | if yes { |
3349 | self.setting(AppSettings::SubcommandsNegateReqs) |
3350 | } else { |
3351 | self.unset_setting(AppSettings::SubcommandsNegateReqs) |
3352 | } |
3353 | } |
3354 | |
3355 | /// Multiple-personality program dispatched on the binary name (`argv[0]`) |
3356 | /// |
3357 | /// A "multicall" executable is a single executable |
3358 | /// that contains a variety of applets, |
3359 | /// and decides which applet to run based on the name of the file. |
3360 | /// The executable can be called from different names by creating hard links |
3361 | /// or symbolic links to it. |
3362 | /// |
3363 | /// This is desirable for: |
3364 | /// - Easy distribution, a single binary that can install hardlinks to access the different |
3365 | /// personalities. |
3366 | /// - Minimal binary size by sharing common code (e.g. standard library, clap) |
3367 | /// - Custom shells or REPLs where there isn't a single top-level command |
3368 | /// |
3369 | /// Setting `multicall` will cause |
3370 | /// - `argv[0]` to be stripped to the base name and parsed as the first argument, as if |
3371 | /// [`Command::no_binary_name`][Command::no_binary_name] was set. |
3372 | /// - Help and errors to report subcommands as if they were the top-level command |
3373 | /// |
3374 | /// When the subcommand is not present, there are several strategies you may employ, depending |
3375 | /// on your needs: |
3376 | /// - Let the error percolate up normally |
3377 | /// - Print a specialized error message using the |
3378 | /// [`Error::context`][crate::Error::context] |
3379 | /// - Print the [help][Command::write_help] but this might be ambiguous |
3380 | /// - Disable `multicall` and re-parse it |
3381 | /// - Disable `multicall` and re-parse it with a specific subcommand |
3382 | /// |
3383 | /// When detecting the error condition, the [`ErrorKind`] isn't sufficient as a sub-subcommand |
3384 | /// might report the same error. Enable |
3385 | /// [`allow_external_subcommands`][Command::allow_external_subcommands] if you want to specifically |
3386 | /// get the unrecognized binary name. |
3387 | /// |
3388 | /// <div class="warning"> |
3389 | /// |
3390 | /// **NOTE:** Multicall can't be used with [`no_binary_name`] since they interpret |
3391 | /// the command name in incompatible ways. |
3392 | /// |
3393 | /// </div> |
3394 | /// |
3395 | /// <div class="warning"> |
3396 | /// |
3397 | /// **NOTE:** The multicall command cannot have arguments. |
3398 | /// |
3399 | /// </div> |
3400 | /// |
3401 | /// <div class="warning"> |
3402 | /// |
3403 | /// **NOTE:** Applets are slightly semantically different from subcommands, |
3404 | /// so it's recommended to use [`Command::subcommand_help_heading`] and |
3405 | /// [`Command::subcommand_value_name`] to change the descriptive text as above. |
3406 | /// |
3407 | /// </div> |
3408 | /// |
3409 | /// # Examples |
3410 | /// |
3411 | /// `hostname` is an example of a multicall executable. |
3412 | /// Both `hostname` and `dnsdomainname` are provided by the same executable |
3413 | /// and which behaviour to use is based on the executable file name. |
3414 | /// |
3415 | /// This is desirable when the executable has a primary purpose |
3416 | /// but there is related functionality that would be convenient to provide |
3417 | /// and implement it to be in the same executable. |
3418 | /// |
3419 | /// The name of the cmd is essentially unused |
3420 | /// and may be the same as the name of a subcommand. |
3421 | /// |
3422 | /// The names of the immediate subcommands of the Command |
3423 | /// are matched against the basename of the first argument, |
3424 | /// which is conventionally the path of the executable. |
3425 | /// |
3426 | /// This does not allow the subcommand to be passed as the first non-path argument. |
3427 | /// |
3428 | /// ```rust |
3429 | /// # use clap_builder as clap; |
3430 | /// # use clap::{Command, error::ErrorKind}; |
3431 | /// let mut cmd = Command::new("hostname" ) |
3432 | /// .multicall(true) |
3433 | /// .subcommand(Command::new("hostname" )) |
3434 | /// .subcommand(Command::new("dnsdomainname" )); |
3435 | /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/hostname" , "dnsdomainname" ]); |
3436 | /// assert!(m.is_err()); |
3437 | /// assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument); |
3438 | /// let m = cmd.get_matches_from(&["/usr/bin/dnsdomainname" ]); |
3439 | /// assert_eq!(m.subcommand_name(), Some("dnsdomainname" )); |
3440 | /// ``` |
3441 | /// |
3442 | /// Busybox is another common example of a multicall executable |
3443 | /// with a subcommmand for each applet that can be run directly, |
3444 | /// e.g. with the `cat` applet being run by running `busybox cat`, |
3445 | /// or with `cat` as a link to the `busybox` binary. |
3446 | /// |
3447 | /// This is desirable when the launcher program has additional options |
3448 | /// or it is useful to run the applet without installing a symlink |
3449 | /// e.g. to test the applet without installing it |
3450 | /// or there may already be a command of that name installed. |
3451 | /// |
3452 | /// To make an applet usable as both a multicall link and a subcommand |
3453 | /// the subcommands must be defined both in the top-level Command |
3454 | /// and as subcommands of the "main" applet. |
3455 | /// |
3456 | /// ```rust |
3457 | /// # use clap_builder as clap; |
3458 | /// # use clap::Command; |
3459 | /// fn applet_commands() -> [Command; 2] { |
3460 | /// [Command::new("true" ), Command::new("false" )] |
3461 | /// } |
3462 | /// let mut cmd = Command::new("busybox" ) |
3463 | /// .multicall(true) |
3464 | /// .subcommand( |
3465 | /// Command::new("busybox" ) |
3466 | /// .subcommand_value_name("APPLET" ) |
3467 | /// .subcommand_help_heading("APPLETS" ) |
3468 | /// .subcommands(applet_commands()), |
3469 | /// ) |
3470 | /// .subcommands(applet_commands()); |
3471 | /// // When called from the executable's canonical name |
3472 | /// // its applets can be matched as subcommands. |
3473 | /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/busybox" , "true" ]).unwrap(); |
3474 | /// assert_eq!(m.subcommand_name(), Some("busybox" )); |
3475 | /// assert_eq!(m.subcommand().unwrap().1.subcommand_name(), Some("true" )); |
3476 | /// // When called from a link named after an applet that applet is matched. |
3477 | /// let m = cmd.get_matches_from(&["/usr/bin/true" ]); |
3478 | /// assert_eq!(m.subcommand_name(), Some("true" )); |
3479 | /// ``` |
3480 | /// |
3481 | /// [`no_binary_name`]: crate::Command::no_binary_name |
3482 | /// [`Command::subcommand_value_name`]: crate::Command::subcommand_value_name |
3483 | /// [`Command::subcommand_help_heading`]: crate::Command::subcommand_help_heading |
3484 | #[inline ] |
3485 | pub fn multicall(self, yes: bool) -> Self { |
3486 | if yes { |
3487 | self.setting(AppSettings::Multicall) |
3488 | } else { |
3489 | self.unset_setting(AppSettings::Multicall) |
3490 | } |
3491 | } |
3492 | |
3493 | /// Sets the value name used for subcommands when printing usage and help. |
3494 | /// |
3495 | /// By default, this is "COMMAND". |
3496 | /// |
3497 | /// See also [`Command::subcommand_help_heading`] |
3498 | /// |
3499 | /// # Examples |
3500 | /// |
3501 | /// ```rust |
3502 | /// # use clap_builder as clap; |
3503 | /// # use clap::{Command, Arg}; |
3504 | /// Command::new("myprog" ) |
3505 | /// .subcommand(Command::new("sub1" )) |
3506 | /// .print_help() |
3507 | /// # ; |
3508 | /// ``` |
3509 | /// |
3510 | /// will produce |
3511 | /// |
3512 | /// ```text |
3513 | /// myprog |
3514 | /// |
3515 | /// Usage: myprog [COMMAND] |
3516 | /// |
3517 | /// Commands: |
3518 | /// help Print this message or the help of the given subcommand(s) |
3519 | /// sub1 |
3520 | /// |
3521 | /// Options: |
3522 | /// -h, --help Print help |
3523 | /// -V, --version Print version |
3524 | /// ``` |
3525 | /// |
3526 | /// but usage of `subcommand_value_name` |
3527 | /// |
3528 | /// ```rust |
3529 | /// # use clap_builder as clap; |
3530 | /// # use clap::{Command, Arg}; |
3531 | /// Command::new("myprog" ) |
3532 | /// .subcommand(Command::new("sub1" )) |
3533 | /// .subcommand_value_name("THING" ) |
3534 | /// .print_help() |
3535 | /// # ; |
3536 | /// ``` |
3537 | /// |
3538 | /// will produce |
3539 | /// |
3540 | /// ```text |
3541 | /// myprog |
3542 | /// |
3543 | /// Usage: myprog [THING] |
3544 | /// |
3545 | /// Commands: |
3546 | /// help Print this message or the help of the given subcommand(s) |
3547 | /// sub1 |
3548 | /// |
3549 | /// Options: |
3550 | /// -h, --help Print help |
3551 | /// -V, --version Print version |
3552 | /// ``` |
3553 | #[must_use ] |
3554 | pub fn subcommand_value_name(mut self, value_name: impl IntoResettable<Str>) -> Self { |
3555 | self.subcommand_value_name = value_name.into_resettable().into_option(); |
3556 | self |
3557 | } |
3558 | |
3559 | /// Sets the help heading used for subcommands when printing usage and help. |
3560 | /// |
3561 | /// By default, this is "Commands". |
3562 | /// |
3563 | /// See also [`Command::subcommand_value_name`] |
3564 | /// |
3565 | /// # Examples |
3566 | /// |
3567 | /// ```rust |
3568 | /// # use clap_builder as clap; |
3569 | /// # use clap::{Command, Arg}; |
3570 | /// Command::new("myprog" ) |
3571 | /// .subcommand(Command::new("sub1" )) |
3572 | /// .print_help() |
3573 | /// # ; |
3574 | /// ``` |
3575 | /// |
3576 | /// will produce |
3577 | /// |
3578 | /// ```text |
3579 | /// myprog |
3580 | /// |
3581 | /// Usage: myprog [COMMAND] |
3582 | /// |
3583 | /// Commands: |
3584 | /// help Print this message or the help of the given subcommand(s) |
3585 | /// sub1 |
3586 | /// |
3587 | /// Options: |
3588 | /// -h, --help Print help |
3589 | /// -V, --version Print version |
3590 | /// ``` |
3591 | /// |
3592 | /// but usage of `subcommand_help_heading` |
3593 | /// |
3594 | /// ```rust |
3595 | /// # use clap_builder as clap; |
3596 | /// # use clap::{Command, Arg}; |
3597 | /// Command::new("myprog" ) |
3598 | /// .subcommand(Command::new("sub1" )) |
3599 | /// .subcommand_help_heading("Things" ) |
3600 | /// .print_help() |
3601 | /// # ; |
3602 | /// ``` |
3603 | /// |
3604 | /// will produce |
3605 | /// |
3606 | /// ```text |
3607 | /// myprog |
3608 | /// |
3609 | /// Usage: myprog [COMMAND] |
3610 | /// |
3611 | /// Things: |
3612 | /// help Print this message or the help of the given subcommand(s) |
3613 | /// sub1 |
3614 | /// |
3615 | /// Options: |
3616 | /// -h, --help Print help |
3617 | /// -V, --version Print version |
3618 | /// ``` |
3619 | #[must_use ] |
3620 | pub fn subcommand_help_heading(mut self, heading: impl IntoResettable<Str>) -> Self { |
3621 | self.subcommand_heading = heading.into_resettable().into_option(); |
3622 | self |
3623 | } |
3624 | } |
3625 | |
3626 | /// # Reflection |
3627 | impl Command { |
3628 | #[inline ] |
3629 | #[cfg (feature = "usage" )] |
3630 | pub(crate) fn get_usage_name(&self) -> Option<&str> { |
3631 | self.usage_name.as_deref() |
3632 | } |
3633 | |
3634 | #[inline ] |
3635 | #[cfg (feature = "usage" )] |
3636 | pub(crate) fn get_usage_name_fallback(&self) -> &str { |
3637 | self.get_usage_name() |
3638 | .unwrap_or_else(|| self.get_bin_name_fallback()) |
3639 | } |
3640 | |
3641 | #[inline ] |
3642 | #[cfg (not(feature = "usage" ))] |
3643 | #[allow (dead_code)] |
3644 | pub(crate) fn get_usage_name_fallback(&self) -> &str { |
3645 | self.get_bin_name_fallback() |
3646 | } |
3647 | |
3648 | /// Get the name of the binary. |
3649 | #[inline ] |
3650 | pub fn get_display_name(&self) -> Option<&str> { |
3651 | self.display_name.as_deref() |
3652 | } |
3653 | |
3654 | /// Get the name of the binary. |
3655 | #[inline ] |
3656 | pub fn get_bin_name(&self) -> Option<&str> { |
3657 | self.bin_name.as_deref() |
3658 | } |
3659 | |
3660 | /// Get the name of the binary. |
3661 | #[inline ] |
3662 | pub(crate) fn get_bin_name_fallback(&self) -> &str { |
3663 | self.bin_name.as_deref().unwrap_or_else(|| self.get_name()) |
3664 | } |
3665 | |
3666 | /// Set binary name. Uses `&mut self` instead of `self`. |
3667 | pub fn set_bin_name(&mut self, name: impl Into<String>) { |
3668 | self.bin_name = Some(name.into()); |
3669 | } |
3670 | |
3671 | /// Get the name of the cmd. |
3672 | #[inline ] |
3673 | pub fn get_name(&self) -> &str { |
3674 | self.name.as_str() |
3675 | } |
3676 | |
3677 | #[inline ] |
3678 | #[cfg (debug_assertions)] |
3679 | pub(crate) fn get_name_str(&self) -> &Str { |
3680 | &self.name |
3681 | } |
3682 | |
3683 | /// Get all known names of the cmd (i.e. primary name and visible aliases). |
3684 | pub fn get_name_and_visible_aliases(&self) -> Vec<&str> { |
3685 | let mut names = vec![self.name.as_str()]; |
3686 | names.extend(self.get_visible_aliases()); |
3687 | names |
3688 | } |
3689 | |
3690 | /// Get the version of the cmd. |
3691 | #[inline ] |
3692 | pub fn get_version(&self) -> Option<&str> { |
3693 | self.version.as_deref() |
3694 | } |
3695 | |
3696 | /// Get the long version of the cmd. |
3697 | #[inline ] |
3698 | pub fn get_long_version(&self) -> Option<&str> { |
3699 | self.long_version.as_deref() |
3700 | } |
3701 | |
3702 | /// Get the placement within help |
3703 | #[inline ] |
3704 | pub fn get_display_order(&self) -> usize { |
3705 | self.disp_ord.unwrap_or(999) |
3706 | } |
3707 | |
3708 | /// Get the authors of the cmd. |
3709 | #[inline ] |
3710 | pub fn get_author(&self) -> Option<&str> { |
3711 | self.author.as_deref() |
3712 | } |
3713 | |
3714 | /// Get the short flag of the subcommand. |
3715 | #[inline ] |
3716 | pub fn get_short_flag(&self) -> Option<char> { |
3717 | self.short_flag |
3718 | } |
3719 | |
3720 | /// Get the long flag of the subcommand. |
3721 | #[inline ] |
3722 | pub fn get_long_flag(&self) -> Option<&str> { |
3723 | self.long_flag.as_deref() |
3724 | } |
3725 | |
3726 | /// Get the help message specified via [`Command::about`]. |
3727 | /// |
3728 | /// [`Command::about`]: Command::about() |
3729 | #[inline ] |
3730 | pub fn get_about(&self) -> Option<&StyledStr> { |
3731 | self.about.as_ref() |
3732 | } |
3733 | |
3734 | /// Get the help message specified via [`Command::long_about`]. |
3735 | /// |
3736 | /// [`Command::long_about`]: Command::long_about() |
3737 | #[inline ] |
3738 | pub fn get_long_about(&self) -> Option<&StyledStr> { |
3739 | self.long_about.as_ref() |
3740 | } |
3741 | |
3742 | /// Get the custom section heading specified via [`Command::flatten_help`]. |
3743 | #[inline ] |
3744 | pub fn is_flatten_help_set(&self) -> bool { |
3745 | self.is_set(AppSettings::FlattenHelp) |
3746 | } |
3747 | |
3748 | /// Get the custom section heading specified via [`Command::next_help_heading`]. |
3749 | /// |
3750 | /// [`Command::help_heading`]: Command::help_heading() |
3751 | #[inline ] |
3752 | pub fn get_next_help_heading(&self) -> Option<&str> { |
3753 | self.current_help_heading.as_deref() |
3754 | } |
3755 | |
3756 | /// Iterate through the *visible* aliases for this subcommand. |
3757 | #[inline ] |
3758 | pub fn get_visible_aliases(&self) -> impl Iterator<Item = &str> + '_ { |
3759 | self.aliases |
3760 | .iter() |
3761 | .filter(|(_, vis)| *vis) |
3762 | .map(|a| a.0.as_str()) |
3763 | } |
3764 | |
3765 | /// Iterate through the *visible* short aliases for this subcommand. |
3766 | #[inline ] |
3767 | pub fn get_visible_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ { |
3768 | self.short_flag_aliases |
3769 | .iter() |
3770 | .filter(|(_, vis)| *vis) |
3771 | .map(|a| a.0) |
3772 | } |
3773 | |
3774 | /// Iterate through the *visible* long aliases for this subcommand. |
3775 | #[inline ] |
3776 | pub fn get_visible_long_flag_aliases(&self) -> impl Iterator<Item = &str> + '_ { |
3777 | self.long_flag_aliases |
3778 | .iter() |
3779 | .filter(|(_, vis)| *vis) |
3780 | .map(|a| a.0.as_str()) |
3781 | } |
3782 | |
3783 | /// Iterate through the set of *all* the aliases for this subcommand, both visible and hidden. |
3784 | #[inline ] |
3785 | pub fn get_all_aliases(&self) -> impl Iterator<Item = &str> + '_ { |
3786 | self.aliases.iter().map(|a| a.0.as_str()) |
3787 | } |
3788 | |
3789 | /// Iterate through the set of *all* the short aliases for this subcommand, both visible and hidden. |
3790 | #[inline ] |
3791 | pub fn get_all_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ { |
3792 | self.short_flag_aliases.iter().map(|a| a.0) |
3793 | } |
3794 | |
3795 | /// Iterate through the set of *all* the long aliases for this subcommand, both visible and hidden. |
3796 | #[inline ] |
3797 | pub fn get_all_long_flag_aliases(&self) -> impl Iterator<Item = &str> + '_ { |
3798 | self.long_flag_aliases.iter().map(|a| a.0.as_str()) |
3799 | } |
3800 | |
3801 | /// Iterate through the *hidden* aliases for this subcommand. |
3802 | #[inline ] |
3803 | pub fn get_aliases(&self) -> impl Iterator<Item = &str> + '_ { |
3804 | self.aliases |
3805 | .iter() |
3806 | .filter(|(_, vis)| !*vis) |
3807 | .map(|a| a.0.as_str()) |
3808 | } |
3809 | |
3810 | #[inline ] |
3811 | pub(crate) fn is_set(&self, s: AppSettings) -> bool { |
3812 | self.settings.is_set(s) || self.g_settings.is_set(s) |
3813 | } |
3814 | |
3815 | /// Should we color the output? |
3816 | pub fn get_color(&self) -> ColorChoice { |
3817 | debug!("Command::color: Color setting..." ); |
3818 | |
3819 | if cfg!(feature = "color" ) { |
3820 | if self.is_set(AppSettings::ColorNever) { |
3821 | debug!("Never" ); |
3822 | ColorChoice::Never |
3823 | } else if self.is_set(AppSettings::ColorAlways) { |
3824 | debug!("Always" ); |
3825 | ColorChoice::Always |
3826 | } else { |
3827 | debug!("Auto" ); |
3828 | ColorChoice::Auto |
3829 | } |
3830 | } else { |
3831 | ColorChoice::Never |
3832 | } |
3833 | } |
3834 | |
3835 | /// Return the current `Styles` for the `Command` |
3836 | #[inline ] |
3837 | pub fn get_styles(&self) -> &Styles { |
3838 | self.app_ext.get().unwrap_or_default() |
3839 | } |
3840 | |
3841 | /// Iterate through the set of subcommands, getting a reference to each. |
3842 | #[inline ] |
3843 | pub fn get_subcommands(&self) -> impl Iterator<Item = &Command> { |
3844 | self.subcommands.iter() |
3845 | } |
3846 | |
3847 | /// Iterate through the set of subcommands, getting a mutable reference to each. |
3848 | #[inline ] |
3849 | pub fn get_subcommands_mut(&mut self) -> impl Iterator<Item = &mut Command> { |
3850 | self.subcommands.iter_mut() |
3851 | } |
3852 | |
3853 | /// Returns `true` if this `Command` has subcommands. |
3854 | #[inline ] |
3855 | pub fn has_subcommands(&self) -> bool { |
3856 | !self.subcommands.is_empty() |
3857 | } |
3858 | |
3859 | /// Returns the help heading for listing subcommands. |
3860 | #[inline ] |
3861 | pub fn get_subcommand_help_heading(&self) -> Option<&str> { |
3862 | self.subcommand_heading.as_deref() |
3863 | } |
3864 | |
3865 | /// Returns the subcommand value name. |
3866 | #[inline ] |
3867 | pub fn get_subcommand_value_name(&self) -> Option<&str> { |
3868 | self.subcommand_value_name.as_deref() |
3869 | } |
3870 | |
3871 | /// Returns the help heading for listing subcommands. |
3872 | #[inline ] |
3873 | pub fn get_before_help(&self) -> Option<&StyledStr> { |
3874 | self.before_help.as_ref() |
3875 | } |
3876 | |
3877 | /// Returns the help heading for listing subcommands. |
3878 | #[inline ] |
3879 | pub fn get_before_long_help(&self) -> Option<&StyledStr> { |
3880 | self.before_long_help.as_ref() |
3881 | } |
3882 | |
3883 | /// Returns the help heading for listing subcommands. |
3884 | #[inline ] |
3885 | pub fn get_after_help(&self) -> Option<&StyledStr> { |
3886 | self.after_help.as_ref() |
3887 | } |
3888 | |
3889 | /// Returns the help heading for listing subcommands. |
3890 | #[inline ] |
3891 | pub fn get_after_long_help(&self) -> Option<&StyledStr> { |
3892 | self.after_long_help.as_ref() |
3893 | } |
3894 | |
3895 | /// Find subcommand such that its name or one of aliases equals `name`. |
3896 | /// |
3897 | /// This does not recurse through subcommands of subcommands. |
3898 | #[inline ] |
3899 | pub fn find_subcommand(&self, name: impl AsRef<std::ffi::OsStr>) -> Option<&Command> { |
3900 | let name = name.as_ref(); |
3901 | self.get_subcommands().find(|s| s.aliases_to(name)) |
3902 | } |
3903 | |
3904 | /// Find subcommand such that its name or one of aliases equals `name`, returning |
3905 | /// a mutable reference to the subcommand. |
3906 | /// |
3907 | /// This does not recurse through subcommands of subcommands. |
3908 | #[inline ] |
3909 | pub fn find_subcommand_mut( |
3910 | &mut self, |
3911 | name: impl AsRef<std::ffi::OsStr>, |
3912 | ) -> Option<&mut Command> { |
3913 | let name = name.as_ref(); |
3914 | self.get_subcommands_mut().find(|s| s.aliases_to(name)) |
3915 | } |
3916 | |
3917 | /// Iterate through the set of groups. |
3918 | #[inline ] |
3919 | pub fn get_groups(&self) -> impl Iterator<Item = &ArgGroup> { |
3920 | self.groups.iter() |
3921 | } |
3922 | |
3923 | /// Iterate through the set of arguments. |
3924 | #[inline ] |
3925 | pub fn get_arguments(&self) -> impl Iterator<Item = &Arg> { |
3926 | self.args.args() |
3927 | } |
3928 | |
3929 | /// Iterate through the *positionals* arguments. |
3930 | #[inline ] |
3931 | pub fn get_positionals(&self) -> impl Iterator<Item = &Arg> { |
3932 | self.get_arguments().filter(|a| a.is_positional()) |
3933 | } |
3934 | |
3935 | /// Iterate through the *options*. |
3936 | pub fn get_opts(&self) -> impl Iterator<Item = &Arg> { |
3937 | self.get_arguments() |
3938 | .filter(|a| a.is_takes_value_set() && !a.is_positional()) |
3939 | } |
3940 | |
3941 | /// Get a list of all arguments the given argument conflicts with. |
3942 | /// |
3943 | /// If the provided argument is declared as global, the conflicts will be determined |
3944 | /// based on the propagation rules of global arguments. |
3945 | /// |
3946 | /// ### Panics |
3947 | /// |
3948 | /// If the given arg contains a conflict with an argument that is unknown to |
3949 | /// this `Command`. |
3950 | pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator |
3951 | { |
3952 | if arg.is_global_set() { |
3953 | self.get_global_arg_conflicts_with(arg) |
3954 | } else { |
3955 | let mut result = Vec::new(); |
3956 | for id in arg.blacklist.iter() { |
3957 | if let Some(arg) = self.find(id) { |
3958 | result.push(arg); |
3959 | } else if let Some(group) = self.find_group(id) { |
3960 | result.extend( |
3961 | self.unroll_args_in_group(&group.id) |
3962 | .iter() |
3963 | .map(|id| self.find(id).expect(INTERNAL_ERROR_MSG)), |
3964 | ); |
3965 | } else { |
3966 | panic!("Command::get_arg_conflicts_with: The passed arg conflicts with an arg unknown to the cmd" ); |
3967 | } |
3968 | } |
3969 | result |
3970 | } |
3971 | } |
3972 | |
3973 | /// Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with. |
3974 | /// |
3975 | /// This behavior follows the propagation rules of global arguments. |
3976 | /// It is useful for finding conflicts for arguments declared as global. |
3977 | /// |
3978 | /// ### Panics |
3979 | /// |
3980 | /// If the given arg contains a conflict with an argument that is unknown to |
3981 | /// this `Command`. |
3982 | fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator |
3983 | { |
3984 | arg.blacklist |
3985 | .iter() |
3986 | .map(|id| { |
3987 | self.args |
3988 | .args() |
3989 | .chain( |
3990 | self.get_subcommands_containing(arg) |
3991 | .iter() |
3992 | .flat_map(|x| x.args.args()), |
3993 | ) |
3994 | .find(|arg| arg.get_id() == id) |
3995 | .expect( |
3996 | "Command::get_arg_conflicts_with: \ |
3997 | The passed arg conflicts with an arg unknown to the cmd" , |
3998 | ) |
3999 | }) |
4000 | .collect() |
4001 | } |
4002 | |
4003 | /// Get a list of subcommands which contain the provided Argument |
4004 | /// |
4005 | /// This command will only include subcommands in its list for which the subcommands |
4006 | /// parent also contains the Argument. |
4007 | /// |
4008 | /// This search follows the propagation rules of global arguments. |
4009 | /// It is useful to finding subcommands, that have inherited a global argument. |
4010 | /// |
4011 | /// <div class="warning"> |
4012 | /// |
4013 | /// **NOTE:** In this case only `Sucommand_1` will be included |
4014 | /// ```text |
4015 | /// Subcommand_1 (contains Arg) |
4016 | /// Subcommand_1.1 (doesn't contain Arg) |
4017 | /// Subcommand_1.1.1 (contains Arg) |
4018 | /// ``` |
4019 | /// |
4020 | /// </div> |
4021 | fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&Self> { |
4022 | let mut vec = Vec::new(); |
4023 | for idx in 0..self.subcommands.len() { |
4024 | if self.subcommands[idx] |
4025 | .args |
4026 | .args() |
4027 | .any(|ar| ar.get_id() == arg.get_id()) |
4028 | { |
4029 | vec.push(&self.subcommands[idx]); |
4030 | vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg)); |
4031 | } |
4032 | } |
4033 | vec |
4034 | } |
4035 | |
4036 | /// Report whether [`Command::no_binary_name`] is set |
4037 | pub fn is_no_binary_name_set(&self) -> bool { |
4038 | self.is_set(AppSettings::NoBinaryName) |
4039 | } |
4040 | |
4041 | /// Report whether [`Command::ignore_errors`] is set |
4042 | pub(crate) fn is_ignore_errors_set(&self) -> bool { |
4043 | self.is_set(AppSettings::IgnoreErrors) |
4044 | } |
4045 | |
4046 | /// Report whether [`Command::dont_delimit_trailing_values`] is set |
4047 | pub fn is_dont_delimit_trailing_values_set(&self) -> bool { |
4048 | self.is_set(AppSettings::DontDelimitTrailingValues) |
4049 | } |
4050 | |
4051 | /// Report whether [`Command::disable_version_flag`] is set |
4052 | pub fn is_disable_version_flag_set(&self) -> bool { |
4053 | self.is_set(AppSettings::DisableVersionFlag) |
4054 | || (self.version.is_none() && self.long_version.is_none()) |
4055 | } |
4056 | |
4057 | /// Report whether [`Command::propagate_version`] is set |
4058 | pub fn is_propagate_version_set(&self) -> bool { |
4059 | self.is_set(AppSettings::PropagateVersion) |
4060 | } |
4061 | |
4062 | /// Report whether [`Command::next_line_help`] is set |
4063 | pub fn is_next_line_help_set(&self) -> bool { |
4064 | self.is_set(AppSettings::NextLineHelp) |
4065 | } |
4066 | |
4067 | /// Report whether [`Command::disable_help_flag`] is set |
4068 | pub fn is_disable_help_flag_set(&self) -> bool { |
4069 | self.is_set(AppSettings::DisableHelpFlag) |
4070 | } |
4071 | |
4072 | /// Report whether [`Command::disable_help_subcommand`] is set |
4073 | pub fn is_disable_help_subcommand_set(&self) -> bool { |
4074 | self.is_set(AppSettings::DisableHelpSubcommand) |
4075 | } |
4076 | |
4077 | /// Report whether [`Command::disable_colored_help`] is set |
4078 | pub fn is_disable_colored_help_set(&self) -> bool { |
4079 | self.is_set(AppSettings::DisableColoredHelp) |
4080 | } |
4081 | |
4082 | /// Report whether [`Command::help_expected`] is set |
4083 | #[cfg (debug_assertions)] |
4084 | pub(crate) fn is_help_expected_set(&self) -> bool { |
4085 | self.is_set(AppSettings::HelpExpected) |
4086 | } |
4087 | |
4088 | #[doc (hidden)] |
4089 | #[cfg_attr ( |
4090 | feature = "deprecated" , |
4091 | deprecated(since = "4.0.0" , note = "This is now the default" ) |
4092 | )] |
4093 | pub fn is_dont_collapse_args_in_usage_set(&self) -> bool { |
4094 | true |
4095 | } |
4096 | |
4097 | /// Report whether [`Command::infer_long_args`] is set |
4098 | pub(crate) fn is_infer_long_args_set(&self) -> bool { |
4099 | self.is_set(AppSettings::InferLongArgs) |
4100 | } |
4101 | |
4102 | /// Report whether [`Command::infer_subcommands`] is set |
4103 | pub(crate) fn is_infer_subcommands_set(&self) -> bool { |
4104 | self.is_set(AppSettings::InferSubcommands) |
4105 | } |
4106 | |
4107 | /// Report whether [`Command::arg_required_else_help`] is set |
4108 | pub fn is_arg_required_else_help_set(&self) -> bool { |
4109 | self.is_set(AppSettings::ArgRequiredElseHelp) |
4110 | } |
4111 | |
4112 | #[doc (hidden)] |
4113 | #[cfg_attr ( |
4114 | feature = "deprecated" , |
4115 | deprecated( |
4116 | since = "4.0.0" , |
4117 | note = "Replaced with `Arg::is_allow_hyphen_values_set`" |
4118 | ) |
4119 | )] |
4120 | pub(crate) fn is_allow_hyphen_values_set(&self) -> bool { |
4121 | self.is_set(AppSettings::AllowHyphenValues) |
4122 | } |
4123 | |
4124 | #[doc (hidden)] |
4125 | #[cfg_attr ( |
4126 | feature = "deprecated" , |
4127 | deprecated( |
4128 | since = "4.0.0" , |
4129 | note = "Replaced with `Arg::is_allow_negative_numbers_set`" |
4130 | ) |
4131 | )] |
4132 | pub fn is_allow_negative_numbers_set(&self) -> bool { |
4133 | self.is_set(AppSettings::AllowNegativeNumbers) |
4134 | } |
4135 | |
4136 | #[doc (hidden)] |
4137 | #[cfg_attr ( |
4138 | feature = "deprecated" , |
4139 | deprecated(since = "4.0.0" , note = "Replaced with `Arg::is_trailing_var_arg_set`" ) |
4140 | )] |
4141 | pub fn is_trailing_var_arg_set(&self) -> bool { |
4142 | self.is_set(AppSettings::TrailingVarArg) |
4143 | } |
4144 | |
4145 | /// Report whether [`Command::allow_missing_positional`] is set |
4146 | pub fn is_allow_missing_positional_set(&self) -> bool { |
4147 | self.is_set(AppSettings::AllowMissingPositional) |
4148 | } |
4149 | |
4150 | /// Report whether [`Command::hide`] is set |
4151 | pub fn is_hide_set(&self) -> bool { |
4152 | self.is_set(AppSettings::Hidden) |
4153 | } |
4154 | |
4155 | /// Report whether [`Command::subcommand_required`] is set |
4156 | pub fn is_subcommand_required_set(&self) -> bool { |
4157 | self.is_set(AppSettings::SubcommandRequired) |
4158 | } |
4159 | |
4160 | /// Report whether [`Command::allow_external_subcommands`] is set |
4161 | pub fn is_allow_external_subcommands_set(&self) -> bool { |
4162 | self.is_set(AppSettings::AllowExternalSubcommands) |
4163 | } |
4164 | |
4165 | /// Configured parser for values passed to an external subcommand |
4166 | /// |
4167 | /// # Example |
4168 | /// |
4169 | /// ```rust |
4170 | /// # use clap_builder as clap; |
4171 | /// let cmd = clap::Command::new("raw" ) |
4172 | /// .external_subcommand_value_parser(clap::value_parser!(String)); |
4173 | /// let value_parser = cmd.get_external_subcommand_value_parser(); |
4174 | /// println!("{value_parser:?}" ); |
4175 | /// ``` |
4176 | pub fn get_external_subcommand_value_parser(&self) -> Option<&super::ValueParser> { |
4177 | if !self.is_allow_external_subcommands_set() { |
4178 | None |
4179 | } else { |
4180 | static DEFAULT: super::ValueParser = super::ValueParser::os_string(); |
4181 | Some(self.external_value_parser.as_ref().unwrap_or(&DEFAULT)) |
4182 | } |
4183 | } |
4184 | |
4185 | /// Report whether [`Command::args_conflicts_with_subcommands`] is set |
4186 | pub fn is_args_conflicts_with_subcommands_set(&self) -> bool { |
4187 | self.is_set(AppSettings::ArgsNegateSubcommands) |
4188 | } |
4189 | |
4190 | #[doc (hidden)] |
4191 | pub fn is_args_override_self(&self) -> bool { |
4192 | self.is_set(AppSettings::AllArgsOverrideSelf) |
4193 | } |
4194 | |
4195 | /// Report whether [`Command::subcommand_precedence_over_arg`] is set |
4196 | pub fn is_subcommand_precedence_over_arg_set(&self) -> bool { |
4197 | self.is_set(AppSettings::SubcommandPrecedenceOverArg) |
4198 | } |
4199 | |
4200 | /// Report whether [`Command::subcommand_negates_reqs`] is set |
4201 | pub fn is_subcommand_negates_reqs_set(&self) -> bool { |
4202 | self.is_set(AppSettings::SubcommandsNegateReqs) |
4203 | } |
4204 | |
4205 | /// Report whether [`Command::multicall`] is set |
4206 | pub fn is_multicall_set(&self) -> bool { |
4207 | self.is_set(AppSettings::Multicall) |
4208 | } |
4209 | |
4210 | /// Access an [`CommandExt`] |
4211 | #[cfg (feature = "unstable-ext" )] |
4212 | pub fn get<T: CommandExt + Extension>(&self) -> Option<&T> { |
4213 | self.ext.get::<T>() |
4214 | } |
4215 | |
4216 | /// Remove an [`CommandExt`] |
4217 | #[cfg (feature = "unstable-ext" )] |
4218 | pub fn remove<T: CommandExt + Extension>(mut self) -> Option<T> { |
4219 | self.ext.remove::<T>() |
4220 | } |
4221 | } |
4222 | |
4223 | // Internally used only |
4224 | impl Command { |
4225 | pub(crate) fn get_override_usage(&self) -> Option<&StyledStr> { |
4226 | self.usage_str.as_ref() |
4227 | } |
4228 | |
4229 | pub(crate) fn get_override_help(&self) -> Option<&StyledStr> { |
4230 | self.help_str.as_ref() |
4231 | } |
4232 | |
4233 | #[cfg (feature = "help" )] |
4234 | pub(crate) fn get_help_template(&self) -> Option<&StyledStr> { |
4235 | self.template.as_ref() |
4236 | } |
4237 | |
4238 | #[cfg (feature = "help" )] |
4239 | pub(crate) fn get_term_width(&self) -> Option<usize> { |
4240 | self.app_ext.get::<TermWidth>().map(|e| e.0) |
4241 | } |
4242 | |
4243 | #[cfg (feature = "help" )] |
4244 | pub(crate) fn get_max_term_width(&self) -> Option<usize> { |
4245 | self.app_ext.get::<MaxTermWidth>().map(|e| e.0) |
4246 | } |
4247 | |
4248 | pub(crate) fn get_keymap(&self) -> &MKeyMap { |
4249 | &self.args |
4250 | } |
4251 | |
4252 | fn get_used_global_args(&self, matches: &ArgMatches, global_arg_vec: &mut Vec<Id>) { |
4253 | global_arg_vec.extend( |
4254 | self.args |
4255 | .args() |
4256 | .filter(|a| a.is_global_set()) |
4257 | .map(|ga| ga.id.clone()), |
4258 | ); |
4259 | if let Some((id, matches)) = matches.subcommand() { |
4260 | if let Some(used_sub) = self.find_subcommand(id) { |
4261 | used_sub.get_used_global_args(matches, global_arg_vec); |
4262 | } |
4263 | } |
4264 | } |
4265 | |
4266 | fn _do_parse( |
4267 | &mut self, |
4268 | raw_args: &mut clap_lex::RawArgs, |
4269 | args_cursor: clap_lex::ArgCursor, |
4270 | ) -> ClapResult<ArgMatches> { |
4271 | debug!("Command::_do_parse" ); |
4272 | |
4273 | // If there are global arguments, or settings we need to propagate them down to subcommands |
4274 | // before parsing in case we run into a subcommand |
4275 | self._build_self(false); |
4276 | |
4277 | let mut matcher = ArgMatcher::new(self); |
4278 | |
4279 | // do the real parsing |
4280 | let mut parser = Parser::new(self); |
4281 | if let Err(error) = parser.get_matches_with(&mut matcher, raw_args, args_cursor) { |
4282 | if self.is_set(AppSettings::IgnoreErrors) && error.use_stderr() { |
4283 | debug!("Command::_do_parse: ignoring error: {error}" ); |
4284 | } else { |
4285 | return Err(error); |
4286 | } |
4287 | } |
4288 | |
4289 | let mut global_arg_vec = Default::default(); |
4290 | self.get_used_global_args(&matcher, &mut global_arg_vec); |
4291 | |
4292 | matcher.propagate_globals(&global_arg_vec); |
4293 | |
4294 | Ok(matcher.into_inner()) |
4295 | } |
4296 | |
4297 | /// Prepare for introspecting on all included [`Command`]s |
4298 | /// |
4299 | /// Call this on the top-level [`Command`] when done building and before reading state for |
4300 | /// cases like completions, custom help output, etc. |
4301 | pub fn build(&mut self) { |
4302 | self._build_recursive(true); |
4303 | self._build_bin_names_internal(); |
4304 | } |
4305 | |
4306 | pub(crate) fn _build_recursive(&mut self, expand_help_tree: bool) { |
4307 | self._build_self(expand_help_tree); |
4308 | for subcmd in self.get_subcommands_mut() { |
4309 | subcmd._build_recursive(expand_help_tree); |
4310 | } |
4311 | } |
4312 | |
4313 | pub(crate) fn _build_self(&mut self, expand_help_tree: bool) { |
4314 | debug!("Command::_build: name={:?}" , self.get_name()); |
4315 | if !self.settings.is_set(AppSettings::Built) { |
4316 | if let Some(deferred) = self.deferred.take() { |
4317 | *self = (deferred)(std::mem::take(self)); |
4318 | } |
4319 | |
4320 | // Make sure all the globally set flags apply to us as well |
4321 | self.settings = self.settings | self.g_settings; |
4322 | |
4323 | if self.is_multicall_set() { |
4324 | self.settings.set(AppSettings::SubcommandRequired); |
4325 | self.settings.set(AppSettings::DisableHelpFlag); |
4326 | self.settings.set(AppSettings::DisableVersionFlag); |
4327 | } |
4328 | if !cfg!(feature = "help" ) && self.get_override_help().is_none() { |
4329 | self.settings.set(AppSettings::DisableHelpFlag); |
4330 | self.settings.set(AppSettings::DisableHelpSubcommand); |
4331 | } |
4332 | if self.is_set(AppSettings::ArgsNegateSubcommands) { |
4333 | self.settings.set(AppSettings::SubcommandsNegateReqs); |
4334 | } |
4335 | if self.external_value_parser.is_some() { |
4336 | self.settings.set(AppSettings::AllowExternalSubcommands); |
4337 | } |
4338 | if !self.has_subcommands() { |
4339 | self.settings.set(AppSettings::DisableHelpSubcommand); |
4340 | } |
4341 | |
4342 | self._propagate(); |
4343 | self._check_help_and_version(expand_help_tree); |
4344 | self._propagate_global_args(); |
4345 | |
4346 | let mut pos_counter = 1; |
4347 | let hide_pv = self.is_set(AppSettings::HidePossibleValues); |
4348 | for a in self.args.args_mut() { |
4349 | // Fill in the groups |
4350 | for g in &a.groups { |
4351 | if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) { |
4352 | ag.args.push(a.get_id().clone()); |
4353 | } else { |
4354 | let mut ag = ArgGroup::new(g); |
4355 | ag.args.push(a.get_id().clone()); |
4356 | self.groups.push(ag); |
4357 | } |
4358 | } |
4359 | |
4360 | // Figure out implied settings |
4361 | a._build(); |
4362 | if hide_pv && a.is_takes_value_set() { |
4363 | a.settings.set(ArgSettings::HidePossibleValues); |
4364 | } |
4365 | if a.is_positional() && a.index.is_none() { |
4366 | a.index = Some(pos_counter); |
4367 | pos_counter += 1; |
4368 | } |
4369 | } |
4370 | |
4371 | self.args._build(); |
4372 | |
4373 | #[allow (deprecated)] |
4374 | { |
4375 | let highest_idx = self |
4376 | .get_keymap() |
4377 | .keys() |
4378 | .filter_map(|x| { |
4379 | if let crate::mkeymap::KeyType::Position(n) = x { |
4380 | Some(*n) |
4381 | } else { |
4382 | None |
4383 | } |
4384 | }) |
4385 | .max() |
4386 | .unwrap_or(0); |
4387 | let is_trailing_var_arg_set = self.is_trailing_var_arg_set(); |
4388 | let is_allow_hyphen_values_set = self.is_allow_hyphen_values_set(); |
4389 | let is_allow_negative_numbers_set = self.is_allow_negative_numbers_set(); |
4390 | for arg in self.args.args_mut() { |
4391 | if is_allow_hyphen_values_set && arg.is_takes_value_set() { |
4392 | arg.settings.set(ArgSettings::AllowHyphenValues); |
4393 | } |
4394 | if is_allow_negative_numbers_set && arg.is_takes_value_set() { |
4395 | arg.settings.set(ArgSettings::AllowNegativeNumbers); |
4396 | } |
4397 | if is_trailing_var_arg_set && arg.get_index() == Some(highest_idx) { |
4398 | arg.settings.set(ArgSettings::TrailingVarArg); |
4399 | } |
4400 | } |
4401 | } |
4402 | |
4403 | #[cfg (debug_assertions)] |
4404 | assert_app(self); |
4405 | self.settings.set(AppSettings::Built); |
4406 | } else { |
4407 | debug!("Command::_build: already built" ); |
4408 | } |
4409 | } |
4410 | |
4411 | pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> { |
4412 | use std::fmt::Write; |
4413 | |
4414 | let mut mid_string = String::from(" " ); |
4415 | #[cfg (feature = "usage" )] |
4416 | if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set() |
4417 | { |
4418 | let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) |
4419 | |
4420 | for s in &reqs { |
4421 | mid_string.push_str(&s.to_string()); |
4422 | mid_string.push(' ' ); |
4423 | } |
4424 | } |
4425 | let is_multicall_set = self.is_multicall_set(); |
4426 | |
4427 | let sc = some!(self.subcommands.iter_mut().find(|s| s.name == name)); |
4428 | |
4429 | // Display subcommand name, short and long in usage |
4430 | let mut sc_names = String::new(); |
4431 | sc_names.push_str(sc.name.as_str()); |
4432 | let mut flag_subcmd = false; |
4433 | if let Some(l) = sc.get_long_flag() { |
4434 | write!(sc_names, "|-- {l}" ).unwrap(); |
4435 | flag_subcmd = true; |
4436 | } |
4437 | if let Some(s) = sc.get_short_flag() { |
4438 | write!(sc_names, "|- {s}" ).unwrap(); |
4439 | flag_subcmd = true; |
4440 | } |
4441 | |
4442 | if flag_subcmd { |
4443 | sc_names = format!(" {{{sc_names}}}" ); |
4444 | } |
4445 | |
4446 | let usage_name = self |
4447 | .bin_name |
4448 | .as_ref() |
4449 | .map(|bin_name| format!(" {bin_name}{mid_string}{sc_names}" )) |
4450 | .unwrap_or(sc_names); |
4451 | sc.usage_name = Some(usage_name); |
4452 | |
4453 | // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by |
4454 | // a space |
4455 | let bin_name = format!( |
4456 | " {}{}{}" , |
4457 | self.bin_name.as_deref().unwrap_or_default(), |
4458 | if self.bin_name.is_some() { " " } else { "" }, |
4459 | &*sc.name |
4460 | ); |
4461 | debug!( |
4462 | "Command::_build_subcommand Setting bin_name of {} to {:?}" , |
4463 | sc.name, bin_name |
4464 | ); |
4465 | sc.bin_name = Some(bin_name); |
4466 | |
4467 | if sc.display_name.is_none() { |
4468 | let self_display_name = if is_multicall_set { |
4469 | self.display_name.as_deref().unwrap_or("" ) |
4470 | } else { |
4471 | self.display_name.as_deref().unwrap_or(&self.name) |
4472 | }; |
4473 | let display_name = format!( |
4474 | " {}{}{}" , |
4475 | self_display_name, |
4476 | if !self_display_name.is_empty() { |
4477 | "-" |
4478 | } else { |
4479 | "" |
4480 | }, |
4481 | &*sc.name |
4482 | ); |
4483 | debug!( |
4484 | "Command::_build_subcommand Setting display_name of {} to {:?}" , |
4485 | sc.name, display_name |
4486 | ); |
4487 | sc.display_name = Some(display_name); |
4488 | } |
4489 | |
4490 | // Ensure all args are built and ready to parse |
4491 | sc._build_self(false); |
4492 | |
4493 | Some(sc) |
4494 | } |
4495 | |
4496 | fn _build_bin_names_internal(&mut self) { |
4497 | debug!("Command::_build_bin_names" ); |
4498 | |
4499 | if !self.is_set(AppSettings::BinNameBuilt) { |
4500 | let mut mid_string = String::from(" " ); |
4501 | #[cfg (feature = "usage" )] |
4502 | if !self.is_subcommand_negates_reqs_set() |
4503 | && !self.is_args_conflicts_with_subcommands_set() |
4504 | { |
4505 | let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) |
4506 | |
4507 | for s in &reqs { |
4508 | mid_string.push_str(&s.to_string()); |
4509 | mid_string.push(' ' ); |
4510 | } |
4511 | } |
4512 | let is_multicall_set = self.is_multicall_set(); |
4513 | |
4514 | let self_bin_name = if is_multicall_set { |
4515 | self.bin_name.as_deref().unwrap_or("" ) |
4516 | } else { |
4517 | self.bin_name.as_deref().unwrap_or(&self.name) |
4518 | } |
4519 | .to_owned(); |
4520 | |
4521 | for sc in &mut self.subcommands { |
4522 | debug!("Command::_build_bin_names:iter: bin_name set..." ); |
4523 | |
4524 | if sc.usage_name.is_none() { |
4525 | use std::fmt::Write; |
4526 | // Display subcommand name, short and long in usage |
4527 | let mut sc_names = String::new(); |
4528 | sc_names.push_str(sc.name.as_str()); |
4529 | let mut flag_subcmd = false; |
4530 | if let Some(l) = sc.get_long_flag() { |
4531 | write!(sc_names, "|-- {l}" ).unwrap(); |
4532 | flag_subcmd = true; |
4533 | } |
4534 | if let Some(s) = sc.get_short_flag() { |
4535 | write!(sc_names, "|- {s}" ).unwrap(); |
4536 | flag_subcmd = true; |
4537 | } |
4538 | |
4539 | if flag_subcmd { |
4540 | sc_names = format!(" {{{sc_names}}}" ); |
4541 | } |
4542 | |
4543 | let usage_name = format!(" {self_bin_name}{mid_string}{sc_names}" ); |
4544 | debug!( |
4545 | "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}" , |
4546 | sc.name, usage_name |
4547 | ); |
4548 | sc.usage_name = Some(usage_name); |
4549 | } else { |
4550 | debug!( |
4551 | "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})" , |
4552 | sc.name, sc.usage_name |
4553 | ); |
4554 | } |
4555 | |
4556 | if sc.bin_name.is_none() { |
4557 | let bin_name = format!( |
4558 | " {}{}{}" , |
4559 | self_bin_name, |
4560 | if !self_bin_name.is_empty() { " " } else { "" }, |
4561 | &*sc.name |
4562 | ); |
4563 | debug!( |
4564 | "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}" , |
4565 | sc.name, bin_name |
4566 | ); |
4567 | sc.bin_name = Some(bin_name); |
4568 | } else { |
4569 | debug!( |
4570 | "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})" , |
4571 | sc.name, sc.bin_name |
4572 | ); |
4573 | } |
4574 | |
4575 | if sc.display_name.is_none() { |
4576 | let self_display_name = if is_multicall_set { |
4577 | self.display_name.as_deref().unwrap_or("" ) |
4578 | } else { |
4579 | self.display_name.as_deref().unwrap_or(&self.name) |
4580 | }; |
4581 | let display_name = format!( |
4582 | " {}{}{}" , |
4583 | self_display_name, |
4584 | if !self_display_name.is_empty() { |
4585 | "-" |
4586 | } else { |
4587 | "" |
4588 | }, |
4589 | &*sc.name |
4590 | ); |
4591 | debug!( |
4592 | "Command::_build_bin_names:iter: Setting display_name of {} to {:?}" , |
4593 | sc.name, display_name |
4594 | ); |
4595 | sc.display_name = Some(display_name); |
4596 | } else { |
4597 | debug!( |
4598 | "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})" , |
4599 | sc.name, sc.display_name |
4600 | ); |
4601 | } |
4602 | |
4603 | sc._build_bin_names_internal(); |
4604 | } |
4605 | self.set(AppSettings::BinNameBuilt); |
4606 | } else { |
4607 | debug!("Command::_build_bin_names: already built" ); |
4608 | } |
4609 | } |
4610 | |
4611 | pub(crate) fn _panic_on_missing_help(&self, help_required_globally: bool) { |
4612 | if self.is_set(AppSettings::HelpExpected) || help_required_globally { |
4613 | let args_missing_help: Vec<Id> = self |
4614 | .args |
4615 | .args() |
4616 | .filter(|arg| arg.get_help().is_none() && arg.get_long_help().is_none()) |
4617 | .map(|arg| arg.get_id().clone()) |
4618 | .collect(); |
4619 | |
4620 | debug_assert!(args_missing_help.is_empty(), |
4621 | "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: {}" , |
4622 | self.name, |
4623 | args_missing_help.join(", " ) |
4624 | ); |
4625 | } |
4626 | |
4627 | for sub_app in &self.subcommands { |
4628 | sub_app._panic_on_missing_help(help_required_globally); |
4629 | } |
4630 | } |
4631 | |
4632 | #[cfg (debug_assertions)] |
4633 | pub(crate) fn two_args_of<F>(&self, condition: F) -> Option<(&Arg, &Arg)> |
4634 | where |
4635 | F: Fn(&Arg) -> bool, |
4636 | { |
4637 | two_elements_of(self.args.args().filter(|a: &&Arg| condition(a))) |
4638 | } |
4639 | |
4640 | // just in case |
4641 | #[allow (unused)] |
4642 | fn two_groups_of<F>(&self, condition: F) -> Option<(&ArgGroup, &ArgGroup)> |
4643 | where |
4644 | F: Fn(&ArgGroup) -> bool, |
4645 | { |
4646 | two_elements_of(self.groups.iter().filter(|a| condition(a))) |
4647 | } |
4648 | |
4649 | /// Propagate global args |
4650 | pub(crate) fn _propagate_global_args(&mut self) { |
4651 | debug!("Command::_propagate_global_args:{}" , self.name); |
4652 | |
4653 | let autogenerated_help_subcommand = !self.is_disable_help_subcommand_set(); |
4654 | |
4655 | for sc in &mut self.subcommands { |
4656 | if sc.get_name() == "help" && autogenerated_help_subcommand { |
4657 | // Avoid propagating args to the autogenerated help subtrees used in completion. |
4658 | // This prevents args from showing up during help completions like |
4659 | // `myapp help subcmd <TAB>`, which should only suggest subcommands and not args, |
4660 | // while still allowing args to show up properly on the generated help message. |
4661 | continue; |
4662 | } |
4663 | |
4664 | for a in self.args.args().filter(|a| a.is_global_set()) { |
4665 | if sc.find(&a.id).is_some() { |
4666 | debug!( |
4667 | "Command::_propagate skipping {:?} to {}, already exists" , |
4668 | a.id, |
4669 | sc.get_name(), |
4670 | ); |
4671 | continue; |
4672 | } |
4673 | |
4674 | debug!( |
4675 | "Command::_propagate pushing {:?} to {}" , |
4676 | a.id, |
4677 | sc.get_name(), |
4678 | ); |
4679 | sc.args.push(a.clone()); |
4680 | } |
4681 | } |
4682 | } |
4683 | |
4684 | /// Propagate settings |
4685 | pub(crate) fn _propagate(&mut self) { |
4686 | debug!("Command::_propagate:{}" , self.name); |
4687 | let mut subcommands = std::mem::take(&mut self.subcommands); |
4688 | for sc in &mut subcommands { |
4689 | self._propagate_subcommand(sc); |
4690 | } |
4691 | self.subcommands = subcommands; |
4692 | } |
4693 | |
4694 | fn _propagate_subcommand(&self, sc: &mut Self) { |
4695 | // We have to create a new scope in order to tell rustc the borrow of `sc` is |
4696 | // done and to recursively call this method |
4697 | { |
4698 | if self.settings.is_set(AppSettings::PropagateVersion) { |
4699 | if let Some(version) = self.version.as_ref() { |
4700 | sc.version.get_or_insert_with(|| version.clone()); |
4701 | } |
4702 | if let Some(long_version) = self.long_version.as_ref() { |
4703 | sc.long_version.get_or_insert_with(|| long_version.clone()); |
4704 | } |
4705 | } |
4706 | |
4707 | sc.settings = sc.settings | self.g_settings; |
4708 | sc.g_settings = sc.g_settings | self.g_settings; |
4709 | sc.app_ext.update(&self.app_ext); |
4710 | } |
4711 | } |
4712 | |
4713 | pub(crate) fn _check_help_and_version(&mut self, expand_help_tree: bool) { |
4714 | debug!( |
4715 | "Command::_check_help_and_version:{} expand_help_tree={}" , |
4716 | self.name, expand_help_tree |
4717 | ); |
4718 | |
4719 | self.long_help_exists = self.long_help_exists_(); |
4720 | |
4721 | if !self.is_disable_help_flag_set() { |
4722 | debug!("Command::_check_help_and_version: Building default --help" ); |
4723 | let mut arg = Arg::new(Id::HELP) |
4724 | .short('h' ) |
4725 | .long("help" ) |
4726 | .action(ArgAction::Help); |
4727 | if self.long_help_exists { |
4728 | arg = arg |
4729 | .help("Print help (see more with '--help')" ) |
4730 | .long_help("Print help (see a summary with '-h')" ); |
4731 | } else { |
4732 | arg = arg.help("Print help" ); |
4733 | } |
4734 | // Avoiding `arg_internal` to not be sensitive to `next_help_heading` / |
4735 | // `next_display_order` |
4736 | self.args.push(arg); |
4737 | } |
4738 | if !self.is_disable_version_flag_set() { |
4739 | debug!("Command::_check_help_and_version: Building default --version" ); |
4740 | let arg = Arg::new(Id::VERSION) |
4741 | .short('V' ) |
4742 | .long("version" ) |
4743 | .action(ArgAction::Version) |
4744 | .help("Print version" ); |
4745 | // Avoiding `arg_internal` to not be sensitive to `next_help_heading` / |
4746 | // `next_display_order` |
4747 | self.args.push(arg); |
4748 | } |
4749 | |
4750 | if !self.is_set(AppSettings::DisableHelpSubcommand) { |
4751 | debug!("Command::_check_help_and_version: Building help subcommand" ); |
4752 | let help_about = "Print this message or the help of the given subcommand(s)" ; |
4753 | |
4754 | let mut help_subcmd = if expand_help_tree { |
4755 | // Slow code path to recursively clone all other subcommand subtrees under help |
4756 | let help_subcmd = Command::new("help" ) |
4757 | .about(help_about) |
4758 | .global_setting(AppSettings::DisableHelpSubcommand) |
4759 | .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help)); |
4760 | |
4761 | let mut help_help_subcmd = Command::new("help" ).about(help_about); |
4762 | help_help_subcmd.version = None; |
4763 | help_help_subcmd.long_version = None; |
4764 | help_help_subcmd = help_help_subcmd |
4765 | .setting(AppSettings::DisableHelpFlag) |
4766 | .setting(AppSettings::DisableVersionFlag); |
4767 | |
4768 | help_subcmd.subcommand(help_help_subcmd) |
4769 | } else { |
4770 | Command::new("help" ).about(help_about).arg( |
4771 | Arg::new("subcommand" ) |
4772 | .action(ArgAction::Append) |
4773 | .num_args(..) |
4774 | .value_name("COMMAND" ) |
4775 | .help("Print help for the subcommand(s)" ), |
4776 | ) |
4777 | }; |
4778 | self._propagate_subcommand(&mut help_subcmd); |
4779 | |
4780 | // The parser acts like this is set, so let's set it so we don't falsely |
4781 | // advertise it to the user |
4782 | help_subcmd.version = None; |
4783 | help_subcmd.long_version = None; |
4784 | help_subcmd = help_subcmd |
4785 | .setting(AppSettings::DisableHelpFlag) |
4786 | .setting(AppSettings::DisableVersionFlag) |
4787 | .unset_global_setting(AppSettings::PropagateVersion); |
4788 | |
4789 | self.subcommands.push(help_subcmd); |
4790 | } |
4791 | } |
4792 | |
4793 | fn _copy_subtree_for_help(&self) -> Command { |
4794 | let mut cmd = Command::new(self.name.clone()) |
4795 | .hide(self.is_hide_set()) |
4796 | .global_setting(AppSettings::DisableHelpFlag) |
4797 | .global_setting(AppSettings::DisableVersionFlag) |
4798 | .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help)); |
4799 | if self.get_about().is_some() { |
4800 | cmd = cmd.about(self.get_about().unwrap().clone()); |
4801 | } |
4802 | cmd |
4803 | } |
4804 | |
4805 | pub(crate) fn _render_version(&self, use_long: bool) -> String { |
4806 | debug!("Command::_render_version" ); |
4807 | |
4808 | let ver = if use_long { |
4809 | self.long_version |
4810 | .as_deref() |
4811 | .or(self.version.as_deref()) |
4812 | .unwrap_or_default() |
4813 | } else { |
4814 | self.version |
4815 | .as_deref() |
4816 | .or(self.long_version.as_deref()) |
4817 | .unwrap_or_default() |
4818 | }; |
4819 | let display_name = self.get_display_name().unwrap_or_else(|| self.get_name()); |
4820 | format!(" {display_name} {ver}\n" ) |
4821 | } |
4822 | |
4823 | pub(crate) fn format_group(&self, g: &Id) -> StyledStr { |
4824 | use std::fmt::Write as _; |
4825 | |
4826 | let g_string = self |
4827 | .unroll_args_in_group(g) |
4828 | .iter() |
4829 | .filter_map(|x| self.find(x)) |
4830 | .map(|x| { |
4831 | if x.is_positional() { |
4832 | // Print val_name for positional arguments. e.g. <file_name> |
4833 | x.name_no_brackets() |
4834 | } else { |
4835 | // Print usage string for flags arguments, e.g. <--help> |
4836 | x.to_string() |
4837 | } |
4838 | }) |
4839 | .collect::<Vec<_>>() |
4840 | .join("|" ); |
4841 | let placeholder = self.get_styles().get_placeholder(); |
4842 | let mut styled = StyledStr::new(); |
4843 | write!(&mut styled, " {placeholder}< {g_string}> {placeholder:#}" ).unwrap(); |
4844 | styled |
4845 | } |
4846 | } |
4847 | |
4848 | /// A workaround: |
4849 | /// <https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999> |
4850 | pub(crate) trait Captures<'a> {} |
4851 | impl<T> Captures<'_> for T {} |
4852 | |
4853 | // Internal Query Methods |
4854 | impl Command { |
4855 | /// Iterate through the *flags* & *options* arguments. |
4856 | #[cfg (any(feature = "usage" , feature = "help" ))] |
4857 | pub(crate) fn get_non_positionals(&self) -> impl Iterator<Item = &Arg> { |
4858 | self.get_arguments().filter(|a| !a.is_positional()) |
4859 | } |
4860 | |
4861 | pub(crate) fn find(&self, arg_id: &Id) -> Option<&Arg> { |
4862 | self.args.args().find(|a| a.get_id() == arg_id) |
4863 | } |
4864 | |
4865 | #[inline ] |
4866 | pub(crate) fn contains_short(&self, s: char) -> bool { |
4867 | debug_assert!( |
4868 | self.is_set(AppSettings::Built), |
4869 | "If Command::_build hasn't been called, manually search through Arg shorts" |
4870 | ); |
4871 | |
4872 | self.args.contains(s) |
4873 | } |
4874 | |
4875 | #[inline ] |
4876 | pub(crate) fn set(&mut self, s: AppSettings) { |
4877 | self.settings.set(s); |
4878 | } |
4879 | |
4880 | #[inline ] |
4881 | pub(crate) fn has_positionals(&self) -> bool { |
4882 | self.get_positionals().next().is_some() |
4883 | } |
4884 | |
4885 | #[cfg (any(feature = "usage" , feature = "help" ))] |
4886 | pub(crate) fn has_visible_subcommands(&self) -> bool { |
4887 | self.subcommands |
4888 | .iter() |
4889 | .any(|sc| sc.name != "help" && !sc.is_set(AppSettings::Hidden)) |
4890 | } |
4891 | |
4892 | /// Check if this subcommand can be referred to as `name`. In other words, |
4893 | /// check if `name` is the name of this subcommand or is one of its aliases. |
4894 | #[inline ] |
4895 | pub(crate) fn aliases_to(&self, name: impl AsRef<std::ffi::OsStr>) -> bool { |
4896 | let name = name.as_ref(); |
4897 | self.get_name() == name || self.get_all_aliases().any(|alias| alias == name) |
4898 | } |
4899 | |
4900 | /// Check if this subcommand can be referred to as `name`. In other words, |
4901 | /// check if `name` is the name of this short flag subcommand or is one of its short flag aliases. |
4902 | #[inline ] |
4903 | pub(crate) fn short_flag_aliases_to(&self, flag: char) -> bool { |
4904 | Some(flag) == self.short_flag |
4905 | || self.get_all_short_flag_aliases().any(|alias| flag == alias) |
4906 | } |
4907 | |
4908 | /// Check if this subcommand can be referred to as `name`. In other words, |
4909 | /// check if `name` is the name of this long flag subcommand or is one of its long flag aliases. |
4910 | #[inline ] |
4911 | pub(crate) fn long_flag_aliases_to(&self, flag: &str) -> bool { |
4912 | match self.long_flag.as_ref() { |
4913 | Some(long_flag) => { |
4914 | long_flag == flag || self.get_all_long_flag_aliases().any(|alias| alias == flag) |
4915 | } |
4916 | None => self.get_all_long_flag_aliases().any(|alias| alias == flag), |
4917 | } |
4918 | } |
4919 | |
4920 | #[cfg (debug_assertions)] |
4921 | pub(crate) fn id_exists(&self, id: &Id) -> bool { |
4922 | self.args.args().any(|x| x.get_id() == id) || self.groups.iter().any(|x| x.id == *id) |
4923 | } |
4924 | |
4925 | /// Iterate through the groups this arg is member of. |
4926 | pub(crate) fn groups_for_arg<'a>(&'a self, arg: &Id) -> impl Iterator<Item = Id> + 'a { |
4927 | debug!("Command::groups_for_arg: id={arg:?}" ); |
4928 | let arg = arg.clone(); |
4929 | self.groups |
4930 | .iter() |
4931 | .filter(move |grp| grp.args.iter().any(|a| a == &arg)) |
4932 | .map(|grp| grp.id.clone()) |
4933 | } |
4934 | |
4935 | pub(crate) fn find_group(&self, group_id: &Id) -> Option<&ArgGroup> { |
4936 | self.groups.iter().find(|g| g.id == *group_id) |
4937 | } |
4938 | |
4939 | /// Iterate through all the names of all subcommands (not recursively), including aliases. |
4940 | /// Used for suggestions. |
4941 | pub(crate) fn all_subcommand_names(&self) -> impl Iterator<Item = &str> + Captures<'_> { |
4942 | self.get_subcommands().flat_map(|sc| { |
4943 | let name = sc.get_name(); |
4944 | let aliases = sc.get_all_aliases(); |
4945 | std::iter::once(name).chain(aliases) |
4946 | }) |
4947 | } |
4948 | |
4949 | pub(crate) fn required_graph(&self) -> ChildGraph<Id> { |
4950 | let mut reqs = ChildGraph::with_capacity(5); |
4951 | for a in self.args.args().filter(|a| a.is_required_set()) { |
4952 | reqs.insert(a.get_id().clone()); |
4953 | } |
4954 | for group in &self.groups { |
4955 | if group.required { |
4956 | let idx = reqs.insert(group.id.clone()); |
4957 | for a in &group.requires { |
4958 | reqs.insert_child(idx, a.clone()); |
4959 | } |
4960 | } |
4961 | } |
4962 | |
4963 | reqs |
4964 | } |
4965 | |
4966 | pub(crate) fn unroll_args_in_group(&self, group: &Id) -> Vec<Id> { |
4967 | debug!("Command::unroll_args_in_group: group={group:?}" ); |
4968 | let mut g_vec = vec![group]; |
4969 | let mut args = vec![]; |
4970 | |
4971 | while let Some(g) = g_vec.pop() { |
4972 | for n in self |
4973 | .groups |
4974 | .iter() |
4975 | .find(|grp| grp.id == *g) |
4976 | .expect(INTERNAL_ERROR_MSG) |
4977 | .args |
4978 | .iter() |
4979 | { |
4980 | debug!("Command::unroll_args_in_group:iter: entity={n:?}" ); |
4981 | if !args.contains(n) { |
4982 | if self.find(n).is_some() { |
4983 | debug!("Command::unroll_args_in_group:iter: this is an arg" ); |
4984 | args.push(n.clone()); |
4985 | } else { |
4986 | debug!("Command::unroll_args_in_group:iter: this is a group" ); |
4987 | g_vec.push(n); |
4988 | } |
4989 | } |
4990 | } |
4991 | } |
4992 | |
4993 | args |
4994 | } |
4995 | |
4996 | pub(crate) fn unroll_arg_requires<F>(&self, func: F, arg: &Id) -> Vec<Id> |
4997 | where |
4998 | F: Fn(&(ArgPredicate, Id)) -> Option<Id>, |
4999 | { |
5000 | let mut processed = vec![]; |
5001 | let mut r_vec = vec![arg]; |
5002 | let mut args = vec![]; |
5003 | |
5004 | while let Some(a) = r_vec.pop() { |
5005 | if processed.contains(&a) { |
5006 | continue; |
5007 | } |
5008 | |
5009 | processed.push(a); |
5010 | |
5011 | if let Some(arg) = self.find(a) { |
5012 | for r in arg.requires.iter().filter_map(&func) { |
5013 | if let Some(req) = self.find(&r) { |
5014 | if !req.requires.is_empty() { |
5015 | r_vec.push(req.get_id()); |
5016 | } |
5017 | } |
5018 | args.push(r); |
5019 | } |
5020 | } |
5021 | } |
5022 | |
5023 | args |
5024 | } |
5025 | |
5026 | /// Find a flag subcommand name by short flag or an alias |
5027 | pub(crate) fn find_short_subcmd(&self, c: char) -> Option<&str> { |
5028 | self.get_subcommands() |
5029 | .find(|sc| sc.short_flag_aliases_to(c)) |
5030 | .map(|sc| sc.get_name()) |
5031 | } |
5032 | |
5033 | /// Find a flag subcommand name by long flag or an alias |
5034 | pub(crate) fn find_long_subcmd(&self, long: &str) -> Option<&str> { |
5035 | self.get_subcommands() |
5036 | .find(|sc| sc.long_flag_aliases_to(long)) |
5037 | .map(|sc| sc.get_name()) |
5038 | } |
5039 | |
5040 | pub(crate) fn write_help_err(&self, mut use_long: bool) -> StyledStr { |
5041 | debug!( |
5042 | "Command::write_help_err: {}, use_long={:?}" , |
5043 | self.get_display_name().unwrap_or_else(|| self.get_name()), |
5044 | use_long && self.long_help_exists(), |
5045 | ); |
5046 | |
5047 | use_long = use_long && self.long_help_exists(); |
5048 | let usage = Usage::new(self); |
5049 | |
5050 | let mut styled = StyledStr::new(); |
5051 | write_help(&mut styled, self, &usage, use_long); |
5052 | |
5053 | styled |
5054 | } |
5055 | |
5056 | pub(crate) fn write_version_err(&self, use_long: bool) -> StyledStr { |
5057 | let msg = self._render_version(use_long); |
5058 | StyledStr::from(msg) |
5059 | } |
5060 | |
5061 | pub(crate) fn long_help_exists(&self) -> bool { |
5062 | debug!("Command::long_help_exists: {}" , self.long_help_exists); |
5063 | self.long_help_exists |
5064 | } |
5065 | |
5066 | fn long_help_exists_(&self) -> bool { |
5067 | debug!("Command::long_help_exists" ); |
5068 | // In this case, both must be checked. This allows the retention of |
5069 | // original formatting, but also ensures that the actual -h or --help |
5070 | // specified by the user is sent through. If hide_short_help is not included, |
5071 | // then items specified with hidden_short_help will also be hidden. |
5072 | let should_long = |v: &Arg| { |
5073 | !v.is_hide_set() |
5074 | && (v.get_long_help().is_some() |
5075 | || v.is_hide_long_help_set() |
5076 | || v.is_hide_short_help_set() |
5077 | || (!v.is_hide_possible_values_set() |
5078 | && v.get_possible_values() |
5079 | .iter() |
5080 | .any(PossibleValue::should_show_help))) |
5081 | }; |
5082 | |
5083 | // Subcommands aren't checked because we prefer short help for them, deferring to |
5084 | // `cmd subcmd --help` for more. |
5085 | self.get_long_about().is_some() |
5086 | || self.get_before_long_help().is_some() |
5087 | || self.get_after_long_help().is_some() |
5088 | || self.get_arguments().any(should_long) |
5089 | } |
5090 | |
5091 | // Should we color the help? |
5092 | pub(crate) fn color_help(&self) -> ColorChoice { |
5093 | #[cfg (feature = "color" )] |
5094 | if self.is_disable_colored_help_set() { |
5095 | return ColorChoice::Never; |
5096 | } |
5097 | |
5098 | self.get_color() |
5099 | } |
5100 | } |
5101 | |
5102 | impl Default for Command { |
5103 | fn default() -> Self { |
5104 | Self { |
5105 | name: Default::default(), |
5106 | long_flag: Default::default(), |
5107 | short_flag: Default::default(), |
5108 | display_name: Default::default(), |
5109 | bin_name: Default::default(), |
5110 | author: Default::default(), |
5111 | version: Default::default(), |
5112 | long_version: Default::default(), |
5113 | about: Default::default(), |
5114 | long_about: Default::default(), |
5115 | before_help: Default::default(), |
5116 | before_long_help: Default::default(), |
5117 | after_help: Default::default(), |
5118 | after_long_help: Default::default(), |
5119 | aliases: Default::default(), |
5120 | short_flag_aliases: Default::default(), |
5121 | long_flag_aliases: Default::default(), |
5122 | usage_str: Default::default(), |
5123 | usage_name: Default::default(), |
5124 | help_str: Default::default(), |
5125 | disp_ord: Default::default(), |
5126 | #[cfg (feature = "help" )] |
5127 | template: Default::default(), |
5128 | settings: Default::default(), |
5129 | g_settings: Default::default(), |
5130 | args: Default::default(), |
5131 | subcommands: Default::default(), |
5132 | groups: Default::default(), |
5133 | current_help_heading: Default::default(), |
5134 | current_disp_ord: Some(0), |
5135 | subcommand_value_name: Default::default(), |
5136 | subcommand_heading: Default::default(), |
5137 | external_value_parser: Default::default(), |
5138 | long_help_exists: false, |
5139 | deferred: None, |
5140 | #[cfg (feature = "unstable-ext" )] |
5141 | ext: Default::default(), |
5142 | app_ext: Default::default(), |
5143 | } |
5144 | } |
5145 | } |
5146 | |
5147 | impl Index<&'_ Id> for Command { |
5148 | type Output = Arg; |
5149 | |
5150 | fn index(&self, key: &Id) -> &Self::Output { |
5151 | self.find(arg_id:key).expect(INTERNAL_ERROR_MSG) |
5152 | } |
5153 | } |
5154 | |
5155 | impl From<&'_ Command> for Command { |
5156 | fn from(cmd: &'_ Command) -> Self { |
5157 | cmd.clone() |
5158 | } |
5159 | } |
5160 | |
5161 | impl fmt::Display for Command { |
5162 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
5163 | write!(f, " {}" , self.name) |
5164 | } |
5165 | } |
5166 | |
5167 | /// User-provided data that can be attached to an [`Arg`] |
5168 | #[cfg (feature = "unstable-ext" )] |
5169 | pub trait CommandExt: Extension {} |
5170 | |
5171 | #[allow (dead_code)] // atm dependent on features enabled |
5172 | pub(crate) trait AppExt: Extension {} |
5173 | |
5174 | #[allow (dead_code)] // atm dependent on features enabled |
5175 | #[derive (Default, Copy, Clone, Debug)] |
5176 | struct TermWidth(usize); |
5177 | |
5178 | impl AppExt for TermWidth {} |
5179 | |
5180 | #[allow (dead_code)] // atm dependent on features enabled |
5181 | #[derive (Default, Copy, Clone, Debug)] |
5182 | struct MaxTermWidth(usize); |
5183 | |
5184 | impl AppExt for MaxTermWidth {} |
5185 | |
5186 | fn two_elements_of<I, T>(mut iter: I) -> Option<(T, T)> |
5187 | where |
5188 | I: Iterator<Item = T>, |
5189 | { |
5190 | let first: Option = iter.next(); |
5191 | let second: Option = iter.next(); |
5192 | |
5193 | match (first, second) { |
5194 | (Some(first: T), Some(second: T)) => Some((first, second)), |
5195 | _ => None, |
5196 | } |
5197 | } |
5198 | |
5199 | #[test ] |
5200 | fn check_auto_traits() { |
5201 | static_assertions::assert_impl_all!(Command: Send, Sync, Unpin); |
5202 | } |
5203 | |