clap/args/arg_matches.rs
1// Std
2use std::{
3 borrow::Cow,
4 collections::HashMap,
5 ffi::{OsStr, OsString},
6 iter::Map,
7 slice::Iter,
8};
9
10// Internal
11use crate::{
12 args::{MatchedArg, SubCommand},
13 INVALID_UTF8,
14};
15
16/// Used to get information about the arguments that were 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
18/// methods.
19///
20/// # Examples
21///
22/// ```no_run
23/// # use clap::{App, Arg};
24/// let matches = App::new("MyApp")
25/// .arg(Arg::with_name("out")
26/// .long("output")
27/// .required(true)
28/// .takes_value(true))
29/// .arg(Arg::with_name("debug")
30/// .short("d")
31/// .multiple(true))
32/// .arg(Arg::with_name("cfg")
33/// .short("c")
34/// .takes_value(true))
35/// .get_matches(); // builds the instance of ArgMatches
36///
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);
41/// }
42///
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());
48///
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");
57/// } else {
58/// println!("Debug mode kind of on");
59/// }
60/// }
61/// ```
62/// [`App::get_matches`]: ./struct.App.html#method.get_matches
63#[derive(Debug, Clone)]
64pub struct ArgMatches<'a> {
65 #[doc(hidden)]
66 pub args: HashMap<&'a str, MatchedArg>,
67 #[doc(hidden)]
68 pub subcommand: Option<Box<SubCommand<'a>>>,
69 #[doc(hidden)]
70 pub usage: Option<String>,
71}
72
73impl<'a> Default for ArgMatches<'a> {
74 fn default() -> Self {
75 ArgMatches {
76 args: HashMap::new(),
77 subcommand: None,
78 usage: None,
79 }
80 }
81}
82
83impl<'a> ArgMatches<'a> {
84 #[doc(hidden)]
85 pub fn new() -> Self {
86 ArgMatches {
87 ..Default::default()
88 }
89 }
90
91 /// Gets the value of a specific [option] or [positional] argument (i.e. an argument that takes
92 /// an additional value at runtime). If the option wasn't present at runtime
93 /// it returns `None`.
94 ///
95 /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
96 /// prefer [`ArgMatches::values_of`] as `ArgMatches::value_of` will only return the *first*
97 /// value.
98 ///
99 /// # Panics
100 ///
101 /// This method will [`panic!`] if the value contains invalid UTF-8 code points.
102 ///
103 /// # Examples
104 ///
105 /// ```rust
106 /// # use clap::{App, Arg};
107 /// let m = App::new("myapp")
108 /// .arg(Arg::with_name("output")
109 /// .takes_value(true))
110 /// .get_matches_from(vec!["myapp", "something"]);
111 ///
112 /// assert_eq!(m.value_of("output"), Some("something"));
113 /// ```
114 /// [option]: ./struct.Arg.html#method.takes_value
115 /// [positional]: ./struct.Arg.html#method.index
116 /// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of
117 /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html
118 pub fn value_of<S: AsRef<str>>(&self, name: S) -> Option<&str> {
119 if let Some(arg) = self.args.get(name.as_ref()) {
120 if let Some(v) = arg.vals.get(0) {
121 return Some(v.to_str().expect(INVALID_UTF8));
122 }
123 }
124 None
125 }
126
127 /// Gets the lossy value of a specific argument. If the argument wasn't present at runtime
128 /// it returns `None`. A lossy value is one which contains invalid UTF-8 code points, those
129 /// invalid points will be replaced with `\u{FFFD}`
130 ///
131 /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
132 /// prefer [`Arg::values_of_lossy`] as `value_of_lossy()` will only return the *first* value.
133 ///
134 /// # Examples
135 ///
136 #[cfg_attr(not(unix), doc = " ```ignore")]
137 #[cfg_attr(unix, doc = " ```")]
138 /// # use clap::{App, Arg};
139 /// use std::ffi::OsString;
140 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
141 ///
142 /// let m = App::new("utf8")
143 /// .arg(Arg::from_usage("<arg> 'some arg'"))
144 /// .get_matches_from(vec![OsString::from("myprog"),
145 /// // "Hi {0xe9}!"
146 /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
147 /// assert_eq!(&*m.value_of_lossy("arg").unwrap(), "Hi \u{FFFD}!");
148 /// ```
149 /// [`Arg::values_of_lossy`]: ./struct.ArgMatches.html#method.values_of_lossy
150 pub fn value_of_lossy<S: AsRef<str>>(&'a self, name: S) -> Option<Cow<'a, str>> {
151 if let Some(arg) = self.args.get(name.as_ref()) {
152 if let Some(v) = arg.vals.get(0) {
153 return Some(v.to_string_lossy());
154 }
155 }
156 None
157 }
158
159 /// Gets the OS version of a string value of a specific argument. If the option wasn't present
160 /// at runtime it returns `None`. An OS value on Unix-like systems is any series of bytes,
161 /// regardless of whether or not they contain valid UTF-8 code points. Since [`String`]s in
162 /// Rust are guaranteed to be valid UTF-8, a valid filename on a Unix system as an argument
163 /// value may contain invalid UTF-8 code points.
164 ///
165 /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
166 /// prefer [`ArgMatches::values_of_os`] as `Arg::value_of_os` will only return the *first*
167 /// value.
168 ///
169 /// # Examples
170 ///
171 #[cfg_attr(not(unix), doc = " ```ignore")]
172 #[cfg_attr(unix, doc = " ```")]
173 /// # use clap::{App, Arg};
174 /// use std::ffi::OsString;
175 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
176 ///
177 /// let m = App::new("utf8")
178 /// .arg(Arg::from_usage("<arg> 'some arg'"))
179 /// .get_matches_from(vec![OsString::from("myprog"),
180 /// // "Hi {0xe9}!"
181 /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
182 /// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']);
183 /// ```
184 /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
185 /// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os
186 pub fn value_of_os<S: AsRef<str>>(&self, name: S) -> Option<&OsStr> {
187 self.args
188 .get(name.as_ref())
189 .and_then(|arg| arg.vals.get(0).map(|v| v.as_os_str()))
190 }
191
192 /// Gets a [`Values`] struct which implements [`Iterator`] for values of a specific argument
193 /// (i.e. an argument that takes multiple values at runtime). If the option wasn't present at
194 /// runtime it returns `None`
195 ///
196 /// # Panics
197 ///
198 /// This method will panic if any of the values contain invalid UTF-8 code points.
199 ///
200 /// # Examples
201 ///
202 /// ```rust
203 /// # use clap::{App, Arg};
204 /// let m = App::new("myprog")
205 /// .arg(Arg::with_name("output")
206 /// .multiple(true)
207 /// .short("o")
208 /// .takes_value(true))
209 /// .get_matches_from(vec![
210 /// "myprog", "-o", "val1", "val2", "val3"
211 /// ]);
212 /// let vals: Vec<&str> = m.values_of("output").unwrap().collect();
213 /// assert_eq!(vals, ["val1", "val2", "val3"]);
214 /// ```
215 /// [`Values`]: ./struct.Values.html
216 /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
217 pub fn values_of<S: AsRef<str>>(&'a self, name: S) -> Option<Values<'a>> {
218 if let Some(arg) = self.args.get(name.as_ref()) {
219 fn to_str_slice(o: &OsString) -> &str {
220 o.to_str().expect(INVALID_UTF8)
221 }
222 let to_str_slice: fn(&OsString) -> &str = to_str_slice; // coerce to fn pointer
223 return Some(Values {
224 iter: arg.vals.iter().map(to_str_slice),
225 });
226 }
227 None
228 }
229
230 /// Gets the lossy values of a specific argument. If the option wasn't present at runtime
231 /// it returns `None`. A lossy value is one where if it contains invalid UTF-8 code points,
232 /// those invalid points will be replaced with `\u{FFFD}`
233 ///
234 /// # Examples
235 ///
236 #[cfg_attr(not(unix), doc = " ```ignore")]
237 #[cfg_attr(unix, doc = " ```")]
238 /// # use clap::{App, Arg};
239 /// use std::ffi::OsString;
240 /// use std::os::unix::ffi::OsStringExt;
241 ///
242 /// let m = App::new("utf8")
243 /// .arg(Arg::from_usage("<arg>... 'some arg'"))
244 /// .get_matches_from(vec![OsString::from("myprog"),
245 /// // "Hi"
246 /// OsString::from_vec(vec![b'H', b'i']),
247 /// // "{0xe9}!"
248 /// OsString::from_vec(vec![0xe9, b'!'])]);
249 /// let mut itr = m.values_of_lossy("arg").unwrap().into_iter();
250 /// assert_eq!(&itr.next().unwrap()[..], "Hi");
251 /// assert_eq!(&itr.next().unwrap()[..], "\u{FFFD}!");
252 /// assert_eq!(itr.next(), None);
253 /// ```
254 pub fn values_of_lossy<S: AsRef<str>>(&'a self, name: S) -> Option<Vec<String>> {
255 if let Some(arg) = self.args.get(name.as_ref()) {
256 return Some(
257 arg.vals
258 .iter()
259 .map(|v| v.to_string_lossy().into_owned())
260 .collect(),
261 );
262 }
263 None
264 }
265
266 /// Gets a [`OsValues`] struct which is implements [`Iterator`] for [`OsString`] values of a
267 /// specific argument. If the option wasn't present at runtime it returns `None`. An OS value
268 /// on Unix-like systems is any series of bytes, regardless of whether or not they contain
269 /// valid UTF-8 code points. Since [`String`]s in Rust are guaranteed to be valid UTF-8, a valid
270 /// filename as an argument value on Linux (for example) may contain invalid UTF-8 code points.
271 ///
272 /// # Examples
273 ///
274 #[cfg_attr(not(unix), doc = " ```ignore")]
275 #[cfg_attr(unix, doc = " ```")]
276 /// # use clap::{App, Arg};
277 /// use std::ffi::{OsStr,OsString};
278 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
279 ///
280 /// let m = App::new("utf8")
281 /// .arg(Arg::from_usage("<arg>... 'some arg'"))
282 /// .get_matches_from(vec![OsString::from("myprog"),
283 /// // "Hi"
284 /// OsString::from_vec(vec![b'H', b'i']),
285 /// // "{0xe9}!"
286 /// OsString::from_vec(vec![0xe9, b'!'])]);
287 ///
288 /// let mut itr = m.values_of_os("arg").unwrap().into_iter();
289 /// assert_eq!(itr.next(), Some(OsStr::new("Hi")));
290 /// assert_eq!(itr.next(), Some(OsStr::from_bytes(&[0xe9, b'!'])));
291 /// assert_eq!(itr.next(), None);
292 /// ```
293 /// [`OsValues`]: ./struct.OsValues.html
294 /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
295 /// [`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html
296 /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
297 pub fn values_of_os<S: AsRef<str>>(&'a self, name: S) -> Option<OsValues<'a>> {
298 fn to_str_slice(o: &OsString) -> &OsStr {
299 &*o
300 }
301 let to_str_slice: fn(&'a OsString) -> &'a OsStr = to_str_slice; // coerce to fn pointer
302 if let Some(arg) = self.args.get(name.as_ref()) {
303 return Some(OsValues {
304 iter: arg.vals.iter().map(to_str_slice),
305 });
306 }
307 None
308 }
309
310 /// Returns `true` if an argument was present at runtime, otherwise `false`.
311 ///
312 /// # Examples
313 ///
314 /// ```rust
315 /// # use clap::{App, Arg};
316 /// let m = App::new("myprog")
317 /// .arg(Arg::with_name("debug")
318 /// .short("d"))
319 /// .get_matches_from(vec![
320 /// "myprog", "-d"
321 /// ]);
322 ///
323 /// assert!(m.is_present("debug"));
324 /// ```
325 pub fn is_present<S: AsRef<str>>(&self, name: S) -> bool {
326 if let Some(ref sc) = self.subcommand {
327 if sc.name == name.as_ref() {
328 return true;
329 }
330 }
331 self.args.contains_key(name.as_ref())
332 }
333
334 /// Returns the number of times an argument was used at runtime. If an argument isn't present
335 /// it will return `0`.
336 ///
337 /// **NOTE:** This returns the number of times the argument was used, *not* the number of
338 /// values. For example, `-o val1 val2 val3 -o val4` would return `2` (2 occurrences, but 4
339 /// values).
340 ///
341 /// # Examples
342 ///
343 /// ```rust
344 /// # use clap::{App, Arg};
345 /// let m = App::new("myprog")
346 /// .arg(Arg::with_name("debug")
347 /// .short("d")
348 /// .multiple(true))
349 /// .get_matches_from(vec![
350 /// "myprog", "-d", "-d", "-d"
351 /// ]);
352 ///
353 /// assert_eq!(m.occurrences_of("debug"), 3);
354 /// ```
355 ///
356 /// This next example shows that counts actual uses of the argument, not just `-`'s
357 ///
358 /// ```rust
359 /// # use clap::{App, Arg};
360 /// let m = App::new("myprog")
361 /// .arg(Arg::with_name("debug")
362 /// .short("d")
363 /// .multiple(true))
364 /// .arg(Arg::with_name("flag")
365 /// .short("f"))
366 /// .get_matches_from(vec![
367 /// "myprog", "-ddfd"
368 /// ]);
369 ///
370 /// assert_eq!(m.occurrences_of("debug"), 3);
371 /// assert_eq!(m.occurrences_of("flag"), 1);
372 /// ```
373 pub fn occurrences_of<S: AsRef<str>>(&self, name: S) -> u64 {
374 self.args.get(name.as_ref()).map_or(0, |a| a.occurs)
375 }
376
377 /// Gets the starting index of the argument in respect to all other arguments. Indices are
378 /// similar to argv indices, but are not exactly 1:1.
379 ///
380 /// For flags (i.e. those arguments which don't have an associated value), indices refer
381 /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices
382 /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the
383 /// index for `val` would be recorded. This is by design.
384 ///
385 /// Besides the flag/option descrepancy, the primary difference between an argv index and clap
386 /// index, is that clap continues counting once all arguments have properly seperated, whereas
387 /// an argv index does not.
388 ///
389 /// The examples should clear this up.
390 ///
391 /// *NOTE:* If an argument is allowed multiple times, this method will only give the *first*
392 /// index.
393 ///
394 /// # Examples
395 ///
396 /// The argv indices are listed in the comments below. See how they correspond to the clap
397 /// indices. Note that if it's not listed in a clap index, this is becuase it's not saved in
398 /// in an `ArgMatches` struct for querying.
399 ///
400 /// ```rust
401 /// # use clap::{App, Arg};
402 /// let m = App::new("myapp")
403 /// .arg(Arg::with_name("flag")
404 /// .short("f"))
405 /// .arg(Arg::with_name("option")
406 /// .short("o")
407 /// .takes_value(true))
408 /// .get_matches_from(vec!["myapp", "-f", "-o", "val"]);
409 /// // ARGV idices: ^0 ^1 ^2 ^3
410 /// // clap idices: ^1 ^3
411 ///
412 /// assert_eq!(m.index_of("flag"), Some(1));
413 /// assert_eq!(m.index_of("option"), Some(3));
414 /// ```
415 ///
416 /// Now notice, if we use one of the other styles of options:
417 ///
418 /// ```rust
419 /// # use clap::{App, Arg};
420 /// let m = App::new("myapp")
421 /// .arg(Arg::with_name("flag")
422 /// .short("f"))
423 /// .arg(Arg::with_name("option")
424 /// .short("o")
425 /// .takes_value(true))
426 /// .get_matches_from(vec!["myapp", "-f", "-o=val"]);
427 /// // ARGV idices: ^0 ^1 ^2
428 /// // clap idices: ^1 ^3
429 ///
430 /// assert_eq!(m.index_of("flag"), Some(1));
431 /// assert_eq!(m.index_of("option"), Some(3));
432 /// ```
433 ///
434 /// Things become much more complicated, or clear if we look at a more complex combination of
435 /// flags. Let's also throw in the final option style for good measure.
436 ///
437 /// ```rust
438 /// # use clap::{App, Arg};
439 /// let m = App::new("myapp")
440 /// .arg(Arg::with_name("flag")
441 /// .short("f"))
442 /// .arg(Arg::with_name("flag2")
443 /// .short("F"))
444 /// .arg(Arg::with_name("flag3")
445 /// .short("z"))
446 /// .arg(Arg::with_name("option")
447 /// .short("o")
448 /// .takes_value(true))
449 /// .get_matches_from(vec!["myapp", "-fzF", "-oval"]);
450 /// // ARGV idices: ^0 ^1 ^2
451 /// // clap idices: ^1,2,3 ^5
452 /// //
453 /// // clap sees the above as 'myapp -f -z -F -o val'
454 /// // ^0 ^1 ^2 ^3 ^4 ^5
455 /// assert_eq!(m.index_of("flag"), Some(1));
456 /// assert_eq!(m.index_of("flag2"), Some(3));
457 /// assert_eq!(m.index_of("flag3"), Some(2));
458 /// assert_eq!(m.index_of("option"), Some(5));
459 /// ```
460 ///
461 /// One final combination of flags/options to see how they combine:
462 ///
463 /// ```rust
464 /// # use clap::{App, Arg};
465 /// let m = App::new("myapp")
466 /// .arg(Arg::with_name("flag")
467 /// .short("f"))
468 /// .arg(Arg::with_name("flag2")
469 /// .short("F"))
470 /// .arg(Arg::with_name("flag3")
471 /// .short("z"))
472 /// .arg(Arg::with_name("option")
473 /// .short("o")
474 /// .takes_value(true)
475 /// .multiple(true))
476 /// .get_matches_from(vec!["myapp", "-fzFoval"]);
477 /// // ARGV idices: ^0 ^1
478 /// // clap idices: ^1,2,3^5
479 /// //
480 /// // clap sees the above as 'myapp -f -z -F -o val'
481 /// // ^0 ^1 ^2 ^3 ^4 ^5
482 /// assert_eq!(m.index_of("flag"), Some(1));
483 /// assert_eq!(m.index_of("flag2"), Some(3));
484 /// assert_eq!(m.index_of("flag3"), Some(2));
485 /// assert_eq!(m.index_of("option"), Some(5));
486 /// ```
487 ///
488 /// The last part to mention is when values are sent in multiple groups with a [delimiter].
489 ///
490 /// ```rust
491 /// # use clap::{App, Arg};
492 /// let m = App::new("myapp")
493 /// .arg(Arg::with_name("option")
494 /// .short("o")
495 /// .takes_value(true)
496 /// .multiple(true))
497 /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
498 /// // ARGV idices: ^0 ^1
499 /// // clap idices: ^2 ^3 ^4
500 /// //
501 /// // clap sees the above as 'myapp -o val1 val2 val3'
502 /// // ^0 ^1 ^2 ^3 ^4
503 /// assert_eq!(m.index_of("option"), Some(2));
504 /// ```
505 /// [`ArgMatches`]: ./struct.ArgMatches.html
506 /// [delimiter]: ./struct.Arg.html#method.value_delimiter
507 pub fn index_of<S: AsRef<str>>(&self, name: S) -> Option<usize> {
508 if let Some(arg) = self.args.get(name.as_ref()) {
509 if let Some(i) = arg.indices.get(0) {
510 return Some(*i);
511 }
512 }
513 None
514 }
515
516 /// Gets all indices of the argument in respect to all other arguments. Indices are
517 /// similar to argv indices, but are not exactly 1:1.
518 ///
519 /// For flags (i.e. those arguments which don't have an associated value), indices refer
520 /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices
521 /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the
522 /// index for `val` would be recorded. This is by design.
523 ///
524 /// *NOTE:* For more information about how clap indices compare to argv indices, see
525 /// [`ArgMatches::index_of`]
526 ///
527 /// # Examples
528 ///
529 /// ```rust
530 /// # use clap::{App, Arg};
531 /// let m = App::new("myapp")
532 /// .arg(Arg::with_name("option")
533 /// .short("o")
534 /// .takes_value(true)
535 /// .use_delimiter(true)
536 /// .multiple(true))
537 /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
538 /// // ARGV idices: ^0 ^1
539 /// // clap idices: ^2 ^3 ^4
540 /// //
541 /// // clap sees the above as 'myapp -o val1 val2 val3'
542 /// // ^0 ^1 ^2 ^3 ^4
543 /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 3, 4]);
544 /// ```
545 ///
546 /// Another quick example is when flags and options are used together
547 ///
548 /// ```rust
549 /// # use clap::{App, Arg};
550 /// let m = App::new("myapp")
551 /// .arg(Arg::with_name("option")
552 /// .short("o")
553 /// .takes_value(true)
554 /// .multiple(true))
555 /// .arg(Arg::with_name("flag")
556 /// .short("f")
557 /// .multiple(true))
558 /// .get_matches_from(vec!["myapp", "-o", "val1", "-f", "-o", "val2", "-f"]);
559 /// // ARGV idices: ^0 ^1 ^2 ^3 ^4 ^5 ^6
560 /// // clap idices: ^2 ^3 ^5 ^6
561 ///
562 /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 5]);
563 /// assert_eq!(m.indices_of("flag").unwrap().collect::<Vec<_>>(), &[3, 6]);
564 /// ```
565 ///
566 /// One final example, which is an odd case; if we *don't* use value delimiter as we did with
567 /// the first example above instead of `val1`, `val2` and `val3` all being distinc values, they
568 /// would all be a single value of `val1,val2,val3`, in which case case they'd only receive a
569 /// single index.
570 ///
571 /// ```rust
572 /// # use clap::{App, Arg};
573 /// let m = App::new("myapp")
574 /// .arg(Arg::with_name("option")
575 /// .short("o")
576 /// .takes_value(true)
577 /// .multiple(true))
578 /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
579 /// // ARGV idices: ^0 ^1
580 /// // clap idices: ^2
581 /// //
582 /// // clap sees the above as 'myapp -o "val1,val2,val3"'
583 /// // ^0 ^1 ^2
584 /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2]);
585 /// ```
586 /// [`ArgMatches`]: ./struct.ArgMatches.html
587 /// [`ArgMatches::index_of`]: ./struct.ArgMatches.html#method.index_of
588 /// [delimiter]: ./struct.Arg.html#method.value_delimiter
589 pub fn indices_of<S: AsRef<str>>(&'a self, name: S) -> Option<Indices<'a>> {
590 if let Some(arg) = self.args.get(name.as_ref()) {
591 fn to_usize(i: &usize) -> usize {
592 *i
593 }
594 let to_usize: fn(&usize) -> usize = to_usize; // coerce to fn pointer
595 return Some(Indices {
596 iter: arg.indices.iter().map(to_usize),
597 });
598 }
599 None
600 }
601
602 /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`]
603 /// as well. This method returns the [`ArgMatches`] for a particular subcommand or `None` if
604 /// the subcommand wasn't present at runtime.
605 ///
606 /// # Examples
607 ///
608 /// ```rust
609 /// # use clap::{App, Arg, SubCommand};
610 /// let app_m = App::new("myprog")
611 /// .arg(Arg::with_name("debug")
612 /// .short("d"))
613 /// .subcommand(SubCommand::with_name("test")
614 /// .arg(Arg::with_name("opt")
615 /// .long("option")
616 /// .takes_value(true)))
617 /// .get_matches_from(vec![
618 /// "myprog", "-d", "test", "--option", "val"
619 /// ]);
620 ///
621 /// // Both parent commands, and child subcommands can have arguments present at the same times
622 /// assert!(app_m.is_present("debug"));
623 ///
624 /// // Get the subcommand's ArgMatches instance
625 /// if let Some(sub_m) = app_m.subcommand_matches("test") {
626 /// // Use the struct like normal
627 /// assert_eq!(sub_m.value_of("opt"), Some("val"));
628 /// }
629 /// ```
630 /// [`Subcommand`]: ./struct.SubCommand.html
631 /// [`App`]: ./struct.App.html
632 /// [`ArgMatches`]: ./struct.ArgMatches.html
633 pub fn subcommand_matches<S: AsRef<str>>(&self, name: S) -> Option<&ArgMatches<'a>> {
634 if let Some(ref s) = self.subcommand {
635 if s.name == name.as_ref() {
636 return Some(&s.matches);
637 }
638 }
639 None
640 }
641
642 /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`]
643 /// as well.But simply getting the sub-[`ArgMatches`] doesn't help much if we don't also know
644 /// which subcommand was actually used. This method returns the name of the subcommand that was
645 /// used at runtime, or `None` if one wasn't.
646 ///
647 /// *NOTE*: Subcommands form a hierarchy, where multiple subcommands can be used at runtime,
648 /// but only a single subcommand from any group of sibling commands may used at once.
649 ///
650 /// An ASCII art depiction may help explain this better...Using a fictional version of `git` as
651 /// the demo subject. Imagine the following are all subcommands of `git` (note, the author is
652 /// aware these aren't actually all subcommands in the real `git` interface, but it makes
653 /// explanation easier)
654 ///
655 /// ```notrust
656 /// Top Level App (git) TOP
657 /// |
658 /// -----------------------------------------
659 /// / | \ \
660 /// clone push add commit LEVEL 1
661 /// | / \ / \ |
662 /// url origin remote ref name message LEVEL 2
663 /// / /\
664 /// path remote local LEVEL 3
665 /// ```
666 ///
667 /// Given the above fictional subcommand hierarchy, valid runtime uses would be (not an all
668 /// inclusive list, and not including argument options per command for brevity and clarity):
669 ///
670 /// ```sh
671 /// $ git clone url
672 /// $ git push origin path
673 /// $ git add ref local
674 /// $ git commit message
675 /// ```
676 ///
677 /// Notice only one command per "level" may be used. You could not, for example, do `$ git
678 /// clone url push origin path`
679 ///
680 /// # Examples
681 ///
682 /// ```no_run
683 /// # use clap::{App, Arg, SubCommand};
684 /// let app_m = App::new("git")
685 /// .subcommand(SubCommand::with_name("clone"))
686 /// .subcommand(SubCommand::with_name("push"))
687 /// .subcommand(SubCommand::with_name("commit"))
688 /// .get_matches();
689 ///
690 /// match app_m.subcommand_name() {
691 /// Some("clone") => {}, // clone was used
692 /// Some("push") => {}, // push was used
693 /// Some("commit") => {}, // commit was used
694 /// _ => {}, // Either no subcommand or one not tested for...
695 /// }
696 /// ```
697 /// [`Subcommand`]: ./struct.SubCommand.html
698 /// [`App`]: ./struct.App.html
699 /// [`ArgMatches`]: ./struct.ArgMatches.html
700 pub fn subcommand_name(&self) -> Option<&str> {
701 self.subcommand.as_ref().map(|sc| &sc.name[..])
702 }
703
704 /// This brings together [`ArgMatches::subcommand_matches`] and [`ArgMatches::subcommand_name`]
705 /// by returning a tuple with both pieces of information.
706 ///
707 /// # Examples
708 ///
709 /// ```no_run
710 /// # use clap::{App, Arg, SubCommand};
711 /// let app_m = App::new("git")
712 /// .subcommand(SubCommand::with_name("clone"))
713 /// .subcommand(SubCommand::with_name("push"))
714 /// .subcommand(SubCommand::with_name("commit"))
715 /// .get_matches();
716 ///
717 /// match app_m.subcommand() {
718 /// ("clone", Some(sub_m)) => {}, // clone was used
719 /// ("push", Some(sub_m)) => {}, // push was used
720 /// ("commit", Some(sub_m)) => {}, // commit was used
721 /// _ => {}, // Either no subcommand or one not tested for...
722 /// }
723 /// ```
724 ///
725 /// Another useful scenario is when you want to support third party, or external, subcommands.
726 /// In these cases you can't know the subcommand name ahead of time, so use a variable instead
727 /// with pattern matching!
728 ///
729 /// ```rust
730 /// # use clap::{App, AppSettings};
731 /// // Assume there is an external subcommand named "subcmd"
732 /// let app_m = App::new("myprog")
733 /// .setting(AppSettings::AllowExternalSubcommands)
734 /// .get_matches_from(vec![
735 /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
736 /// ]);
737 ///
738 /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
739 /// // string argument name
740 /// match app_m.subcommand() {
741 /// (external, Some(sub_m)) => {
742 /// let ext_args: Vec<&str> = sub_m.values_of("").unwrap().collect();
743 /// assert_eq!(external, "subcmd");
744 /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
745 /// },
746 /// _ => {},
747 /// }
748 /// ```
749 /// [`ArgMatches::subcommand_matches`]: ./struct.ArgMatches.html#method.subcommand_matches
750 /// [`ArgMatches::subcommand_name`]: ./struct.ArgMatches.html#method.subcommand_name
751 pub fn subcommand(&self) -> (&str, Option<&ArgMatches<'a>>) {
752 self.subcommand
753 .as_ref()
754 .map_or(("", None), |sc| (&sc.name[..], Some(&sc.matches)))
755 }
756
757 /// Returns a string slice of the usage statement for the [`App`] or [`SubCommand`]
758 ///
759 /// # Examples
760 ///
761 /// ```no_run
762 /// # use clap::{App, Arg, SubCommand};
763 /// let app_m = App::new("myprog")
764 /// .subcommand(SubCommand::with_name("test"))
765 /// .get_matches();
766 ///
767 /// println!("{}", app_m.usage());
768 /// ```
769 /// [`Subcommand`]: ./struct.SubCommand.html
770 /// [`App`]: ./struct.App.html
771 pub fn usage(&self) -> &str {
772 self.usage.as_ref().map_or("", |u| &u[..])
773 }
774}
775
776// The following were taken and adapated from vec_map source
777// repo: https://github.com/contain-rs/vec-map
778// commit: be5e1fa3c26e351761b33010ddbdaf5f05dbcc33
779// license: MIT - Copyright (c) 2015 The Rust Project Developers
780
781/// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of`]
782/// method.
783///
784/// # Examples
785///
786/// ```rust
787/// # use clap::{App, Arg};
788/// let m = App::new("myapp")
789/// .arg(Arg::with_name("output")
790/// .short("o")
791/// .multiple(true)
792/// .takes_value(true))
793/// .get_matches_from(vec!["myapp", "-o", "val1", "val2"]);
794///
795/// let mut values = m.values_of("output").unwrap();
796///
797/// assert_eq!(values.next(), Some("val1"));
798/// assert_eq!(values.next(), Some("val2"));
799/// assert_eq!(values.next(), None);
800/// ```
801/// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of
802#[derive(Debug, Clone)]
803pub struct Values<'a> {
804 iter: Map<Iter<'a, OsString>, fn(&'a OsString) -> &'a str>,
805}
806
807impl<'a> Iterator for Values<'a> {
808 type Item = &'a str;
809
810 fn next(&mut self) -> Option<&'a str> {
811 self.iter.next()
812 }
813 fn size_hint(&self) -> (usize, Option<usize>) {
814 self.iter.size_hint()
815 }
816}
817
818impl<'a> DoubleEndedIterator for Values<'a> {
819 fn next_back(&mut self) -> Option<&'a str> {
820 self.iter.next_back()
821 }
822}
823
824impl<'a> ExactSizeIterator for Values<'a> {}
825
826/// Creates an empty iterator.
827impl<'a> Default for Values<'a> {
828 fn default() -> Self {
829 static EMPTY: [OsString; 0] = [];
830 // This is never called because the iterator is empty:
831 fn to_str_slice(_: &OsString) -> &str {
832 unreachable!()
833 }
834 Values {
835 iter: EMPTY[..].iter().map(to_str_slice),
836 }
837 }
838}
839
840/// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of_os`]
841/// method. Usage of this iterator allows values which contain invalid UTF-8 code points unlike
842/// [`Values`].
843///
844/// # Examples
845///
846#[cfg_attr(not(unix), doc = " ```ignore")]
847#[cfg_attr(unix, doc = " ```")]
848/// # use clap::{App, Arg};
849/// use std::ffi::OsString;
850/// use std::os::unix::ffi::{OsStrExt,OsStringExt};
851///
852/// let m = App::new("utf8")
853/// .arg(Arg::from_usage("<arg> 'some arg'"))
854/// .get_matches_from(vec![OsString::from("myprog"),
855/// // "Hi {0xe9}!"
856/// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
857/// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']);
858/// ```
859/// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os
860/// [`Values`]: ./struct.Values.html
861#[derive(Debug, Clone)]
862pub struct OsValues<'a> {
863 iter: Map<Iter<'a, OsString>, fn(&'a OsString) -> &'a OsStr>,
864}
865
866impl<'a> Iterator for OsValues<'a> {
867 type Item = &'a OsStr;
868
869 fn next(&mut self) -> Option<&'a OsStr> {
870 self.iter.next()
871 }
872 fn size_hint(&self) -> (usize, Option<usize>) {
873 self.iter.size_hint()
874 }
875}
876
877impl<'a> DoubleEndedIterator for OsValues<'a> {
878 fn next_back(&mut self) -> Option<&'a OsStr> {
879 self.iter.next_back()
880 }
881}
882
883impl<'a> ExactSizeIterator for OsValues<'a> {}
884
885/// Creates an empty iterator.
886impl<'a> Default for OsValues<'a> {
887 fn default() -> Self {
888 static EMPTY: [OsString; 0] = [];
889 // This is never called because the iterator is empty:
890 fn to_str_slice(_: &OsString) -> &OsStr {
891 unreachable!()
892 }
893 OsValues {
894 iter: EMPTY[..].iter().map(to_str_slice),
895 }
896 }
897}
898
899/// An iterator for getting multiple indices out of an argument via the [`ArgMatches::indices_of`]
900/// method.
901///
902/// # Examples
903///
904/// ```rust
905/// # use clap::{App, Arg};
906/// let m = App::new("myapp")
907/// .arg(Arg::with_name("output")
908/// .short("o")
909/// .multiple(true)
910/// .takes_value(true))
911/// .get_matches_from(vec!["myapp", "-o", "val1", "val2"]);
912///
913/// let mut indices = m.indices_of("output").unwrap();
914///
915/// assert_eq!(indices.next(), Some(2));
916/// assert_eq!(indices.next(), Some(3));
917/// assert_eq!(indices.next(), None);
918/// ```
919/// [`ArgMatches::indices_of`]: ./struct.ArgMatches.html#method.indices_of
920#[derive(Debug, Clone)]
921pub struct Indices<'a> {
922 // would rather use '_, but: https://github.com/rust-lang/rust/issues/48469
923 iter: Map<Iter<'a, usize>, fn(&'a usize) -> usize>,
924}
925
926impl<'a> Iterator for Indices<'a> {
927 type Item = usize;
928
929 fn next(&mut self) -> Option<usize> {
930 self.iter.next()
931 }
932 fn size_hint(&self) -> (usize, Option<usize>) {
933 self.iter.size_hint()
934 }
935}
936
937impl<'a> DoubleEndedIterator for Indices<'a> {
938 fn next_back(&mut self) -> Option<usize> {
939 self.iter.next_back()
940 }
941}
942
943impl<'a> ExactSizeIterator for Indices<'a> {}
944
945/// Creates an empty iterator.
946impl<'a> Default for Indices<'a> {
947 fn default() -> Self {
948 static EMPTY: [usize; 0] = [];
949 // This is never called because the iterator is empty:
950 fn to_usize(_: &usize) -> usize {
951 unreachable!()
952 }
953 Indices {
954 iter: EMPTY[..].iter().map(to_usize),
955 }
956 }
957}
958
959#[cfg(test)]
960mod tests {
961 use super::*;
962
963 #[test]
964 fn test_default_values() {
965 let mut values: Values = Values::default();
966 assert_eq!(values.next(), None);
967 }
968
969 #[test]
970 fn test_default_values_with_shorter_lifetime() {
971 let matches = ArgMatches::new();
972 let mut values = matches.values_of("").unwrap_or_default();
973 assert_eq!(values.next(), None);
974 }
975
976 #[test]
977 fn test_default_osvalues() {
978 let mut values: OsValues = OsValues::default();
979 assert_eq!(values.next(), None);
980 }
981
982 #[test]
983 fn test_default_osvalues_with_shorter_lifetime() {
984 let matches = ArgMatches::new();
985 let mut values = matches.values_of_os("").unwrap_or_default();
986 assert_eq!(values.next(), None);
987 }
988
989 #[test]
990 fn test_default_indices() {
991 let mut indices: Indices = Indices::default();
992 assert_eq!(indices.next(), None);
993 }
994
995 #[test]
996 fn test_default_indices_with_shorter_lifetime() {
997 let matches = ArgMatches::new();
998 let mut indices = matches.indices_of("").unwrap_or_default();
999 assert_eq!(indices.next(), None);
1000 }
1001}