clap/macros.rs
1/// A convenience macro for loading the YAML file at compile time (relative to the current file,
2/// like modules work). That YAML object can then be passed to this function.
3///
4/// # Panics
5///
6/// The YAML file must be properly formatted or this function will panic!(). A good way to
7/// ensure this doesn't happen is to run your program with the `--help` switch. If this passes
8/// without error, you needn't worry because the YAML is properly formatted.
9///
10/// # Examples
11///
12/// The following example shows how to load a properly formatted YAML file to build an instance
13/// of an `App` struct.
14///
15/// ```ignore
16/// # #[macro_use]
17/// # extern crate clap;
18/// # use clap::App;
19/// # fn main() {
20/// let yml = load_yaml!("app.yml");
21/// let app = App::from_yaml(yml);
22///
23/// // continued logic goes here, such as `app.get_matches()` etc.
24/// # }
25/// ```
26#[cfg(feature = "yaml")]
27#[macro_export]
28macro_rules! load_yaml {
29 ($yml:expr) => (
30 &::clap::YamlLoader::load_from_str(include_str!($yml)).expect("failed to load YAML file")[0]
31 );
32}
33
34/// Convenience macro getting a typed value `T` where `T` implements [`std::str::FromStr`] from an
35/// argument value. This macro returns a `Result<T,String>` which allows you as the developer to
36/// decide what you'd like to do on a failed parse. There are two types of errors, parse failures
37/// and those where the argument wasn't present (such as a non-required argument). You can use
38/// it to get a single value, or a iterator as with the [`ArgMatches::values_of`]
39///
40/// # Examples
41///
42/// ```no_run
43/// # #[macro_use]
44/// # extern crate clap;
45/// # use clap::App;
46/// # fn main() {
47/// let matches = App::new("myapp")
48/// .arg_from_usage("[length] 'Set the length to use as a pos whole num, i.e. 20'")
49/// .get_matches();
50///
51/// let len = value_t!(matches.value_of("length"), u32).unwrap_or_else(|e| e.exit());
52/// let also_len = value_t!(matches, "length", u32).unwrap_or_else(|e| e.exit());
53///
54/// println!("{} + 2: {}", len, len + 2);
55/// # }
56/// ```
57/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
58/// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of
59/// [`Result<T,String>`]: https://doc.rust-lang.org/std/result/enum.Result.html
60#[macro_export]
61macro_rules! value_t {
62 ($m:ident, $v:expr, $t:ty) => {
63 value_t!($m.value_of($v), $t)
64 };
65 ($m:ident.value_of($v:expr), $t:ty) => {
66 if let Some(v) = $m.value_of($v) {
67 match v.parse::<$t>() {
68 Ok(val) => Ok(val),
69 Err(_) =>
70 Err(::clap::Error::value_validation_auto(
71 format!("The argument '{}' isn't a valid value", v))),
72 }
73 } else {
74 Err(::clap::Error::argument_not_found_auto($v))
75 }
76 };
77}
78
79/// Convenience macro getting a typed value `T` where `T` implements [`std::str::FromStr`] or
80/// exiting upon error, instead of returning a [`Result`] type.
81///
82/// **NOTE:** This macro is for backwards compatibility sake. Prefer
83/// [`value_t!(/* ... */).unwrap_or_else(|e| e.exit())`]
84///
85/// # Examples
86///
87/// ```no_run
88/// # #[macro_use]
89/// # extern crate clap;
90/// # use clap::App;
91/// # fn main() {
92/// let matches = App::new("myapp")
93/// .arg_from_usage("[length] 'Set the length to use as a pos whole num, i.e. 20'")
94/// .get_matches();
95///
96/// let len = value_t_or_exit!(matches.value_of("length"), u32);
97/// let also_len = value_t_or_exit!(matches, "length", u32);
98///
99/// println!("{} + 2: {}", len, len + 2);
100/// # }
101/// ```
102/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
103/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
104/// [`value_t!(/* ... */).unwrap_or_else(|e| e.exit())`]: ./macro.value_t!.html
105#[macro_export]
106macro_rules! value_t_or_exit {
107 ($m:ident, $v:expr, $t:ty) => {
108 value_t_or_exit!($m.value_of($v), $t)
109 };
110 ($m:ident.value_of($v:expr), $t:ty) => {
111 if let Some(v) = $m.value_of($v) {
112 match v.parse::<$t>() {
113 Ok(val) => val,
114 Err(_) =>
115 ::clap::Error::value_validation_auto(
116 format!("The argument '{}' isn't a valid value", v)).exit(),
117 }
118 } else {
119 ::clap::Error::argument_not_found_auto($v).exit()
120 }
121 };
122}
123
124/// Convenience macro getting a typed value [`Vec<T>`] where `T` implements [`std::str::FromStr`]
125/// This macro returns a [`clap::Result<Vec<T>>`] which allows you as the developer to decide
126/// what you'd like to do on a failed parse.
127///
128/// # Examples
129///
130/// ```no_run
131/// # #[macro_use]
132/// # extern crate clap;
133/// # use clap::App;
134/// # fn main() {
135/// let matches = App::new("myapp")
136/// .arg_from_usage("[seq]... 'A sequence of pos whole nums, i.e. 20 45'")
137/// .get_matches();
138///
139/// let vals = values_t!(matches.values_of("seq"), u32).unwrap_or_else(|e| e.exit());
140/// for v in &vals {
141/// println!("{} + 2: {}", v, v + 2);
142/// }
143///
144/// let vals = values_t!(matches, "seq", u32).unwrap_or_else(|e| e.exit());
145/// for v in &vals {
146/// println!("{} + 2: {}", v, v + 2);
147/// }
148/// # }
149/// ```
150/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
151/// [`Vec<T>`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
152/// [`clap::Result<Vec<T>>`]: ./type.Result.html
153#[macro_export]
154macro_rules! values_t {
155 ($m:ident, $v:expr, $t:ty) => {
156 values_t!($m.values_of($v), $t)
157 };
158 ($m:ident.values_of($v:expr), $t:ty) => {
159 if let Some(vals) = $m.values_of($v) {
160 let mut tmp = vec![];
161 let mut err = None;
162 for pv in vals {
163 match pv.parse::<$t>() {
164 Ok(rv) => tmp.push(rv),
165 Err(..) => {
166 err = Some(::clap::Error::value_validation_auto(
167 format!("The argument '{}' isn't a valid value", pv)));
168 break
169 }
170 }
171 }
172 match err {
173 Some(e) => Err(e),
174 None => Ok(tmp),
175 }
176 } else {
177 Err(::clap::Error::argument_not_found_auto($v))
178 }
179 };
180}
181
182/// Convenience macro getting a typed value [`Vec<T>`] where `T` implements [`std::str::FromStr`]
183/// or exiting upon error.
184///
185/// **NOTE:** This macro is for backwards compatibility sake. Prefer
186/// [`values_t!(/* ... */).unwrap_or_else(|e| e.exit())`]
187///
188/// # Examples
189///
190/// ```no_run
191/// # #[macro_use]
192/// # extern crate clap;
193/// # use clap::App;
194/// # fn main() {
195/// let matches = App::new("myapp")
196/// .arg_from_usage("[seq]... 'A sequence of pos whole nums, i.e. 20 45'")
197/// .get_matches();
198///
199/// let vals = values_t_or_exit!(matches.values_of("seq"), u32);
200/// for v in &vals {
201/// println!("{} + 2: {}", v, v + 2);
202/// }
203///
204/// // type for example only
205/// let vals: Vec<u32> = values_t_or_exit!(matches, "seq", u32);
206/// for v in &vals {
207/// println!("{} + 2: {}", v, v + 2);
208/// }
209/// # }
210/// ```
211/// [`values_t!(/* ... */).unwrap_or_else(|e| e.exit())`]: ./macro.values_t!.html
212/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
213/// [`Vec<T>`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
214#[macro_export]
215macro_rules! values_t_or_exit {
216 ($m:ident, $v:expr, $t:ty) => {
217 values_t_or_exit!($m.values_of($v), $t)
218 };
219 ($m:ident.values_of($v:expr), $t:ty) => {
220 if let Some(vals) = $m.values_of($v) {
221 vals.map(|v| v.parse::<$t>().unwrap_or_else(|_|{
222 ::clap::Error::value_validation_auto(
223 format!("One or more arguments aren't valid values")).exit()
224 })).collect::<Vec<$t>>()
225 } else {
226 ::clap::Error::argument_not_found_auto($v).exit()
227 }
228 };
229}
230
231// _clap_count_exprs! is derived from https://github.com/DanielKeep/rust-grabbag
232// commit: 82a35ca5d9a04c3b920622d542104e3310ee5b07
233// License: MIT
234// Copyright ⓒ 2015 grabbag contributors.
235// Licensed under the MIT license (see LICENSE or <http://opensource.org
236// /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
237// <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
238// files in the project carrying such notice may not be copied, modified,
239// or distributed except according to those terms.
240//
241/// Counts the number of comma-delimited expressions passed to it. The result is a compile-time
242/// evaluable expression, suitable for use as a static array size, or the value of a `const`.
243///
244/// # Examples
245///
246/// ```
247/// # #[macro_use] extern crate clap;
248/// # fn main() {
249/// const COUNT: usize = _clap_count_exprs!(a, 5+1, "hi there!".into_string());
250/// assert_eq!(COUNT, 3);
251/// # }
252/// ```
253#[macro_export]
254macro_rules! _clap_count_exprs {
255 () => { 0 };
256 ($e:expr) => { 1 };
257 ($e:expr, $($es:expr),+) => { 1 + $crate::_clap_count_exprs!($($es),*) };
258}
259
260/// Convenience macro to generate more complete enums with variants to be used as a type when
261/// parsing arguments. This enum also provides a `variants()` function which can be used to
262/// retrieve a `Vec<&'static str>` of the variant names, as well as implementing [`FromStr`] and
263/// [`Display`] automatically.
264///
265/// **NOTE:** Case insensitivity is supported for ASCII characters only. It's highly recommended to
266/// use [`Arg::case_insensitive(true)`] for args that will be used with these enums
267///
268/// **NOTE:** This macro automatically implements [`std::str::FromStr`] and [`std::fmt::Display`]
269///
270/// **NOTE:** These enums support pub (or not) and uses of the `#[derive()]` traits
271///
272/// # Examples
273///
274/// ```rust
275/// # #[macro_use]
276/// # extern crate clap;
277/// # use clap::{App, Arg};
278/// arg_enum!{
279/// #[derive(PartialEq, Debug)]
280/// pub enum Foo {
281/// Bar,
282/// Baz,
283/// Qux
284/// }
285/// }
286/// // Foo enum can now be used via Foo::Bar, or Foo::Baz, etc
287/// // and implements std::str::FromStr to use with the value_t! macros
288/// fn main() {
289/// let m = App::new("app")
290/// .arg(Arg::from_usage("<foo> 'the foo'")
291/// .possible_values(&Foo::variants())
292/// .case_insensitive(true))
293/// .get_matches_from(vec![
294/// "app", "baz"
295/// ]);
296/// let f = value_t!(m, "foo", Foo).unwrap_or_else(|e| e.exit());
297///
298/// assert_eq!(f, Foo::Baz);
299/// }
300/// ```
301/// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
302/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
303/// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
304/// [`std::fmt::Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
305/// [`Arg::case_insensitive(true)`]: ./struct.Arg.html#method.case_insensitive
306#[macro_export]
307macro_rules! arg_enum {
308 (@as_item $($i:item)*) => ($($i)*);
309 (@impls ( $($tts:tt)* ) -> ($e:ident, $($v:ident),+)) => {
310 arg_enum!(@as_item
311 $($tts)*
312
313 impl ::std::str::FromStr for $e {
314 type Err = String;
315
316 fn from_str(s: &str) -> ::std::result::Result<Self,Self::Err> {
317 #[allow(deprecated, unused_imports)]
318 use ::std::ascii::AsciiExt;
319 match s {
320 $(stringify!($v) |
321 _ if s.eq_ignore_ascii_case(stringify!($v)) => Ok($e::$v)),+,
322 _ => Err({
323 let v = vec![
324 $(stringify!($v),)+
325 ];
326 format!("valid values: {}",
327 v.join(", "))
328 }),
329 }
330 }
331 }
332 impl ::std::fmt::Display for $e {
333 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
334 match *self {
335 $($e::$v => write!(f, stringify!($v)),)+
336 }
337 }
338 }
339 impl $e {
340 #[allow(dead_code)]
341 pub fn variants() -> [&'static str; $crate::_clap_count_exprs!($(stringify!($v)),+)] {
342 [
343 $(stringify!($v),)+
344 ]
345 }
346 });
347 };
348 ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => {
349 arg_enum!(@impls
350 ($(#[$($m),+])+
351 pub enum $e {
352 $($v$(=$val)*),+
353 }) -> ($e, $($v),+)
354 );
355 };
356 ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => {
357 arg_enum!(@impls
358 ($(#[$($m),+])+
359 pub enum $e {
360 $($v$(=$val)*),+
361 }) -> ($e, $($v),+)
362 );
363 };
364 ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => {
365 arg_enum!(@impls
366 ($(#[$($m),+])+
367 enum $e {
368 $($v$(=$val)*),+
369 }) -> ($e, $($v),+)
370 );
371 };
372 ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => {
373 arg_enum!(@impls
374 ($(#[$($m),+])+
375 enum $e {
376 $($v$(=$val)*),+
377 }) -> ($e, $($v),+)
378 );
379 };
380 (pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => {
381 arg_enum!(@impls
382 (pub enum $e {
383 $($v$(=$val)*),+
384 }) -> ($e, $($v),+)
385 );
386 };
387 (pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => {
388 arg_enum!(@impls
389 (pub enum $e {
390 $($v$(=$val)*),+
391 }) -> ($e, $($v),+)
392 );
393 };
394 (enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => {
395 arg_enum!(@impls
396 (enum $e {
397 $($v$(=$val)*),+
398 }) -> ($e, $($v),+)
399 );
400 };
401 (enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => {
402 arg_enum!(@impls
403 (enum $e {
404 $($v$(=$val)*),+
405 }) -> ($e, $($v),+)
406 );
407 };
408}
409
410/// Allows you to pull the version from your Cargo.toml at compile time as
411/// `MAJOR.MINOR.PATCH_PKGVERSION_PRE`
412///
413/// # Examples
414///
415/// ```no_run
416/// # #[macro_use]
417/// # extern crate clap;
418/// # use clap::App;
419/// # fn main() {
420/// let m = App::new("app")
421/// .version(crate_version!())
422/// .get_matches();
423/// # }
424/// ```
425#[cfg(not(feature = "no_cargo"))]
426#[macro_export]
427macro_rules! crate_version {
428 () => {
429 env!("CARGO_PKG_VERSION")
430 };
431}
432
433/// Allows you to pull the authors for the app from your Cargo.toml at
434/// compile time in the form:
435/// `"author1 lastname <author1@example.com>:author2 lastname <author2@example.com>"`
436///
437/// You can replace the colons with a custom separator by supplying a
438/// replacement string, so, for example,
439/// `crate_authors!(",\n")` would become
440/// `"author1 lastname <author1@example.com>,\nauthor2 lastname <author2@example.com>,\nauthor3 lastname <author3@example.com>"`
441///
442/// # Examples
443///
444/// ```no_run
445/// # #[macro_use]
446/// # extern crate clap;
447/// # use clap::App;
448/// # fn main() {
449/// let m = App::new("app")
450/// .author(crate_authors!("\n"))
451/// .get_matches();
452/// # }
453/// ```
454#[cfg(not(feature = "no_cargo"))]
455#[macro_export]
456macro_rules! crate_authors {
457 ($sep:expr) => {{
458 use std::ops::Deref;
459 use std::sync::{ONCE_INIT, Once};
460
461 #[allow(missing_copy_implementations)]
462 #[allow(dead_code)]
463 struct CargoAuthors { __private_field: () };
464
465 impl Deref for CargoAuthors {
466 type Target = str;
467
468 #[allow(unsafe_code)]
469 fn deref(&self) -> &'static str {
470 static ONCE: Once = ONCE_INIT;
471 static mut VALUE: *const String = 0 as *const String;
472
473 unsafe {
474 ONCE.call_once(|| {
475 let s = env!("CARGO_PKG_AUTHORS").replace(':', $sep);
476 VALUE = Box::into_raw(Box::new(s));
477 });
478
479 &(*VALUE)[..]
480 }
481 }
482 }
483
484 &*CargoAuthors { __private_field: () }
485 }};
486 () => {
487 env!("CARGO_PKG_AUTHORS")
488 };
489}
490
491/// Allows you to pull the description from your Cargo.toml at compile time.
492///
493/// # Examples
494///
495/// ```no_run
496/// # #[macro_use]
497/// # extern crate clap;
498/// # use clap::App;
499/// # fn main() {
500/// let m = App::new("app")
501/// .about(crate_description!())
502/// .get_matches();
503/// # }
504/// ```
505#[cfg(not(feature = "no_cargo"))]
506#[macro_export]
507macro_rules! crate_description {
508 () => {
509 env!("CARGO_PKG_DESCRIPTION")
510 };
511}
512
513/// Allows you to pull the name from your Cargo.toml at compile time.
514///
515/// # Examples
516///
517/// ```no_run
518/// # #[macro_use]
519/// # extern crate clap;
520/// # use clap::App;
521/// # fn main() {
522/// let m = App::new(crate_name!())
523/// .get_matches();
524/// # }
525/// ```
526#[cfg(not(feature = "no_cargo"))]
527#[macro_export]
528macro_rules! crate_name {
529 () => {
530 env!("CARGO_PKG_NAME")
531 };
532}
533
534/// Allows you to build the `App` instance from your Cargo.toml at compile time.
535///
536/// Equivalent to using the `crate_*!` macros with their respective fields.
537///
538/// Provided separator is for the [`crate_authors!`](macro.crate_authors.html) macro,
539/// refer to the documentation therefor.
540///
541/// **NOTE:** Changing the values in your `Cargo.toml` does not trigger a re-build automatically,
542/// and therefore won't change the generated output until you recompile.
543///
544/// **Pro Tip:** In some cases you can "trick" the compiler into triggering a rebuild when your
545/// `Cargo.toml` is changed by including this in your `src/main.rs` file
546/// `include_str!("../Cargo.toml");`
547///
548/// # Examples
549///
550/// ```no_run
551/// # #[macro_use]
552/// # extern crate clap;
553/// # fn main() {
554/// let m = app_from_crate!().get_matches();
555/// # }
556/// ```
557#[cfg(not(feature = "no_cargo"))]
558#[macro_export]
559macro_rules! app_from_crate {
560 () => {
561 $crate::App::new(crate_name!())
562 .version(crate_version!())
563 .author(crate_authors!())
564 .about(crate_description!())
565 };
566 ($sep:expr) => {
567 $crate::App::new(crate_name!())
568 .version(crate_version!())
569 .author(crate_authors!($sep))
570 .about(crate_description!())
571 };
572}
573
574/// Build `App`, `Arg`s, `SubCommand`s and `Group`s with Usage-string like input
575/// but without the associated parsing runtime cost.
576///
577/// `clap_app!` also supports several shorthand syntaxes.
578///
579/// # Examples
580///
581/// ```no_run
582/// # #[macro_use]
583/// # extern crate clap;
584/// # fn main() {
585/// let matches = clap_app!(myapp =>
586/// (version: "1.0")
587/// (author: "Kevin K. <kbknapp@gmail.com>")
588/// (about: "Does awesome things")
589/// (@arg CONFIG: -c --config +takes_value "Sets a custom config file")
590/// (@arg INPUT: +required "Sets the input file to use")
591/// (@arg debug: -d ... "Sets the level of debugging information")
592/// (@group difficulty =>
593/// (@arg hard: -h --hard "Sets hard mode")
594/// (@arg normal: -n --normal "Sets normal mode")
595/// (@arg easy: -e --easy "Sets easy mode")
596/// )
597/// (@subcommand test =>
598/// (about: "controls testing features")
599/// (version: "1.3")
600/// (author: "Someone E. <someone_else@other.com>")
601/// (@arg verbose: -v --verbose "Print test information verbosely")
602/// )
603/// )
604/// .get_matches();
605/// # }
606/// ```
607/// # Shorthand Syntax for Args
608///
609/// * A single hyphen followed by a character (such as `-c`) sets the [`Arg::short`]
610/// * A double hyphen followed by a character or word (such as `--config`) sets [`Arg::long`]
611/// * If one wishes to use a [`Arg::long`] with a hyphen inside (i.e. `--config-file`), you
612/// must use `--("config-file")` due to limitations of the Rust macro system.
613/// * Three dots (`...`) sets [`Arg::multiple(true)`]
614/// * Angled brackets after either a short or long will set [`Arg::value_name`] and
615/// `Arg::required(true)` such as `--config <FILE>` = `Arg::value_name("FILE")` and
616/// `Arg::required(true)`
617/// * Square brackets after either a short or long will set [`Arg::value_name`] and
618/// `Arg::required(false)` such as `--config [FILE]` = `Arg::value_name("FILE")` and
619/// `Arg::required(false)`
620/// * There are short hand syntaxes for Arg methods that accept booleans
621/// * A plus sign will set that method to `true` such as `+required` = `Arg::required(true)`
622/// * An exclamation will set that method to `false` such as `!required` = `Arg::required(false)`
623/// * A `#{min, max}` will set [`Arg::min_values(min)`] and [`Arg::max_values(max)`]
624/// * An asterisk (`*`) will set `Arg::required(true)`
625/// * Curly brackets around a `fn` will set [`Arg::validator`] as in `{fn}` = `Arg::validator(fn)`
626/// * An Arg method that accepts a string followed by square brackets will set that method such as
627/// `conflicts_with[FOO]` will set `Arg::conflicts_with("FOO")` (note the lack of quotes around
628/// `FOO` in the macro)
629/// * An Arg method that takes a string and can be set multiple times (such as
630/// [`Arg::conflicts_with`]) followed by square brackets and a list of values separated by spaces
631/// will set that method such as `conflicts_with[FOO BAR BAZ]` will set
632/// `Arg::conflicts_with("FOO")`, `Arg::conflicts_with("BAR")`, and `Arg::conflicts_with("BAZ")`
633/// (note the lack of quotes around the values in the macro)
634///
635/// # Shorthand Syntax for Groups
636///
637/// * There are short hand syntaxes for `ArgGroup` methods that accept booleans
638/// * A plus sign will set that method to `true` such as `+required` = `ArgGroup::required(true)`
639/// * An exclamation will set that method to `false` such as `!required` = `ArgGroup::required(false)`
640///
641/// [`Arg::short`]: ./struct.Arg.html#method.short
642/// [`Arg::long`]: ./struct.Arg.html#method.long
643/// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
644/// [`Arg::value_name`]: ./struct.Arg.html#method.value_name
645/// [`Arg::min_values(min)`]: ./struct.Arg.html#method.min_values
646/// [`Arg::max_values(max)`]: ./struct.Arg.html#method.max_values
647/// [`Arg::validator`]: ./struct.Arg.html#method.validator
648/// [`Arg::conflicts_with`]: ./struct.Arg.html#method.conflicts_with
649#[macro_export]
650macro_rules! clap_app {
651 (@app ($builder:expr)) => { $builder };
652 (@app ($builder:expr) (@arg ($name:expr): $($tail:tt)*) $($tt:tt)*) => {
653 clap_app!{ @app
654 ($builder.arg(
655 clap_app!{ @arg ($crate::Arg::with_name($name)) (-) $($tail)* }))
656 $($tt)*
657 }
658 };
659 (@app ($builder:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => {
660 clap_app!{ @app
661 ($builder.arg(
662 clap_app!{ @arg ($crate::Arg::with_name(stringify!($name))) (-) $($tail)* }))
663 $($tt)*
664 }
665 };
666 (@app ($builder:expr) (@setting $setting:ident) $($tt:tt)*) => {
667 clap_app!{ @app
668 ($builder.setting($crate::AppSettings::$setting))
669 $($tt)*
670 }
671 };
672// Treat the application builder as an argument to set its attributes
673 (@app ($builder:expr) (@attributes $($attr:tt)*) $($tt:tt)*) => {
674 clap_app!{ @app (clap_app!{ @arg ($builder) $($attr)* }) $($tt)* }
675 };
676 (@app ($builder:expr) (@group $name:ident => $($tail:tt)*) $($tt:tt)*) => {
677 clap_app!{ @app
678 (clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name))) $($tail)* })
679 $($tt)*
680 }
681 };
682 (@app ($builder:expr) (@group $name:ident !$ident:ident => $($tail:tt)*) $($tt:tt)*) => {
683 clap_app!{ @app
684 (clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name)).$ident(false)) $($tail)* })
685 $($tt)*
686 }
687 };
688 (@app ($builder:expr) (@group $name:ident +$ident:ident => $($tail:tt)*) $($tt:tt)*) => {
689 clap_app!{ @app
690 (clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name)).$ident(true)) $($tail)* })
691 $($tt)*
692 }
693 };
694// Handle subcommand creation
695 (@app ($builder:expr) (@subcommand $name:ident => $($tail:tt)*) $($tt:tt)*) => {
696 clap_app!{ @app
697 ($builder.subcommand(
698 clap_app!{ @app ($crate::SubCommand::with_name(stringify!($name))) $($tail)* }
699 ))
700 $($tt)*
701 }
702 };
703// Yaml like function calls - used for setting various meta directly against the app
704 (@app ($builder:expr) ($ident:ident: $($v:expr),*) $($tt:tt)*) => {
705// clap_app!{ @app ($builder.$ident($($v),*)) $($tt)* }
706 clap_app!{ @app
707 ($builder.$ident($($v),*))
708 $($tt)*
709 }
710 };
711
712// Add members to group and continue argument handling with the parent builder
713 (@group ($builder:expr, $group:expr)) => { $builder.group($group) };
714 // Treat the group builder as an argument to set its attributes
715 (@group ($builder:expr, $group:expr) (@attributes $($attr:tt)*) $($tt:tt)*) => {
716 clap_app!{ @group ($builder, clap_app!{ @arg ($group) (-) $($attr)* }) $($tt)* }
717 };
718 (@group ($builder:expr, $group:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => {
719 clap_app!{ @group
720 (clap_app!{ @app ($builder) (@arg $name: $($tail)*) },
721 $group.arg(stringify!($name)))
722 $($tt)*
723 }
724 };
725
726// No more tokens to munch
727 (@arg ($arg:expr) $modes:tt) => { $arg };
728// Shorthand tokens influenced by the usage_string
729 (@arg ($arg:expr) $modes:tt --($long:expr) $($tail:tt)*) => {
730 clap_app!{ @arg ($arg.long($long)) $modes $($tail)* }
731 };
732 (@arg ($arg:expr) $modes:tt --$long:ident $($tail:tt)*) => {
733 clap_app!{ @arg ($arg.long(stringify!($long))) $modes $($tail)* }
734 };
735 (@arg ($arg:expr) $modes:tt -$short:ident $($tail:tt)*) => {
736 clap_app!{ @arg ($arg.short(stringify!($short))) $modes $($tail)* }
737 };
738 (@arg ($arg:expr) (-) <$var:ident> $($tail:tt)*) => {
739 clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value +required $($tail)* }
740 };
741 (@arg ($arg:expr) (+) <$var:ident> $($tail:tt)*) => {
742 clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* }
743 };
744 (@arg ($arg:expr) (-) [$var:ident] $($tail:tt)*) => {
745 clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value $($tail)* }
746 };
747 (@arg ($arg:expr) (+) [$var:ident] $($tail:tt)*) => {
748 clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* }
749 };
750 (@arg ($arg:expr) $modes:tt ... $($tail:tt)*) => {
751 clap_app!{ @arg ($arg) $modes +multiple $($tail)* }
752 };
753// Shorthand magic
754 (@arg ($arg:expr) $modes:tt #{$n:expr, $m:expr} $($tail:tt)*) => {
755 clap_app!{ @arg ($arg) $modes min_values($n) max_values($m) $($tail)* }
756 };
757 (@arg ($arg:expr) $modes:tt * $($tail:tt)*) => {
758 clap_app!{ @arg ($arg) $modes +required $($tail)* }
759 };
760// !foo -> .foo(false)
761 (@arg ($arg:expr) $modes:tt !$ident:ident $($tail:tt)*) => {
762 clap_app!{ @arg ($arg.$ident(false)) $modes $($tail)* }
763 };
764// +foo -> .foo(true)
765 (@arg ($arg:expr) $modes:tt +$ident:ident $($tail:tt)*) => {
766 clap_app!{ @arg ($arg.$ident(true)) $modes $($tail)* }
767 };
768// Validator
769 (@arg ($arg:expr) $modes:tt {$fn_:expr} $($tail:tt)*) => {
770 clap_app!{ @arg ($arg.validator($fn_)) $modes $($tail)* }
771 };
772 (@as_expr $expr:expr) => { $expr };
773// Help
774 (@arg ($arg:expr) $modes:tt $desc:tt) => { $arg.help(clap_app!{ @as_expr $desc }) };
775// Handle functions that need to be called multiple times for each argument
776 (@arg ($arg:expr) $modes:tt $ident:ident[$($target:ident)*] $($tail:tt)*) => {
777 clap_app!{ @arg ($arg $( .$ident(stringify!($target)) )*) $modes $($tail)* }
778 };
779// Inherit builder's functions, e.g. `index(2)`, `requires_if("val", "arg")`
780 (@arg ($arg:expr) $modes:tt $ident:ident($($expr:expr),*) $($tail:tt)*) => {
781 clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* }
782 };
783// Inherit builder's functions with trailing comma, e.g. `index(2,)`, `requires_if("val", "arg",)`
784 (@arg ($arg:expr) $modes:tt $ident:ident($($expr:expr,)*) $($tail:tt)*) => {
785 clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* }
786 };
787
788// Build a subcommand outside of an app.
789 (@subcommand $name:ident => $($tail:tt)*) => {
790 clap_app!{ @app ($crate::SubCommand::with_name(stringify!($name))) $($tail)* }
791 };
792// Start the magic
793 (($name:expr) => $($tail:tt)*) => {{
794 clap_app!{ @app ($crate::App::new($name)) $($tail)*}
795 }};
796
797 ($name:ident => $($tail:tt)*) => {{
798 clap_app!{ @app ($crate::App::new(stringify!($name))) $($tail)*}
799 }};
800}
801
802macro_rules! impl_settings {
803 ($n:ident, $($v:ident => $c:path),+) => {
804 pub fn set(&mut self, s: $n) {
805 match s {
806 $($n::$v => self.0.insert($c)),+
807 }
808 }
809
810 pub fn unset(&mut self, s: $n) {
811 match s {
812 $($n::$v => self.0.remove($c)),+
813 }
814 }
815
816 pub fn is_set(&self, s: $n) -> bool {
817 match s {
818 $($n::$v => self.0.contains($c)),+
819 }
820 }
821 };
822}
823
824// Convenience for writing to stderr thanks to https://github.com/BurntSushi
825macro_rules! wlnerr(
826 ($($arg:tt)*) => ({
827 use std::io::{Write, stderr};
828 writeln!(&mut stderr(), $($arg)*).ok();
829 })
830);
831
832#[cfg(feature = "debug")]
833#[cfg_attr(feature = "debug", macro_use)]
834#[cfg_attr(feature = "debug", allow(unused_macros))]
835mod debug_macros {
836 macro_rules! debugln {
837 ($fmt:expr) => (println!(concat!("DEBUG:clap:", $fmt)));
838 ($fmt:expr, $($arg:tt)*) => (println!(concat!("DEBUG:clap:",$fmt), $($arg)*));
839 }
840 macro_rules! sdebugln {
841 ($fmt:expr) => (println!($fmt));
842 ($fmt:expr, $($arg:tt)*) => (println!($fmt, $($arg)*));
843 }
844 macro_rules! debug {
845 ($fmt:expr) => (print!(concat!("DEBUG:clap:", $fmt)));
846 ($fmt:expr, $($arg:tt)*) => (print!(concat!("DEBUG:clap:",$fmt), $($arg)*));
847 }
848 macro_rules! sdebug {
849 ($fmt:expr) => (print!($fmt));
850 ($fmt:expr, $($arg:tt)*) => (print!($fmt, $($arg)*));
851 }
852}
853
854#[cfg(not(feature = "debug"))]
855#[cfg_attr(not(feature = "debug"), macro_use)]
856mod debug_macros {
857 macro_rules! debugln {
858 ($fmt:expr) => ();
859 ($fmt:expr, $($arg:tt)*) => ();
860 }
861 macro_rules! sdebugln {
862 ($fmt:expr) => ();
863 ($fmt:expr, $($arg:tt)*) => ();
864 }
865 macro_rules! debug {
866 ($fmt:expr) => ();
867 ($fmt:expr, $($arg:tt)*) => ();
868 }
869}
870
871// Helper/deduplication macro for printing the correct number of spaces in help messages
872// used in:
873// src/args/arg_builder/*.rs
874// src/app/mod.rs
875macro_rules! write_nspaces {
876 ($dst:expr, $num:expr) => ({
877 debugln!("write_spaces!: num={}", $num);
878 for _ in 0..$num {
879 $dst.write_all(b" ")?;
880 }
881 })
882}
883
884// convenience macro for remove an item from a vec
885//macro_rules! vec_remove_all {
886// ($vec:expr, $to_rem:expr) => {
887// debugln!("vec_remove_all! to_rem={:?}", $to_rem);
888// for i in (0 .. $vec.len()).rev() {
889// let should_remove = $to_rem.any(|name| name == &$vec[i]);
890// if should_remove { $vec.swap_remove(i); }
891// }
892// };
893//}
894macro_rules! find_from {
895 ($_self:expr, $arg_name:expr, $from:ident, $matcher:expr) => {{
896 let mut ret = None;
897 for k in $matcher.arg_names() {
898 if let Some(f) = find_by_name!($_self, k, flags, iter) {
899 if let Some(ref v) = f.$from() {
900 if v.contains($arg_name) {
901 ret = Some(f.to_string());
902 }
903 }
904 }
905 if let Some(o) = find_by_name!($_self, k, opts, iter) {
906 if let Some(ref v) = o.$from() {
907 if v.contains(&$arg_name) {
908 ret = Some(o.to_string());
909 }
910 }
911 }
912 if let Some(pos) = find_by_name!($_self, k, positionals, values) {
913 if let Some(ref v) = pos.$from() {
914 if v.contains($arg_name) {
915 ret = Some(pos.b.name.to_owned());
916 }
917 }
918 }
919 }
920 ret
921 }};
922}
923
924//macro_rules! find_name_from {
925// ($_self:expr, $arg_name:expr, $from:ident, $matcher:expr) => {{
926// let mut ret = None;
927// for k in $matcher.arg_names() {
928// if let Some(f) = find_by_name!($_self, k, flags, iter) {
929// if let Some(ref v) = f.$from() {
930// if v.contains($arg_name) {
931// ret = Some(f.b.name);
932// }
933// }
934// }
935// if let Some(o) = find_by_name!($_self, k, opts, iter) {
936// if let Some(ref v) = o.$from() {
937// if v.contains(&$arg_name) {
938// ret = Some(o.b.name);
939// }
940// }
941// }
942// if let Some(pos) = find_by_name!($_self, k, positionals, values) {
943// if let Some(ref v) = pos.$from() {
944// if v.contains($arg_name) {
945// ret = Some(pos.b.name);
946// }
947// }
948// }
949// }
950// ret
951// }};
952//}
953
954
955macro_rules! find_any_by_name {
956 ($p:expr, $name:expr) => {
957 {
958 fn as_trait_obj<'a, 'b, T: AnyArg<'a, 'b>>(x: &T) -> &AnyArg<'a, 'b> { x }
959 find_by_name!($p, $name, flags, iter).map(as_trait_obj).or(
960 find_by_name!($p, $name, opts, iter).map(as_trait_obj).or(
961 find_by_name!($p, $name, positionals, values).map(as_trait_obj)
962 )
963 )
964 }
965 }
966}
967// Finds an arg by name
968macro_rules! find_by_name {
969 ($p:expr, $name:expr, $what:ident, $how:ident) => {
970 $p.$what.$how().find(|o| o.b.name == $name)
971 }
972}
973
974// Finds an option including if it's aliased
975macro_rules! find_opt_by_long {
976 (@os $_self:ident, $long:expr) => {{
977 _find_by_long!($_self, $long, opts)
978 }};
979 ($_self:ident, $long:expr) => {{
980 _find_by_long!($_self, $long, opts)
981 }};
982}
983
984macro_rules! find_flag_by_long {
985 (@os $_self:ident, $long:expr) => {{
986 _find_by_long!($_self, $long, flags)
987 }};
988 ($_self:ident, $long:expr) => {{
989 _find_by_long!($_self, $long, flags)
990 }};
991}
992
993macro_rules! _find_by_long {
994 ($_self:ident, $long:expr, $what:ident) => {{
995 $_self.$what
996 .iter()
997 .filter(|a| a.s.long.is_some())
998 .find(|a| {
999 a.s.long.unwrap() == $long ||
1000 (a.s.aliases.is_some() &&
1001 a.s
1002 .aliases
1003 .as_ref()
1004 .unwrap()
1005 .iter()
1006 .any(|&(alias, _)| alias == $long))
1007 })
1008 }}
1009}
1010
1011// Finds an option
1012macro_rules! find_opt_by_short {
1013 ($_self:ident, $short:expr) => {{
1014 _find_by_short!($_self, $short, opts)
1015 }}
1016}
1017
1018macro_rules! find_flag_by_short {
1019 ($_self:ident, $short:expr) => {{
1020 _find_by_short!($_self, $short, flags)
1021 }}
1022}
1023
1024macro_rules! _find_by_short {
1025 ($_self:ident, $short:expr, $what:ident) => {{
1026 $_self.$what
1027 .iter()
1028 .filter(|a| a.s.short.is_some())
1029 .find(|a| a.s.short.unwrap() == $short)
1030 }}
1031}
1032
1033macro_rules! find_subcmd {
1034 ($_self:expr, $sc:expr) => {{
1035 $_self.subcommands
1036 .iter()
1037 .find(|s| {
1038 &*s.p.meta.name == $sc ||
1039 (s.p.meta.aliases.is_some() &&
1040 s.p
1041 .meta
1042 .aliases
1043 .as_ref()
1044 .unwrap()
1045 .iter()
1046 .any(|&(n, _)| n == $sc))
1047 })
1048 }};
1049}
1050
1051macro_rules! shorts {
1052 ($_self:ident) => {{
1053 _shorts_longs!($_self, short)
1054 }};
1055}
1056
1057
1058macro_rules! longs {
1059 ($_self:ident) => {{
1060 _shorts_longs!($_self, long)
1061 }};
1062}
1063
1064macro_rules! _shorts_longs {
1065 ($_self:ident, $what:ident) => {{
1066 $_self.flags
1067 .iter()
1068 .filter(|f| f.s.$what.is_some())
1069 .map(|f| f.s.$what.as_ref().unwrap())
1070 .chain($_self.opts.iter()
1071 .filter(|o| o.s.$what.is_some())
1072 .map(|o| o.s.$what.as_ref().unwrap()))
1073 }};
1074}
1075
1076macro_rules! arg_names {
1077 ($_self:ident) => {{
1078 _names!(@args $_self)
1079 }};
1080}
1081
1082macro_rules! sc_names {
1083 ($_self:ident) => {{
1084 _names!(@sc $_self)
1085 }};
1086}
1087
1088macro_rules! _names {
1089 (@args $_self:ident) => {{
1090 $_self.flags
1091 .iter()
1092 .map(|f| &*f.b.name)
1093 .chain($_self.opts.iter()
1094 .map(|o| &*o.b.name)
1095 .chain($_self.positionals.values()
1096 .map(|p| &*p.b.name)))
1097 }};
1098 (@sc $_self:ident) => {{
1099 $_self.subcommands
1100 .iter()
1101 .map(|s| &*s.p.meta.name)
1102 .chain($_self.subcommands
1103 .iter()
1104 .filter(|s| s.p.meta.aliases.is_some())
1105 .flat_map(|s| s.p.meta.aliases.as_ref().unwrap().iter().map(|&(n, _)| n)))
1106
1107 }}
1108}