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
> {
63 pub args
: HashMap
<&'a
str, MatchedArg
>,
65 pub subcommand
: Option
<Box
<SubCommand
<'a
>>>,
67 pub usage
: Option
<String
>,
70 impl<'a
> Default
for ArgMatches
<'a
> {
71 fn default() -> Self {
80 impl<'a
> ArgMatches
<'a
> {
82 pub fn new() -> Self { ArgMatches { ..Default::default() }
}
84 /// Gets the value of a specific [option] or [positional] argument (i.e. an argument that takes
85 /// an additional value at runtime). If the option wasn't present at runtime
86 /// it returns `None`.
88 /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
89 /// prefer [`ArgMatches::values_of`] as `ArgMatches::value_of` will only return the *first*
94 /// This method will [`panic!`] if the value contains invalid UTF-8 code points.
99 /// # use clap::{App, Arg};
100 /// let m = App::new("myapp")
101 /// .arg(Arg::with_name("output")
102 /// .takes_value(true))
103 /// .get_matches_from(vec!["myapp", "something"]);
105 /// assert_eq!(m.value_of("output"), Some("something"));
107 /// [option]: ./struct.Arg.html#method.takes_value
108 /// [positional]: ./struct.Arg.html#method.index
109 /// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of
110 /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html
111 pub fn value_of
<S
: AsRef
<str>>(&self, name
: S
) -> Option
<&str> {
112 if let Some(arg
) = self.args
.get(name
.as_ref()) {
113 if let Some(v
) = arg
.vals
.get(0) {
114 return Some(v
.to_str().expect(INVALID_UTF8
));
120 /// Gets the lossy value of a specific argument. If the argument wasn't present at runtime
121 /// it returns `None`. A lossy value is one which contains invalid UTF-8 code points, those
122 /// invalid points will be replaced with `\u{FFFD}`
124 /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
125 /// prefer [`Arg::values_of_lossy`] as `value_of_lossy()` will only return the *first* value.
129 #[cfg_attr(not(unix), doc=" ```ignore")]
130 #[cfg_attr( unix , doc=" ```")]
131 /// # use clap::{App, Arg};
132 /// use std::ffi::OsString;
133 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
135 /// let m = App::new("utf8")
136 /// .arg(Arg::from_usage("<arg> 'some arg'"))
137 /// .get_matches_from(vec![OsString::from("myprog"),
139 /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
140 /// assert_eq!(&*m.value_of_lossy("arg").unwrap(), "Hi \u{FFFD}!");
142 /// [`Arg::values_of_lossy`]: ./struct.ArgMatches.html#method.values_of_lossy
143 pub fn value_of_lossy
<S
: AsRef
<str>>(&'a
self, name
: S
) -> Option
<Cow
<'a
, str>> {
144 if let Some(arg
) = self.args
.get(name
.as_ref()) {
145 if let Some(v
) = arg
.vals
.get(0) {
146 return Some(v
.to_string_lossy());
152 /// Gets the OS version of a string value of a specific argument. If the option wasn't present
153 /// at runtime it returns `None`. An OS value on Unix-like systems is any series of bytes,
154 /// regardless of whether or not they contain valid UTF-8 code points. Since [`String`]s in
155 /// Rust are guaranteed to be valid UTF-8, a valid filename on a Unix system as an argument
156 /// value may contain invalid UTF-8 code points.
158 /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
159 /// prefer [`ArgMatches::values_of_os`] as `Arg::value_of_os` will only return the *first*
164 #[cfg_attr(not(unix), doc=" ```ignore")]
165 #[cfg_attr( unix , doc=" ```")]
166 /// # use clap::{App, Arg};
167 /// use std::ffi::OsString;
168 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
170 /// let m = App::new("utf8")
171 /// .arg(Arg::from_usage("<arg> 'some arg'"))
172 /// .get_matches_from(vec![OsString::from("myprog"),
174 /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
175 /// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']);
177 /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
178 /// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os
179 pub fn value_of_os
<S
: AsRef
<str>>(&self, name
: S
) -> Option
<&OsStr
> {
182 .map_or(None
, |arg
| arg
.vals
.get(0).map(|v
| v
.as_os_str()))
185 /// Gets a [`Values`] struct which implements [`Iterator`] for values of a specific argument
186 /// (i.e. an argument that takes multiple values at runtime). If the option wasn't present at
187 /// runtime it returns `None`
191 /// This method will panic if any of the values contain invalid UTF-8 code points.
196 /// # use clap::{App, Arg};
197 /// let m = App::new("myprog")
198 /// .arg(Arg::with_name("output")
201 /// .takes_value(true))
202 /// .get_matches_from(vec![
203 /// "myprog", "-o", "val1", "val2", "val3"
205 /// let vals: Vec<&str> = m.values_of("output").unwrap().collect();
206 /// assert_eq!(vals, ["val1", "val2", "val3"]);
208 /// [`Values`]: ./struct.Values.html
209 /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
210 pub fn values_of
<S
: AsRef
<str>>(&'a
self, name
: S
) -> Option
<Values
<'a
>> {
211 if let Some(arg
) = self.args
.get(name
.as_ref()) {
212 fn to_str_slice(o
: &OsString
) -> &str { o.to_str().expect(INVALID_UTF8) }
213 let to_str_slice
: fn(&OsString
) -> &str = to_str_slice
; // coerce to fn pointer
214 return Some(Values { iter: arg.vals.iter().map(to_str_slice) }
);
219 /// Gets the lossy values of a specific argument. If the option wasn't present at runtime
220 /// it returns `None`. A lossy value is one where if it contains invalid UTF-8 code points,
221 /// those invalid points will be replaced with `\u{FFFD}`
225 #[cfg_attr(not(unix), doc=" ```ignore")]
226 #[cfg_attr( unix , doc=" ```")]
227 /// # use clap::{App, Arg};
228 /// use std::ffi::OsString;
229 /// use std::os::unix::ffi::OsStringExt;
231 /// let m = App::new("utf8")
232 /// .arg(Arg::from_usage("<arg>... 'some arg'"))
233 /// .get_matches_from(vec![OsString::from("myprog"),
235 /// OsString::from_vec(vec![b'H', b'i']),
237 /// OsString::from_vec(vec![0xe9, b'!'])]);
238 /// let mut itr = m.values_of_lossy("arg").unwrap().into_iter();
239 /// assert_eq!(&itr.next().unwrap()[..], "Hi");
240 /// assert_eq!(&itr.next().unwrap()[..], "\u{FFFD}!");
241 /// assert_eq!(itr.next(), None);
243 pub fn values_of_lossy
<S
: AsRef
<str>>(&'a
self, name
: S
) -> Option
<Vec
<String
>> {
244 if let Some(arg
) = self.args
.get(name
.as_ref()) {
247 .map(|v
| v
.to_string_lossy().into_owned())
253 /// Gets a [`OsValues`] struct which is implements [`Iterator`] for [`OsString`] values of a
254 /// specific argument. If the option wasn't present at runtime it returns `None`. An OS value
255 /// on Unix-like systems is any series of bytes, regardless of whether or not they contain
256 /// valid UTF-8 code points. Since [`String`]s in Rust are guaranteed to be valid UTF-8, a valid
257 /// filename as an argument value on Linux (for example) may contain invalid UTF-8 code points.
261 #[cfg_attr(not(unix), doc=" ```ignore")]
262 #[cfg_attr( unix , doc=" ```")]
263 /// # use clap::{App, Arg};
264 /// use std::ffi::{OsStr,OsString};
265 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
267 /// let m = App::new("utf8")
268 /// .arg(Arg::from_usage("<arg>... 'some arg'"))
269 /// .get_matches_from(vec![OsString::from("myprog"),
271 /// OsString::from_vec(vec![b'H', b'i']),
273 /// OsString::from_vec(vec![0xe9, b'!'])]);
275 /// let mut itr = m.values_of_os("arg").unwrap().into_iter();
276 /// assert_eq!(itr.next(), Some(OsStr::new("Hi")));
277 /// assert_eq!(itr.next(), Some(OsStr::from_bytes(&[0xe9, b'!'])));
278 /// assert_eq!(itr.next(), None);
280 /// [`OsValues`]: ./struct.OsValues.html
281 /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
282 /// [`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html
283 /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
284 pub fn values_of_os
<S
: AsRef
<str>>(&'a
self, name
: S
) -> Option
<OsValues
<'a
>> {
285 fn to_str_slice(o
: &OsString
) -> &OsStr { &*o }
286 let to_str_slice
: fn(&'a OsString
) -> &'a OsStr
= to_str_slice
; // coerce to fn pointer
287 if let Some(arg
) = self.args
.get(name
.as_ref()) {
288 return Some(OsValues { iter: arg.vals.iter().map(to_str_slice) }
);
293 /// Returns `true` if an argument was present at runtime, otherwise `false`.
298 /// # use clap::{App, Arg};
299 /// let m = App::new("myprog")
300 /// .arg(Arg::with_name("debug")
302 /// .get_matches_from(vec![
306 /// assert!(m.is_present("debug"));
308 pub fn is_present
<S
: AsRef
<str>>(&self, name
: S
) -> bool
{
309 if let Some(ref sc
) = self.subcommand
{
310 if sc
.name
== name
.as_ref() {
314 self.args
.contains_key(name
.as_ref())
317 /// Returns the number of times an argument was used at runtime. If an argument isn't present
318 /// it will return `0`.
320 /// **NOTE:** This returns the number of times the argument was used, *not* the number of
321 /// values. For example, `-o val1 val2 val3 -o val4` would return `2` (2 occurrences, but 4
327 /// # use clap::{App, Arg};
328 /// let m = App::new("myprog")
329 /// .arg(Arg::with_name("debug")
332 /// .get_matches_from(vec![
333 /// "myprog", "-d", "-d", "-d"
336 /// assert_eq!(m.occurrences_of("debug"), 3);
339 /// This next example shows that counts actual uses of the argument, not just `-`'s
342 /// # use clap::{App, Arg};
343 /// let m = App::new("myprog")
344 /// .arg(Arg::with_name("debug")
347 /// .arg(Arg::with_name("flag")
349 /// .get_matches_from(vec![
350 /// "myprog", "-ddfd"
353 /// assert_eq!(m.occurrences_of("debug"), 3);
354 /// assert_eq!(m.occurrences_of("flag"), 1);
356 pub fn occurrences_of
<S
: AsRef
<str>>(&self, name
: S
) -> u64 {
357 self.args
.get(name
.as_ref()).map_or(0, |a
| a
.occurs
)
360 /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`]
361 /// as well. This method returns the [`ArgMatches`] for a particular subcommand or `None` if
362 /// the subcommand wasn't present at runtime.
367 /// # use clap::{App, Arg, SubCommand};
368 /// let app_m = App::new("myprog")
369 /// .arg(Arg::with_name("debug")
371 /// .subcommand(SubCommand::with_name("test")
372 /// .arg(Arg::with_name("opt")
374 /// .takes_value(true)))
375 /// .get_matches_from(vec![
376 /// "myprog", "-d", "test", "--option", "val"
379 /// // Both parent commands, and child subcommands can have arguments present at the same times
380 /// assert!(app_m.is_present("debug"));
382 /// // Get the subcommand's ArgMatches instance
383 /// if let Some(sub_m) = app_m.subcommand_matches("test") {
384 /// // Use the struct like normal
385 /// assert_eq!(sub_m.value_of("opt"), Some("val"));
388 /// [`Subcommand`]: ./struct.SubCommand.html
389 /// [`App`]: ./struct.App.html
390 /// [`ArgMatches`]: ./struct.ArgMatches.html
391 pub fn subcommand_matches
<S
: AsRef
<str>>(&self, name
: S
) -> Option
<&ArgMatches
<'a
>> {
392 if let Some(ref s
) = self.subcommand
{
393 if s
.name
== name
.as_ref() {
394 return Some(&s
.matches
);
400 /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`]
401 /// as well.But simply getting the sub-[`ArgMatches`] doesn't help much if we don't also know
402 /// which subcommand was actually used. This method returns the name of the subcommand that was
403 /// used at runtime, or `None` if one wasn't.
405 /// *NOTE*: Subcommands form a hierarchy, where multiple subcommands can be used at runtime,
406 /// but only a single subcommand from any group of sibling commands may used at once.
408 /// An ASCII art depiction may help explain this better...Using a fictional version of `git` as
409 /// the demo subject. Imagine the following are all subcommands of `git` (note, the author is
410 /// aware these aren't actually all subcommands in the real `git` interface, but it makes
411 /// explanation easier)
414 /// Top Level App (git) TOP
416 /// -----------------------------------------
418 /// clone push add commit LEVEL 1
420 /// url origin remote ref name message LEVEL 2
422 /// path remote local LEVEL 3
425 /// Given the above fictional subcommand hierarchy, valid runtime uses would be (not an all
426 /// inclusive list, and not including argument options per command for brevity and clarity):
430 /// $ git push origin path
431 /// $ git add ref local
432 /// $ git commit message
435 /// Notice only one command per "level" may be used. You could not, for example, do `$ git
436 /// clone url push origin path`
441 /// # use clap::{App, Arg, SubCommand};
442 /// let app_m = App::new("git")
443 /// .subcommand(SubCommand::with_name("clone"))
444 /// .subcommand(SubCommand::with_name("push"))
445 /// .subcommand(SubCommand::with_name("commit"))
448 /// match app_m.subcommand_name() {
449 /// Some("clone") => {}, // clone was used
450 /// Some("push") => {}, // push was used
451 /// Some("commit") => {}, // commit was used
452 /// _ => {}, // Either no subcommand or one not tested for...
455 /// [`Subcommand`]: ./struct.SubCommand.html
456 /// [`App`]: ./struct.App.html
457 /// [`ArgMatches`]: ./struct.ArgMatches.html
458 pub fn subcommand_name(&self) -> Option
<&str> {
459 self.subcommand
.as_ref().map(|sc
| &sc
.name
[..])
462 /// This brings together [`ArgMatches::subcommand_matches`] and [`ArgMatches::subcommand_name`]
463 /// by returning a tuple with both pieces of information.
468 /// # use clap::{App, Arg, SubCommand};
469 /// let app_m = App::new("git")
470 /// .subcommand(SubCommand::with_name("clone"))
471 /// .subcommand(SubCommand::with_name("push"))
472 /// .subcommand(SubCommand::with_name("commit"))
475 /// match app_m.subcommand() {
476 /// ("clone", Some(sub_m)) => {}, // clone was used
477 /// ("push", Some(sub_m)) => {}, // push was used
478 /// ("commit", Some(sub_m)) => {}, // commit was used
479 /// _ => {}, // Either no subcommand or one not tested for...
483 /// Another useful scenario is when you want to support third party, or external, subcommands.
484 /// In these cases you can't know the subcommand name ahead of time, so use a variable instead
485 /// with pattern matching!
488 /// # use clap::{App, AppSettings};
489 /// // Assume there is an external subcommand named "subcmd"
490 /// let app_m = App::new("myprog")
491 /// .setting(AppSettings::AllowExternalSubcommands)
492 /// .get_matches_from(vec![
493 /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
496 /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
497 /// // string argument name
498 /// match app_m.subcommand() {
499 /// (external, Some(sub_m)) => {
500 /// let ext_args: Vec<&str> = sub_m.values_of("").unwrap().collect();
501 /// assert_eq!(external, "subcmd");
502 /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
507 /// [`ArgMatches::subcommand_matches`]: ./struct.ArgMatches.html#method.subcommand_matches
508 /// [`ArgMatches::subcommand_name`]: ./struct.ArgMatches.html#method.subcommand_name
509 pub fn subcommand(&self) -> (&str, Option
<&ArgMatches
<'a
>>) {
510 self.subcommand
.as_ref().map_or(("", None
), |sc
| (&sc
.name
[..], Some(&sc
.matches
)))
513 /// Returns a string slice of the usage statement for the [`App`] or [`SubCommand`]
518 /// # use clap::{App, Arg, SubCommand};
519 /// let app_m = App::new("myprog")
520 /// .subcommand(SubCommand::with_name("test"))
523 /// println!("{}", app_m.usage());
525 /// [`Subcommand`]: ./struct.SubCommand.html
526 /// [`App`]: ./struct.App.html
527 pub fn usage(&self) -> &str { self.usage.as_ref().map_or("", |u| &u[..]) }
531 // The following were taken and adapated from vec_map source
532 // repo: https://github.com/contain-rs/vec-map
533 // commit: be5e1fa3c26e351761b33010ddbdaf5f05dbcc33
534 // license: MIT - Copyright (c) 2015 The Rust Project Developers
536 /// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of`]
542 /// # use clap::{App, Arg};
543 /// let m = App::new("myapp")
544 /// .arg(Arg::with_name("output")
545 /// .takes_value(true))
546 /// .get_matches_from(vec!["myapp", "something"]);
548 /// assert_eq!(m.value_of("output"), Some("something"));
550 /// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of
552 #[allow(missing_debug_implementations)]
553 pub struct Values
<'a
> {
554 iter
: Map
<Iter
<'a
, OsString
>, fn(&'a OsString
) -> &'a
str>,
557 impl<'a
> Iterator
for Values
<'a
> {
560 fn next(&mut self) -> Option
<&'a
str> { self.iter.next() }
561 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
564 impl<'a
> DoubleEndedIterator
for Values
<'a
> {
565 fn next_back(&mut self) -> Option
<&'a
str> { self.iter.next_back() }
568 impl<'a
> ExactSizeIterator
for Values
<'a
> {}
570 /// Creates an empty iterator.
571 impl<'a
> Default
for Values
<'a
> {
572 fn default() -> Self {
573 static EMPTY
: [OsString
; 0] = [];
574 // This is never called because the iterator is empty:
575 fn to_str_slice(_
: &OsString
) -> &str { unreachable!() }
;
576 Values { iter: EMPTY[..].iter().map(to_str_slice) }
581 fn test_default_values() {
582 let mut values
: Values
= Values
::default();
583 assert_eq
!(values
.next(), None
);
587 fn test_default_values_with_shorter_lifetime() {
588 let matches
= ArgMatches
::new();
589 let mut values
= matches
.values_of("").unwrap_or_default();
590 assert_eq
!(values
.next(), None
);
593 /// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of_os`]
594 /// method. Usage of this iterator allows values which contain invalid UTF-8 code points unlike
599 #[cfg_attr(not(unix), doc=" ```ignore")]
600 #[cfg_attr( unix , doc=" ```")]
601 /// # use clap::{App, Arg};
602 /// use std::ffi::OsString;
603 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
605 /// let m = App::new("utf8")
606 /// .arg(Arg::from_usage("<arg> 'some arg'"))
607 /// .get_matches_from(vec![OsString::from("myprog"),
609 /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
610 /// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']);
612 /// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os
613 /// [`Values`]: ./struct.Values.html
615 #[allow(missing_debug_implementations)]
616 pub struct OsValues
<'a
> {
617 iter
: Map
<Iter
<'a
, OsString
>, fn(&'a OsString
) -> &'a OsStr
>,
620 impl<'a
> Iterator
for OsValues
<'a
> {
621 type Item
= &'a OsStr
;
623 fn next(&mut self) -> Option
<&'a OsStr
> { self.iter.next() }
624 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
627 impl<'a
> DoubleEndedIterator
for OsValues
<'a
> {
628 fn next_back(&mut self) -> Option
<&'a OsStr
> { self.iter.next_back() }
631 /// Creates an empty iterator.
632 impl<'a
> Default
for OsValues
<'a
> {
633 fn default() -> Self {
634 static EMPTY
: [OsString
; 0] = [];
635 // This is never called because the iterator is empty:
636 fn to_str_slice(_
: &OsString
) -> &OsStr { unreachable!() }
;
637 OsValues { iter: EMPTY[..].iter().map(to_str_slice) }
642 fn test_default_osvalues() {
643 let mut values
: OsValues
= OsValues
::default();
644 assert_eq
!(values
.next(), None
);
648 fn test_default_osvalues_with_shorter_lifetime() {
649 let matches
= ArgMatches
::new();
650 let mut values
= matches
.values_of_os("").unwrap_or_default();
651 assert_eq
!(values
.next(), None
);