3 use std
::collections
::HashMap
;
4 use std
::ffi
::{OsStr, OsString}
;
13 /// Used to get information about the arguments that where supplied to the program at runtime by
14 /// the user. New instances of this struct are obtained by using the [`App::get_matches`] family of
20 /// # use clap::{App, Arg};
21 /// let matches = App::new("MyApp")
22 /// .arg(Arg::with_name("out")
25 /// .takes_value(true))
26 /// .arg(Arg::with_name("debug")
29 /// .arg(Arg::with_name("cfg")
31 /// .takes_value(true))
32 /// .get_matches(); // builds the instance of ArgMatches
34 /// // to get information about the "cfg" argument we created, such as the value supplied we use
35 /// // various ArgMatches methods, such as ArgMatches::value_of
36 /// if let Some(c) = matches.value_of("cfg") {
37 /// println!("Value for -c: {}", c);
40 /// // The ArgMatches::value_of method returns an Option because the user may not have supplied
41 /// // that argument at runtime. But if we specified that the argument was "required" as we did
42 /// // with the "out" argument, we can safely unwrap because `clap` verifies that was actually
43 /// // used at runtime.
44 /// println!("Value for --output: {}", matches.value_of("out").unwrap());
46 /// // You can check the presence of an argument
47 /// if matches.is_present("out") {
48 /// // Another way to check if an argument was present, or if it occurred multiple times is to
49 /// // use occurrences_of() which returns 0 if an argument isn't found at runtime, or the
50 /// // number of times that it occurred, if it was. To allow an argument to appear more than
51 /// // once, you must use the .multiple(true) method, otherwise it will only return 1 or 0.
52 /// if matches.occurrences_of("debug") > 2 {
53 /// println!("Debug mode is REALLY on, don't be crazy");
55 /// println!("Debug mode kind of on");
59 /// [`App::get_matches`]: ./struct.App.html#method.get_matches
60 #[derive(Debug, Clone)]
61 pub struct ArgMatches
<'a
> {
62 #[doc(hidden)] pub args: HashMap<&'a str, MatchedArg>,
63 #[doc(hidden)] pub subcommand: Option<Box<SubCommand<'a>>>,
64 #[doc(hidden)] pub usage: Option<String>,
67 impl<'a
> Default
for ArgMatches
<'a
> {
68 fn default() -> Self {
77 impl<'a
> ArgMatches
<'a
> {
79 pub fn new() -> Self {
85 /// Gets the value of a specific [option] or [positional] argument (i.e. an argument that takes
86 /// an additional value at runtime). If the option wasn't present at runtime
87 /// it returns `None`.
89 /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
90 /// prefer [`ArgMatches::values_of`] as `ArgMatches::value_of` will only return the *first*
95 /// This method will [`panic!`] if the value contains invalid UTF-8 code points.
100 /// # use clap::{App, Arg};
101 /// let m = App::new("myapp")
102 /// .arg(Arg::with_name("output")
103 /// .takes_value(true))
104 /// .get_matches_from(vec!["myapp", "something"]);
106 /// assert_eq!(m.value_of("output"), Some("something"));
108 /// [option]: ./struct.Arg.html#method.takes_value
109 /// [positional]: ./struct.Arg.html#method.index
110 /// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of
111 /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html
112 pub fn value_of
<S
: AsRef
<str>>(&self, name
: S
) -> Option
<&str> {
113 if let Some(arg
) = self.args
.get(name
.as_ref()) {
114 if let Some(v
) = arg
.vals
.get(0) {
115 return Some(v
.to_str().expect(INVALID_UTF8
));
121 /// Gets the lossy value of a specific argument. If the argument wasn't present at runtime
122 /// it returns `None`. A lossy value is one which contains invalid UTF-8 code points, those
123 /// invalid points will be replaced with `\u{FFFD}`
125 /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
126 /// prefer [`Arg::values_of_lossy`] as `value_of_lossy()` will only return the *first* value.
130 #[cfg_attr(not(unix), doc = " ```ignore")]
131 #[cfg_attr(unix, doc = " ```")]
132 /// # use clap::{App, Arg};
133 /// use std::ffi::OsString;
134 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
136 /// let m = App::new("utf8")
137 /// .arg(Arg::from_usage("<arg> 'some arg'"))
138 /// .get_matches_from(vec![OsString::from("myprog"),
140 /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
141 /// assert_eq!(&*m.value_of_lossy("arg").unwrap(), "Hi \u{FFFD}!");
143 /// [`Arg::values_of_lossy`]: ./struct.ArgMatches.html#method.values_of_lossy
144 pub fn value_of_lossy
<S
: AsRef
<str>>(&'a
self, name
: S
) -> Option
<Cow
<'a
, str>> {
145 if let Some(arg
) = self.args
.get(name
.as_ref()) {
146 if let Some(v
) = arg
.vals
.get(0) {
147 return Some(v
.to_string_lossy());
153 /// Gets the OS version of a string value of a specific argument. If the option wasn't present
154 /// at runtime it returns `None`. An OS value on Unix-like systems is any series of bytes,
155 /// regardless of whether or not they contain valid UTF-8 code points. Since [`String`]s in
156 /// Rust are guaranteed to be valid UTF-8, a valid filename on a Unix system as an argument
157 /// value may contain invalid UTF-8 code points.
159 /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
160 /// prefer [`ArgMatches::values_of_os`] as `Arg::value_of_os` will only return the *first*
165 #[cfg_attr(not(unix), doc = " ```ignore")]
166 #[cfg_attr(unix, doc = " ```")]
167 /// # use clap::{App, Arg};
168 /// use std::ffi::OsString;
169 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
171 /// let m = App::new("utf8")
172 /// .arg(Arg::from_usage("<arg> 'some arg'"))
173 /// .get_matches_from(vec![OsString::from("myprog"),
175 /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
176 /// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']);
178 /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
179 /// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os
180 pub fn value_of_os
<S
: AsRef
<str>>(&self, name
: S
) -> Option
<&OsStr
> {
183 .and_then(|arg
| arg
.vals
.get(0).map(|v
| v
.as_os_str()))
186 /// Gets a [`Values`] struct which implements [`Iterator`] for values of a specific argument
187 /// (i.e. an argument that takes multiple values at runtime). If the option wasn't present at
188 /// runtime it returns `None`
192 /// This method will panic if any of the values contain invalid UTF-8 code points.
197 /// # use clap::{App, Arg};
198 /// let m = App::new("myprog")
199 /// .arg(Arg::with_name("output")
202 /// .takes_value(true))
203 /// .get_matches_from(vec![
204 /// "myprog", "-o", "val1", "val2", "val3"
206 /// let vals: Vec<&str> = m.values_of("output").unwrap().collect();
207 /// assert_eq!(vals, ["val1", "val2", "val3"]);
209 /// [`Values`]: ./struct.Values.html
210 /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
211 pub fn values_of
<S
: AsRef
<str>>(&'a
self, name
: S
) -> Option
<Values
<'a
>> {
212 if let Some(arg
) = self.args
.get(name
.as_ref()) {
213 fn to_str_slice(o
: &OsString
) -> &str { o.to_str().expect(INVALID_UTF8) }
214 let to_str_slice
: fn(&OsString
) -> &str = to_str_slice
; // coerce to fn pointer
216 iter
: arg
.vals
.iter().map(to_str_slice
),
222 /// Gets the lossy values of a specific argument. If the option wasn't present at runtime
223 /// it returns `None`. A lossy value is one where if it contains invalid UTF-8 code points,
224 /// those invalid points will be replaced with `\u{FFFD}`
228 #[cfg_attr(not(unix), doc = " ```ignore")]
229 #[cfg_attr(unix, doc = " ```")]
230 /// # use clap::{App, Arg};
231 /// use std::ffi::OsString;
232 /// use std::os::unix::ffi::OsStringExt;
234 /// let m = App::new("utf8")
235 /// .arg(Arg::from_usage("<arg>... 'some arg'"))
236 /// .get_matches_from(vec![OsString::from("myprog"),
238 /// OsString::from_vec(vec![b'H', b'i']),
240 /// OsString::from_vec(vec![0xe9, b'!'])]);
241 /// let mut itr = m.values_of_lossy("arg").unwrap().into_iter();
242 /// assert_eq!(&itr.next().unwrap()[..], "Hi");
243 /// assert_eq!(&itr.next().unwrap()[..], "\u{FFFD}!");
244 /// assert_eq!(itr.next(), None);
246 pub fn values_of_lossy
<S
: AsRef
<str>>(&'a
self, name
: S
) -> Option
<Vec
<String
>> {
247 if let Some(arg
) = self.args
.get(name
.as_ref()) {
251 .map(|v
| v
.to_string_lossy().into_owned())
258 /// Gets a [`OsValues`] struct which is implements [`Iterator`] for [`OsString`] values of a
259 /// specific argument. If the option wasn't present at runtime it returns `None`. An OS value
260 /// on Unix-like systems is any series of bytes, regardless of whether or not they contain
261 /// valid UTF-8 code points. Since [`String`]s in Rust are guaranteed to be valid UTF-8, a valid
262 /// filename as an argument value on Linux (for example) may contain invalid UTF-8 code points.
266 #[cfg_attr(not(unix), doc = " ```ignore")]
267 #[cfg_attr(unix, doc = " ```")]
268 /// # use clap::{App, Arg};
269 /// use std::ffi::{OsStr,OsString};
270 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
272 /// let m = App::new("utf8")
273 /// .arg(Arg::from_usage("<arg>... 'some arg'"))
274 /// .get_matches_from(vec![OsString::from("myprog"),
276 /// OsString::from_vec(vec![b'H', b'i']),
278 /// OsString::from_vec(vec![0xe9, b'!'])]);
280 /// let mut itr = m.values_of_os("arg").unwrap().into_iter();
281 /// assert_eq!(itr.next(), Some(OsStr::new("Hi")));
282 /// assert_eq!(itr.next(), Some(OsStr::from_bytes(&[0xe9, b'!'])));
283 /// assert_eq!(itr.next(), None);
285 /// [`OsValues`]: ./struct.OsValues.html
286 /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
287 /// [`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html
288 /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
289 pub fn values_of_os
<S
: AsRef
<str>>(&'a
self, name
: S
) -> Option
<OsValues
<'a
>> {
290 fn to_str_slice(o
: &OsString
) -> &OsStr { &*o }
291 let to_str_slice
: fn(&'a OsString
) -> &'a OsStr
= to_str_slice
; // coerce to fn pointer
292 if let Some(arg
) = self.args
.get(name
.as_ref()) {
293 return Some(OsValues
{
294 iter
: arg
.vals
.iter().map(to_str_slice
),
300 /// Returns `true` if an argument was present at runtime, otherwise `false`.
305 /// # use clap::{App, Arg};
306 /// let m = App::new("myprog")
307 /// .arg(Arg::with_name("debug")
309 /// .get_matches_from(vec![
313 /// assert!(m.is_present("debug"));
315 pub fn is_present
<S
: AsRef
<str>>(&self, name
: S
) -> bool
{
316 if let Some(ref sc
) = self.subcommand
{
317 if sc
.name
== name
.as_ref() {
321 self.args
.contains_key(name
.as_ref())
324 /// Returns the number of times an argument was used at runtime. If an argument isn't present
325 /// it will return `0`.
327 /// **NOTE:** This returns the number of times the argument was used, *not* the number of
328 /// values. For example, `-o val1 val2 val3 -o val4` would return `2` (2 occurrences, but 4
334 /// # use clap::{App, Arg};
335 /// let m = App::new("myprog")
336 /// .arg(Arg::with_name("debug")
339 /// .get_matches_from(vec![
340 /// "myprog", "-d", "-d", "-d"
343 /// assert_eq!(m.occurrences_of("debug"), 3);
346 /// This next example shows that counts actual uses of the argument, not just `-`'s
349 /// # use clap::{App, Arg};
350 /// let m = App::new("myprog")
351 /// .arg(Arg::with_name("debug")
354 /// .arg(Arg::with_name("flag")
356 /// .get_matches_from(vec![
357 /// "myprog", "-ddfd"
360 /// assert_eq!(m.occurrences_of("debug"), 3);
361 /// assert_eq!(m.occurrences_of("flag"), 1);
363 pub fn occurrences_of
<S
: AsRef
<str>>(&self, name
: S
) -> u64 {
364 self.args
.get(name
.as_ref()).map_or(0, |a
| a
.occurs
)
367 /// Gets the starting index of the argument in respect to all other arguments. Indices are
368 /// similar to argv indices, but are not exactly 1:1.
370 /// For flags (i.e. those arguments which don't have an associated value), indices refer
371 /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices
372 /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the
373 /// index for `val` would be recorded. This is by design.
375 /// Besides the flag/option descrepancy, the primary difference between an argv index and clap
376 /// index, is that clap continues counting once all arguments have properly seperated, whereas
377 /// an argv index does not.
379 /// The examples should clear this up.
381 /// *NOTE:* If an argument is allowed multiple times, this method will only give the *first*
386 /// The argv indices are listed in the comments below. See how they correspond to the clap
387 /// indices. Note that if it's not listed in a clap index, this is becuase it's not saved in
388 /// in an `ArgMatches` struct for querying.
391 /// # use clap::{App, Arg};
392 /// let m = App::new("myapp")
393 /// .arg(Arg::with_name("flag")
395 /// .arg(Arg::with_name("option")
397 /// .takes_value(true))
398 /// .get_matches_from(vec!["myapp", "-f", "-o", "val"]);
399 /// // ARGV idices: ^0 ^1 ^2 ^3
400 /// // clap idices: ^1 ^3
402 /// assert_eq!(m.index_of("flag"), Some(1));
403 /// assert_eq!(m.index_of("option"), Some(3));
406 /// Now notice, if we use one of the other styles of options:
409 /// # use clap::{App, Arg};
410 /// let m = App::new("myapp")
411 /// .arg(Arg::with_name("flag")
413 /// .arg(Arg::with_name("option")
415 /// .takes_value(true))
416 /// .get_matches_from(vec!["myapp", "-f", "-o=val"]);
417 /// // ARGV idices: ^0 ^1 ^2
418 /// // clap idices: ^1 ^3
420 /// assert_eq!(m.index_of("flag"), Some(1));
421 /// assert_eq!(m.index_of("option"), Some(3));
424 /// Things become much more complicated, or clear if we look at a more complex combination of
425 /// flags. Let's also throw in the final option style for good measure.
428 /// # use clap::{App, Arg};
429 /// let m = App::new("myapp")
430 /// .arg(Arg::with_name("flag")
432 /// .arg(Arg::with_name("flag2")
434 /// .arg(Arg::with_name("flag3")
436 /// .arg(Arg::with_name("option")
438 /// .takes_value(true))
439 /// .get_matches_from(vec!["myapp", "-fzF", "-oval"]);
440 /// // ARGV idices: ^0 ^1 ^2
441 /// // clap idices: ^1,2,3 ^5
443 /// // clap sees the above as 'myapp -f -z -F -o val'
444 /// // ^0 ^1 ^2 ^3 ^4 ^5
445 /// assert_eq!(m.index_of("flag"), Some(1));
446 /// assert_eq!(m.index_of("flag2"), Some(3));
447 /// assert_eq!(m.index_of("flag3"), Some(2));
448 /// assert_eq!(m.index_of("option"), Some(5));
451 /// One final combination of flags/options to see how they combine:
454 /// # use clap::{App, Arg};
455 /// let m = App::new("myapp")
456 /// .arg(Arg::with_name("flag")
458 /// .arg(Arg::with_name("flag2")
460 /// .arg(Arg::with_name("flag3")
462 /// .arg(Arg::with_name("option")
464 /// .takes_value(true)
466 /// .get_matches_from(vec!["myapp", "-fzFoval"]);
467 /// // ARGV idices: ^0 ^1
468 /// // clap idices: ^1,2,3^5
470 /// // clap sees the above as 'myapp -f -z -F -o val'
471 /// // ^0 ^1 ^2 ^3 ^4 ^5
472 /// assert_eq!(m.index_of("flag"), Some(1));
473 /// assert_eq!(m.index_of("flag2"), Some(3));
474 /// assert_eq!(m.index_of("flag3"), Some(2));
475 /// assert_eq!(m.index_of("option"), Some(5));
478 /// The last part to mention is when values are sent in multiple groups with a [delimiter].
481 /// # use clap::{App, Arg};
482 /// let m = App::new("myapp")
483 /// .arg(Arg::with_name("option")
485 /// .takes_value(true)
487 /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
488 /// // ARGV idices: ^0 ^1
489 /// // clap idices: ^2 ^3 ^4
491 /// // clap sees the above as 'myapp -o val1 val2 val3'
492 /// // ^0 ^1 ^2 ^3 ^4
493 /// assert_eq!(m.index_of("option"), Some(2));
495 /// [`ArgMatches`]: ./struct.ArgMatches.html
496 /// [delimiter]: ./struct.Arg.html#method.value_delimiter
497 pub fn index_of
<S
: AsRef
<str>>(&self, name
: S
) -> Option
<usize> {
498 if let Some(arg
) = self.args
.get(name
.as_ref()) {
499 if let Some(i
) = arg
.indices
.get(0) {
506 /// Gets all indices of the argument in respect to all other arguments. Indices are
507 /// similar to argv indices, but are not exactly 1:1.
509 /// For flags (i.e. those arguments which don't have an associated value), indices refer
510 /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices
511 /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the
512 /// index for `val` would be recorded. This is by design.
514 /// *NOTE:* For more information about how clap indices compare to argv indices, see
515 /// [`ArgMatches::index_of`]
520 /// # use clap::{App, Arg};
521 /// let m = App::new("myapp")
522 /// .arg(Arg::with_name("option")
524 /// .takes_value(true)
525 /// .use_delimiter(true)
527 /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
528 /// // ARGV idices: ^0 ^1
529 /// // clap idices: ^2 ^3 ^4
531 /// // clap sees the above as 'myapp -o val1 val2 val3'
532 /// // ^0 ^1 ^2 ^3 ^4
533 /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 3, 4]);
536 /// Another quick example is when flags and options are used together
539 /// # use clap::{App, Arg};
540 /// let m = App::new("myapp")
541 /// .arg(Arg::with_name("option")
543 /// .takes_value(true)
545 /// .arg(Arg::with_name("flag")
548 /// .get_matches_from(vec!["myapp", "-o", "val1", "-f", "-o", "val2", "-f"]);
549 /// // ARGV idices: ^0 ^1 ^2 ^3 ^4 ^5 ^6
550 /// // clap idices: ^2 ^3 ^5 ^6
552 /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 5]);
553 /// assert_eq!(m.indices_of("flag").unwrap().collect::<Vec<_>>(), &[3, 6]);
556 /// One final example, which is an odd case; if we *don't* use value delimiter as we did with
557 /// the first example above instead of `val1`, `val2` and `val3` all being distinc values, they
558 /// would all be a single value of `val1,val2,val3`, in which case case they'd only receive a
562 /// # use clap::{App, Arg};
563 /// let m = App::new("myapp")
564 /// .arg(Arg::with_name("option")
566 /// .takes_value(true)
568 /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
569 /// // ARGV idices: ^0 ^1
570 /// // clap idices: ^2
572 /// // clap sees the above as 'myapp -o "val1,val2,val3"'
574 /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2]);
576 /// [`ArgMatches`]: ./struct.ArgMatches.html
577 /// [`ArgMatches::index_of`]: ./struct.ArgMatches.html#method.index_of
578 /// [delimiter]: ./struct.Arg.html#method.value_delimiter
579 pub fn indices_of
<S
: AsRef
<str>>(&'a
self, name
: S
) -> Option
<Indices
<'a
>> {
580 if let Some(arg
) = self.args
.get(name
.as_ref()) {
581 fn to_usize(i
: &usize) -> usize { *i }
582 let to_usize
: fn(&usize) -> usize = to_usize
; // coerce to fn pointer
583 return Some(Indices
{
584 iter
: arg
.indices
.iter().map(to_usize
),
590 /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`]
591 /// as well. This method returns the [`ArgMatches`] for a particular subcommand or `None` if
592 /// the subcommand wasn't present at runtime.
597 /// # use clap::{App, Arg, SubCommand};
598 /// let app_m = App::new("myprog")
599 /// .arg(Arg::with_name("debug")
601 /// .subcommand(SubCommand::with_name("test")
602 /// .arg(Arg::with_name("opt")
604 /// .takes_value(true)))
605 /// .get_matches_from(vec![
606 /// "myprog", "-d", "test", "--option", "val"
609 /// // Both parent commands, and child subcommands can have arguments present at the same times
610 /// assert!(app_m.is_present("debug"));
612 /// // Get the subcommand's ArgMatches instance
613 /// if let Some(sub_m) = app_m.subcommand_matches("test") {
614 /// // Use the struct like normal
615 /// assert_eq!(sub_m.value_of("opt"), Some("val"));
618 /// [`Subcommand`]: ./struct.SubCommand.html
619 /// [`App`]: ./struct.App.html
620 /// [`ArgMatches`]: ./struct.ArgMatches.html
621 pub fn subcommand_matches
<S
: AsRef
<str>>(&self, name
: S
) -> Option
<&ArgMatches
<'a
>> {
622 if let Some(ref s
) = self.subcommand
{
623 if s
.name
== name
.as_ref() {
624 return Some(&s
.matches
);
630 /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`]
631 /// as well.But simply getting the sub-[`ArgMatches`] doesn't help much if we don't also know
632 /// which subcommand was actually used. This method returns the name of the subcommand that was
633 /// used at runtime, or `None` if one wasn't.
635 /// *NOTE*: Subcommands form a hierarchy, where multiple subcommands can be used at runtime,
636 /// but only a single subcommand from any group of sibling commands may used at once.
638 /// An ASCII art depiction may help explain this better...Using a fictional version of `git` as
639 /// the demo subject. Imagine the following are all subcommands of `git` (note, the author is
640 /// aware these aren't actually all subcommands in the real `git` interface, but it makes
641 /// explanation easier)
644 /// Top Level App (git) TOP
646 /// -----------------------------------------
648 /// clone push add commit LEVEL 1
650 /// url origin remote ref name message LEVEL 2
652 /// path remote local LEVEL 3
655 /// Given the above fictional subcommand hierarchy, valid runtime uses would be (not an all
656 /// inclusive list, and not including argument options per command for brevity and clarity):
660 /// $ git push origin path
661 /// $ git add ref local
662 /// $ git commit message
665 /// Notice only one command per "level" may be used. You could not, for example, do `$ git
666 /// clone url push origin path`
671 /// # use clap::{App, Arg, SubCommand};
672 /// let app_m = App::new("git")
673 /// .subcommand(SubCommand::with_name("clone"))
674 /// .subcommand(SubCommand::with_name("push"))
675 /// .subcommand(SubCommand::with_name("commit"))
678 /// match app_m.subcommand_name() {
679 /// Some("clone") => {}, // clone was used
680 /// Some("push") => {}, // push was used
681 /// Some("commit") => {}, // commit was used
682 /// _ => {}, // Either no subcommand or one not tested for...
685 /// [`Subcommand`]: ./struct.SubCommand.html
686 /// [`App`]: ./struct.App.html
687 /// [`ArgMatches`]: ./struct.ArgMatches.html
688 pub fn subcommand_name(&self) -> Option
<&str> {
689 self.subcommand
.as_ref().map(|sc
| &sc
.name
[..])
692 /// This brings together [`ArgMatches::subcommand_matches`] and [`ArgMatches::subcommand_name`]
693 /// by returning a tuple with both pieces of information.
698 /// # use clap::{App, Arg, SubCommand};
699 /// let app_m = App::new("git")
700 /// .subcommand(SubCommand::with_name("clone"))
701 /// .subcommand(SubCommand::with_name("push"))
702 /// .subcommand(SubCommand::with_name("commit"))
705 /// match app_m.subcommand() {
706 /// ("clone", Some(sub_m)) => {}, // clone was used
707 /// ("push", Some(sub_m)) => {}, // push was used
708 /// ("commit", Some(sub_m)) => {}, // commit was used
709 /// _ => {}, // Either no subcommand or one not tested for...
713 /// Another useful scenario is when you want to support third party, or external, subcommands.
714 /// In these cases you can't know the subcommand name ahead of time, so use a variable instead
715 /// with pattern matching!
718 /// # use clap::{App, AppSettings};
719 /// // Assume there is an external subcommand named "subcmd"
720 /// let app_m = App::new("myprog")
721 /// .setting(AppSettings::AllowExternalSubcommands)
722 /// .get_matches_from(vec![
723 /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
726 /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
727 /// // string argument name
728 /// match app_m.subcommand() {
729 /// (external, Some(sub_m)) => {
730 /// let ext_args: Vec<&str> = sub_m.values_of("").unwrap().collect();
731 /// assert_eq!(external, "subcmd");
732 /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
737 /// [`ArgMatches::subcommand_matches`]: ./struct.ArgMatches.html#method.subcommand_matches
738 /// [`ArgMatches::subcommand_name`]: ./struct.ArgMatches.html#method.subcommand_name
739 pub fn subcommand(&self) -> (&str, Option
<&ArgMatches
<'a
>>) {
742 .map_or(("", None
), |sc
| (&sc
.name
[..], Some(&sc
.matches
)))
745 /// Returns a string slice of the usage statement for the [`App`] or [`SubCommand`]
750 /// # use clap::{App, Arg, SubCommand};
751 /// let app_m = App::new("myprog")
752 /// .subcommand(SubCommand::with_name("test"))
755 /// println!("{}", app_m.usage());
757 /// [`Subcommand`]: ./struct.SubCommand.html
758 /// [`App`]: ./struct.App.html
759 pub fn usage(&self) -> &str { self.usage.as_ref().map_or("", |u| &u[..]) }
763 // The following were taken and adapated from vec_map source
764 // repo: https://github.com/contain-rs/vec-map
765 // commit: be5e1fa3c26e351761b33010ddbdaf5f05dbcc33
766 // license: MIT - Copyright (c) 2015 The Rust Project Developers
768 /// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of`]
774 /// # use clap::{App, Arg};
775 /// let m = App::new("myapp")
776 /// .arg(Arg::with_name("output")
779 /// .takes_value(true))
780 /// .get_matches_from(vec!["myapp", "-o", "val1", "val2"]);
782 /// let mut values = m.values_of("output").unwrap();
784 /// assert_eq!(values.next(), Some("val1"));
785 /// assert_eq!(values.next(), Some("val2"));
786 /// assert_eq!(values.next(), None);
788 /// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of
790 #[allow(missing_debug_implementations)]
791 pub struct Values
<'a
> {
792 iter
: Map
<Iter
<'a
, OsString
>, fn(&'a OsString
) -> &'a
str>,
795 impl<'a
> Iterator
for Values
<'a
> {
798 fn next(&mut self) -> Option
<&'a
str> { self.iter.next() }
799 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
802 impl<'a
> DoubleEndedIterator
for Values
<'a
> {
803 fn next_back(&mut self) -> Option
<&'a
str> { self.iter.next_back() }
806 impl<'a
> ExactSizeIterator
for Values
<'a
> {}
808 /// Creates an empty iterator.
809 impl<'a
> Default
for Values
<'a
> {
810 fn default() -> Self {
811 static EMPTY
: [OsString
; 0] = [];
812 // This is never called because the iterator is empty:
813 fn to_str_slice(_
: &OsString
) -> &str { unreachable!() }
;
815 iter
: EMPTY
[..].iter().map(to_str_slice
),
820 /// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of_os`]
821 /// method. Usage of this iterator allows values which contain invalid UTF-8 code points unlike
826 #[cfg_attr(not(unix), doc = " ```ignore")]
827 #[cfg_attr(unix, doc = " ```")]
828 /// # use clap::{App, Arg};
829 /// use std::ffi::OsString;
830 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
832 /// let m = App::new("utf8")
833 /// .arg(Arg::from_usage("<arg> 'some arg'"))
834 /// .get_matches_from(vec![OsString::from("myprog"),
836 /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
837 /// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']);
839 /// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os
840 /// [`Values`]: ./struct.Values.html
842 #[allow(missing_debug_implementations)]
843 pub struct OsValues
<'a
> {
844 iter
: Map
<Iter
<'a
, OsString
>, fn(&'a OsString
) -> &'a OsStr
>,
847 impl<'a
> Iterator
for OsValues
<'a
> {
848 type Item
= &'a OsStr
;
850 fn next(&mut self) -> Option
<&'a OsStr
> { self.iter.next() }
851 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
854 impl<'a
> DoubleEndedIterator
for OsValues
<'a
> {
855 fn next_back(&mut self) -> Option
<&'a OsStr
> { self.iter.next_back() }
858 /// Creates an empty iterator.
859 impl<'a
> Default
for OsValues
<'a
> {
860 fn default() -> Self {
861 static EMPTY
: [OsString
; 0] = [];
862 // This is never called because the iterator is empty:
863 fn to_str_slice(_
: &OsString
) -> &OsStr { unreachable!() }
;
865 iter
: EMPTY
[..].iter().map(to_str_slice
),
870 /// An iterator for getting multiple indices out of an argument via the [`ArgMatches::indices_of`]
876 /// # use clap::{App, Arg};
877 /// let m = App::new("myapp")
878 /// .arg(Arg::with_name("output")
881 /// .takes_value(true))
882 /// .get_matches_from(vec!["myapp", "-o", "val1", "val2"]);
884 /// let mut indices = m.indices_of("output").unwrap();
886 /// assert_eq!(indices.next(), Some(2));
887 /// assert_eq!(indices.next(), Some(3));
888 /// assert_eq!(indices.next(), None);
890 /// [`ArgMatches::indices_of`]: ./struct.ArgMatches.html#method.indices_of
892 #[allow(missing_debug_implementations)]
893 pub struct Indices
<'a
> { // would rather use '_, but: https://github.com/rust-lang/rust/issues/48469
894 iter
: Map
<Iter
<'a
, usize>, fn(&'a
usize) -> usize>,
897 impl<'a
> Iterator
for Indices
<'a
> {
900 fn next(&mut self) -> Option
<usize> { self.iter.next() }
901 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
904 impl<'a
> DoubleEndedIterator
for Indices
<'a
> {
905 fn next_back(&mut self) -> Option
<usize> { self.iter.next_back() }
908 impl<'a
> ExactSizeIterator
for Indices
<'a
> {}
910 /// Creates an empty iterator.
911 impl<'a
> Default
for Indices
<'a
> {
912 fn default() -> Self {
913 static EMPTY
: [usize; 0] = [];
914 // This is never called because the iterator is empty:
915 fn to_usize(_
: &usize) -> usize { unreachable!() }
;
917 iter
: EMPTY
[..].iter().map(to_usize
),
927 fn test_default_values() {
928 let mut values
: Values
= Values
::default();
929 assert_eq
!(values
.next(), None
);
933 fn test_default_values_with_shorter_lifetime() {
934 let matches
= ArgMatches
::new();
935 let mut values
= matches
.values_of("").unwrap_or_default();
936 assert_eq
!(values
.next(), None
);
940 fn test_default_osvalues() {
941 let mut values
: OsValues
= OsValues
::default();
942 assert_eq
!(values
.next(), None
);
946 fn test_default_osvalues_with_shorter_lifetime() {
947 let matches
= ArgMatches
::new();
948 let mut values
= matches
.values_of_os("").unwrap_or_default();
949 assert_eq
!(values
.next(), None
);
953 fn test_default_indices() {
954 let mut indices
: Indices
= Indices
::default();
955 assert_eq
!(indices
.next(), None
);
959 fn test_default_indices_with_shorter_lifetime() {
960 let matches
= ArgMatches
::new();
961 let mut indices
= matches
.indices_of("").unwrap_or_default();
962 assert_eq
!(indices
.next(), None
);