3 use std
::collections
::HashMap
;
4 use std
::ffi
::{OsStr, OsString}
;
16 /// Used to get information about the arguments that where supplied to the program at runtime by
17 /// the user. New instances of this struct are obtained by using the [`App::get_matches`] family of
23 /// # use clap::{App, Arg};
24 /// let matches = App::new("MyApp")
25 /// .arg(Arg::with_name("out")
28 /// .takes_value(true))
29 /// .arg(Arg::with_name("debug")
32 /// .arg(Arg::with_name("cfg")
34 /// .takes_value(true))
35 /// .get_matches(); // builds the instance of ArgMatches
37 /// // to get information about the "cfg" argument we created, such as the value supplied we use
38 /// // various ArgMatches methods, such as ArgMatches::value_of
39 /// if let Some(c) = matches.value_of("cfg") {
40 /// println!("Value for -c: {}", c);
43 /// // The ArgMatches::value_of method returns an Option because the user may not have supplied
44 /// // that argument at runtime. But if we specified that the argument was "required" as we did
45 /// // with the "out" argument, we can safely unwrap because `clap` verifies that was actually
46 /// // used at runtime.
47 /// println!("Value for --output: {}", matches.value_of("out").unwrap());
49 /// // You can check the presence of an argument
50 /// if matches.is_present("out") {
51 /// // Another way to check if an argument was present, or if it occurred multiple times is to
52 /// // use occurrences_of() which returns 0 if an argument isn't found at runtime, or the
53 /// // number of times that it occurred, if it was. To allow an argument to appear more than
54 /// // once, you must use the .multiple(true) method, otherwise it will only return 1 or 0.
55 /// if matches.occurrences_of("debug") > 2 {
56 /// println!("Debug mode is REALLY on, don't be crazy");
58 /// println!("Debug mode kind of on");
62 /// [`App::get_matches`]: ./struct.App.html#method.get_matches
63 #[derive(Debug, Clone)]
64 pub struct ArgMatches
<'a
> {
66 pub args
: HashMap
<&'a
str, MatchedArg
>,
68 pub subcommand
: Option
<Box
<SubCommand
<'a
>>>,
70 pub usage
: Option
<String
>,
73 impl<'a
> Default
for ArgMatches
<'a
> {
74 fn default() -> Self {
83 impl<'a
> ArgMatches
<'a
> {
85 pub fn new() -> Self { ArgMatches { ..Default::default() }
}
87 /// Gets the value of a specific [option] or [positional] argument (i.e. an argument that takes
88 /// an additional value at runtime). If the option wasn't present at runtime
89 /// it returns `None`.
91 /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
92 /// prefer [`ArgMatches::values_of`] as `ArgMatches::value_of` will only return the *first*
97 /// This method will [`panic!`] if the value contains invalid UTF-8 code points.
102 /// # use clap::{App, Arg};
103 /// let m = App::new("myapp")
104 /// .arg(Arg::with_name("output")
105 /// .takes_value(true))
106 /// .get_matches_from(vec!["myapp", "something"]);
108 /// assert_eq!(m.value_of("output"), Some("something"));
110 /// [option]: ./struct.Arg.html#method.takes_value
111 /// [positional]: ./struct.Arg.html#method.index
112 /// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of
113 /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html
114 pub fn value_of
<S
: AsRef
<str>>(&self, name
: S
) -> Option
<&str> {
115 if let Some(arg
) = self.args
.get(name
.as_ref()) {
116 if let Some(v
) = arg
.vals
.values().nth(0) {
117 return Some(v
.to_str().expect(INVALID_UTF8
));
123 /// Gets the lossy value of a specific argument. If the argument wasn't present at runtime
124 /// it returns `None`. A lossy value is one which contains invalid UTF-8 code points, those
125 /// invalid points will be replaced with `\u{FFFD}`
127 /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
128 /// prefer [`Arg::values_of_lossy`] as `value_of_lossy()` will only return the *first* value.
132 #[cfg_attr(not(unix), doc=" ```ignore")]
133 #[cfg_attr( unix , doc=" ```")]
134 /// # use clap::{App, Arg};
135 /// use std::ffi::OsString;
136 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
138 /// let m = App::new("utf8")
139 /// .arg(Arg::from_usage("<arg> 'some arg'"))
140 /// .get_matches_from(vec![OsString::from("myprog"),
142 /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
143 /// assert_eq!(&*m.value_of_lossy("arg").unwrap(), "Hi \u{FFFD}!");
145 /// [`Arg::values_of_lossy`]: ./struct.ArgMatches.html#method.values_of_lossy
146 pub fn value_of_lossy
<S
: AsRef
<str>>(&'a
self, name
: S
) -> Option
<Cow
<'a
, str>> {
147 if let Some(arg
) = self.args
.get(name
.as_ref()) {
148 if let Some(v
) = arg
.vals
.values().nth(0) {
149 return Some(v
.to_string_lossy());
155 /// Gets the OS version of a string value of a specific argument. If the option wasn't present
156 /// at runtime it returns `None`. An OS value on Unix-like systems is any series of bytes,
157 /// regardless of whether or not they contain valid UTF-8 code points. Since [`String`]s in
158 /// Rust are guaranteed to be valid UTF-8, a valid filename on a Unix system as an argument
159 /// value may contain invalid UTF-8 code points.
161 /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
162 /// prefer [`ArgMatches::values_of_os`] as `Arg::value_of_os` will only return the *first*
167 #[cfg_attr(not(unix), doc=" ```ignore")]
168 #[cfg_attr( unix , doc=" ```")]
169 /// # use clap::{App, Arg};
170 /// use std::ffi::OsString;
171 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
173 /// let m = App::new("utf8")
174 /// .arg(Arg::from_usage("<arg> 'some arg'"))
175 /// .get_matches_from(vec![OsString::from("myprog"),
177 /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
178 /// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']);
180 /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
181 /// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os
182 pub fn value_of_os
<S
: AsRef
<str>>(&self, name
: S
) -> Option
<&OsStr
> {
185 .map_or(None
, |arg
| arg
.vals
.values().nth(0).map(|v
| v
.as_os_str()))
188 /// Gets a [`Values`] struct which implements [`Iterator`] for values of a specific argument
189 /// (i.e. an argument that takes multiple values at runtime). If the option wasn't present at
190 /// runtime it returns `None`
194 /// This method will panic if any of the values contain invalid UTF-8 code points.
199 /// # use clap::{App, Arg};
200 /// let m = App::new("myprog")
201 /// .arg(Arg::with_name("output")
204 /// .takes_value(true))
205 /// .get_matches_from(vec![
206 /// "myprog", "-o", "val1", "val2", "val3"
208 /// let vals: Vec<&str> = m.values_of("output").unwrap().collect();
209 /// assert_eq!(vals, ["val1", "val2", "val3"]);
211 /// [`Values`]: ./struct.Values.html
212 /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
213 pub fn values_of
<S
: AsRef
<str>>(&'a
self, name
: S
) -> Option
<Values
<'a
>> {
214 if let Some(arg
) = self.args
.get(name
.as_ref()) {
215 fn to_str_slice(o
: &OsString
) -> &str { o.to_str().expect(INVALID_UTF8) }
216 let to_str_slice
: fn(&OsString
) -> &str = to_str_slice
; // coerce to fn pointer
217 return Some(Values { iter: arg.vals.values().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()) {
250 .map(|v
| v
.to_string_lossy().into_owned())
256 /// Gets a [`OsValues`] struct which is implements [`Iterator`] for [`OsString`] values of a
257 /// specific argument. If the option wasn't present at runtime it returns `None`. An OS value
258 /// on Unix-like systems is any series of bytes, regardless of whether or not they contain
259 /// valid UTF-8 code points. Since [`String`]s in Rust are guaranteed to be valid UTF-8, a valid
260 /// filename as an argument value on Linux (for example) may contain invalid UTF-8 code points.
264 #[cfg_attr(not(unix), doc=" ```ignore")]
265 #[cfg_attr( unix , doc=" ```")]
266 /// # use clap::{App, Arg};
267 /// use std::ffi::{OsStr,OsString};
268 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
270 /// let m = App::new("utf8")
271 /// .arg(Arg::from_usage("<arg>... 'some arg'"))
272 /// .get_matches_from(vec![OsString::from("myprog"),
274 /// OsString::from_vec(vec![b'H', b'i']),
276 /// OsString::from_vec(vec![0xe9, b'!'])]);
278 /// let mut itr = m.values_of_os("arg").unwrap().into_iter();
279 /// assert_eq!(itr.next(), Some(OsStr::new("Hi")));
280 /// assert_eq!(itr.next(), Some(OsStr::from_bytes(&[0xe9, b'!'])));
281 /// assert_eq!(itr.next(), None);
283 /// [`OsValues`]: ./struct.OsValues.html
284 /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
285 /// [`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html
286 /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
287 pub fn values_of_os
<S
: AsRef
<str>>(&'a
self, name
: S
) -> Option
<OsValues
<'a
>> {
288 fn to_str_slice(o
: &OsString
) -> &OsStr { &*o }
289 let to_str_slice
: fn(&'a OsString
) -> &'a OsStr
= to_str_slice
; // coerce to fn pointer
290 if let Some(arg
) = self.args
.get(name
.as_ref()) {
291 return Some(OsValues { iter: arg.vals.values().map(to_str_slice) }
);
296 /// Returns `true` if an argument was present at runtime, otherwise `false`.
301 /// # use clap::{App, Arg};
302 /// let m = App::new("myprog")
303 /// .arg(Arg::with_name("debug")
305 /// .get_matches_from(vec![
309 /// assert!(m.is_present("debug"));
311 pub fn is_present
<S
: AsRef
<str>>(&self, name
: S
) -> bool
{
312 if let Some(ref sc
) = self.subcommand
{
313 if sc
.name
== name
.as_ref() {
317 self.args
.contains_key(name
.as_ref())
320 /// Returns the number of times an argument was used at runtime. If an argument isn't present
321 /// it will return `0`.
323 /// **NOTE:** This returns the number of times the argument was used, *not* the number of
324 /// values. For example, `-o val1 val2 val3 -o val4` would return `2` (2 occurrences, but 4
330 /// # use clap::{App, Arg};
331 /// let m = App::new("myprog")
332 /// .arg(Arg::with_name("debug")
335 /// .get_matches_from(vec![
336 /// "myprog", "-d", "-d", "-d"
339 /// assert_eq!(m.occurrences_of("debug"), 3);
342 /// This next example shows that counts actual uses of the argument, not just `-`'s
345 /// # use clap::{App, Arg};
346 /// let m = App::new("myprog")
347 /// .arg(Arg::with_name("debug")
350 /// .arg(Arg::with_name("flag")
352 /// .get_matches_from(vec![
353 /// "myprog", "-ddfd"
356 /// assert_eq!(m.occurrences_of("debug"), 3);
357 /// assert_eq!(m.occurrences_of("flag"), 1);
359 pub fn occurrences_of
<S
: AsRef
<str>>(&self, name
: S
) -> u64 {
360 self.args
.get(name
.as_ref()).map_or(0, |a
| a
.occurs
)
363 /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`]
364 /// as well. This method returns the [`ArgMatches`] for a particular subcommand or `None` if
365 /// the subcommand wasn't present at runtime.
370 /// # use clap::{App, Arg, SubCommand};
371 /// let app_m = App::new("myprog")
372 /// .arg(Arg::with_name("debug")
374 /// .subcommand(SubCommand::with_name("test")
375 /// .arg(Arg::with_name("opt")
377 /// .takes_value(true)))
378 /// .get_matches_from(vec![
379 /// "myprog", "-d", "test", "--option", "val"
382 /// // Both parent commands, and child subcommands can have arguments present at the same times
383 /// assert!(app_m.is_present("debug"));
385 /// // Get the subcommand's ArgMatches instance
386 /// if let Some(sub_m) = app_m.subcommand_matches("test") {
387 /// // Use the struct like normal
388 /// assert_eq!(sub_m.value_of("opt"), Some("val"));
391 /// [`Subcommand`]: ./struct.SubCommand.html
392 /// [`App`]: ./struct.App.html
393 /// [`ArgMatches`]: ./struct.ArgMatches.html
394 pub fn subcommand_matches
<S
: AsRef
<str>>(&self, name
: S
) -> Option
<&ArgMatches
<'a
>> {
395 if let Some(ref s
) = self.subcommand
{
396 if s
.name
== name
.as_ref() {
397 return Some(&s
.matches
);
403 /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`]
404 /// as well.But simply getting the sub-[`ArgMatches`] doesn't help much if we don't also know
405 /// which subcommand was actually used. This method returns the name of the subcommand that was
406 /// used at runtime, or `None` if one wasn't.
408 /// *NOTE*: Subcommands form a hierarchy, where multiple subcommands can be used at runtime,
409 /// but only a single subcommand from any group of sibling commands may used at once.
411 /// An ASCII art depiction may help explain this better...Using a fictional version of `git` as
412 /// the demo subject. Imagine the following are all subcommands of `git` (note, the author is
413 /// aware these aren't actually all subcommands in the real `git` interface, but it makes
414 /// explanation easier)
417 /// Top Level App (git) TOP
419 /// -----------------------------------------
421 /// clone push add commit LEVEL 1
423 /// url origin remote ref name message LEVEL 2
425 /// path remote local LEVEL 3
428 /// Given the above fictional subcommand hierarchy, valid runtime uses would be (not an all
429 /// inclusive list, and not including argument options per command for brevity and clarity):
433 /// $ git push origin path
434 /// $ git add ref local
435 /// $ git commit message
438 /// Notice only one command per "level" may be used. You could not, for example, do `$ git
439 /// clone url push origin path`
444 /// # use clap::{App, Arg, SubCommand};
445 /// let app_m = App::new("git")
446 /// .subcommand(SubCommand::with_name("clone"))
447 /// .subcommand(SubCommand::with_name("push"))
448 /// .subcommand(SubCommand::with_name("commit"))
451 /// match app_m.subcommand_name() {
452 /// Some("clone") => {}, // clone was used
453 /// Some("push") => {}, // push was used
454 /// Some("commit") => {}, // commit was used
455 /// _ => {}, // Either no subcommand or one not tested for...
458 /// [`Subcommand`]: ./struct.SubCommand.html
459 /// [`App`]: ./struct.App.html
460 /// [`ArgMatches`]: ./struct.ArgMatches.html
461 pub fn subcommand_name(&self) -> Option
<&str> {
462 self.subcommand
.as_ref().map(|sc
| &sc
.name
[..])
465 /// This brings together [`ArgMatches::subcommand_matches`] and [`ArgMatches::subcommand_name`]
466 /// by returning a tuple with both pieces of information.
471 /// # use clap::{App, Arg, SubCommand};
472 /// let app_m = App::new("git")
473 /// .subcommand(SubCommand::with_name("clone"))
474 /// .subcommand(SubCommand::with_name("push"))
475 /// .subcommand(SubCommand::with_name("commit"))
478 /// match app_m.subcommand() {
479 /// ("clone", Some(sub_m)) => {}, // clone was used
480 /// ("push", Some(sub_m)) => {}, // push was used
481 /// ("commit", Some(sub_m)) => {}, // commit was used
482 /// _ => {}, // Either no subcommand or one not tested for...
486 /// Another useful scenario is when you want to support third party, or external, subcommands.
487 /// In these cases you can't know the subcommand name ahead of time, so use a variable instead
488 /// with pattern matching!
491 /// # use clap::{App, AppSettings};
492 /// // Assume there is an external subcommand named "subcmd"
493 /// let app_m = App::new("myprog")
494 /// .setting(AppSettings::AllowExternalSubcommands)
495 /// .get_matches_from(vec![
496 /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
499 /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
500 /// // string argument name
501 /// match app_m.subcommand() {
502 /// (external, Some(sub_m)) => {
503 /// let ext_args: Vec<&str> = sub_m.values_of("").unwrap().collect();
504 /// assert_eq!(external, "subcmd");
505 /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
510 /// [`ArgMatches::subcommand_matches`]: ./struct.ArgMatches.html#method.subcommand_matches
511 /// [`ArgMatches::subcommand_name`]: ./struct.ArgMatches.html#method.subcommand_name
512 pub fn subcommand(&self) -> (&str, Option
<&ArgMatches
<'a
>>) {
513 self.subcommand
.as_ref().map_or(("", None
), |sc
| (&sc
.name
[..], Some(&sc
.matches
)))
516 /// Returns a string slice of the usage statement for the [`App`] or [`SubCommand`]
521 /// # use clap::{App, Arg, SubCommand};
522 /// let app_m = App::new("myprog")
523 /// .subcommand(SubCommand::with_name("test"))
526 /// println!("{}", app_m.usage());
528 /// [`Subcommand`]: ./struct.SubCommand.html
529 /// [`App`]: ./struct.App.html
530 pub fn usage(&self) -> &str { self.usage.as_ref().map_or("", |u| &u[..]) }
534 // The following were taken and adapated from vec_map source
535 // repo: https://github.com/contain-rs/vec-map
536 // commit: be5e1fa3c26e351761b33010ddbdaf5f05dbcc33
537 // license: MIT - Copyright (c) 2015 The Rust Project Developers
539 /// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of`]
545 /// # use clap::{App, Arg};
546 /// let m = App::new("myapp")
547 /// .arg(Arg::with_name("output")
548 /// .takes_value(true))
549 /// .get_matches_from(vec!["myapp", "something"]);
551 /// assert_eq!(m.value_of("output"), Some("something"));
553 /// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of
555 #[allow(missing_debug_implementations)]
556 pub struct Values
<'a
> {
557 iter
: Map
<vec_map
::Values
<'a
, OsString
>, fn(&'a OsString
) -> &'a
str>,
560 impl<'a
> Iterator
for Values
<'a
> {
563 fn next(&mut self) -> Option
<&'a
str> { self.iter.next() }
564 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
567 impl<'a
> DoubleEndedIterator
for Values
<'a
> {
568 fn next_back(&mut self) -> Option
<&'a
str> { self.iter.next_back() }
571 /// An iterator over the key-value pairs of a map.
573 pub struct Iter
<'a
, V
: 'a
> {
576 iter
: slice
::Iter
<'a
, Option
<V
>>,
579 impl<'a
, V
> Iterator
for Iter
<'a
, V
> {
583 fn next(&mut self) -> Option
<&'a V
> {
584 while self.front
< self.back
{
585 if let Some(elem
) = self.iter
.next() {
586 if let Some(x
) = elem
.as_ref() {
597 fn size_hint(&self) -> (usize, Option
<usize>) { (0, Some(self.back - self.front)) }
600 impl<'a
, V
> DoubleEndedIterator
for Iter
<'a
, V
> {
602 fn next_back(&mut self) -> Option
<&'a V
> {
603 while self.front
< self.back
{
604 if let Some(elem
) = self.iter
.next_back() {
605 if let Some(x
) = elem
.as_ref() {
616 /// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of_os`]
617 /// method. Usage of this iterator allows values which contain invalid UTF-8 code points unlike
622 #[cfg_attr(not(unix), doc=" ```ignore")]
623 #[cfg_attr( unix , doc=" ```")]
624 /// # use clap::{App, Arg};
625 /// use std::ffi::OsString;
626 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
628 /// let m = App::new("utf8")
629 /// .arg(Arg::from_usage("<arg> 'some arg'"))
630 /// .get_matches_from(vec![OsString::from("myprog"),
632 /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
633 /// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']);
635 /// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os
636 /// [`Values`]: ./struct.Values.html
638 #[allow(missing_debug_implementations)]
639 pub struct OsValues
<'a
> {
640 iter
: Map
<vec_map
::Values
<'a
, OsString
>, fn(&'a OsString
) -> &'a OsStr
>,
643 impl<'a
> Iterator
for OsValues
<'a
> {
644 type Item
= &'a OsStr
;
646 fn next(&mut self) -> Option
<&'a OsStr
> { self.iter.next() }
647 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
650 impl<'a
> DoubleEndedIterator
for OsValues
<'a
> {
651 fn next_back(&mut self) -> Option
<&'a OsStr
> { self.iter.next_back() }