diff --git a/docs/ansi_term/all.html b/docs/ansi_term/all.html new file mode 100644 index 00000000..554cd5c5 --- /dev/null +++ b/docs/ansi_term/all.html @@ -0,0 +1,3 @@ +
Redirecting to ../../ansi_term/struct.Infix.html...
+ + + \ No newline at end of file diff --git a/docs/ansi_term/ansi/struct.Prefix.html b/docs/ansi_term/ansi/struct.Prefix.html new file mode 100644 index 00000000..b50e136f --- /dev/null +++ b/docs/ansi_term/ansi/struct.Prefix.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../ansi_term/struct.Prefix.html...
+ + + \ No newline at end of file diff --git a/docs/ansi_term/ansi/struct.Suffix.html b/docs/ansi_term/ansi/struct.Suffix.html new file mode 100644 index 00000000..e7c2a6fd --- /dev/null +++ b/docs/ansi_term/ansi/struct.Suffix.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../ansi_term/struct.Suffix.html...
+ + + \ No newline at end of file diff --git a/docs/ansi_term/display/fn.ANSIByteStrings.html b/docs/ansi_term/display/fn.ANSIByteStrings.html new file mode 100644 index 00000000..a8a16146 --- /dev/null +++ b/docs/ansi_term/display/fn.ANSIByteStrings.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../ansi_term/fn.ANSIByteStrings.html...
+ + + \ No newline at end of file diff --git a/docs/ansi_term/display/fn.ANSIStrings.html b/docs/ansi_term/display/fn.ANSIStrings.html new file mode 100644 index 00000000..febbcb04 --- /dev/null +++ b/docs/ansi_term/display/fn.ANSIStrings.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../ansi_term/fn.ANSIStrings.html...
+ + + \ No newline at end of file diff --git a/docs/ansi_term/display/struct.ANSIGenericString.html b/docs/ansi_term/display/struct.ANSIGenericString.html new file mode 100644 index 00000000..5db46601 --- /dev/null +++ b/docs/ansi_term/display/struct.ANSIGenericString.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../ansi_term/struct.ANSIGenericString.html...
+ + + \ No newline at end of file diff --git a/docs/ansi_term/display/struct.ANSIGenericStrings.html b/docs/ansi_term/display/struct.ANSIGenericStrings.html new file mode 100644 index 00000000..4edb693e --- /dev/null +++ b/docs/ansi_term/display/struct.ANSIGenericStrings.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../ansi_term/struct.ANSIGenericStrings.html...
+ + + \ No newline at end of file diff --git a/docs/ansi_term/display/type.ANSIByteString.html b/docs/ansi_term/display/type.ANSIByteString.html new file mode 100644 index 00000000..82d9832f --- /dev/null +++ b/docs/ansi_term/display/type.ANSIByteString.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../ansi_term/type.ANSIByteString.html...
+ + + \ No newline at end of file diff --git a/docs/ansi_term/display/type.ANSIByteStrings.html b/docs/ansi_term/display/type.ANSIByteStrings.html new file mode 100644 index 00000000..8773adb7 --- /dev/null +++ b/docs/ansi_term/display/type.ANSIByteStrings.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../ansi_term/type.ANSIByteStrings.html...
+ + + \ No newline at end of file diff --git a/docs/ansi_term/display/type.ANSIString.html b/docs/ansi_term/display/type.ANSIString.html new file mode 100644 index 00000000..9f82d1d2 --- /dev/null +++ b/docs/ansi_term/display/type.ANSIString.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../ansi_term/type.ANSIString.html...
+ + + \ No newline at end of file diff --git a/docs/ansi_term/display/type.ANSIStrings.html b/docs/ansi_term/display/type.ANSIStrings.html new file mode 100644 index 00000000..ed45abd1 --- /dev/null +++ b/docs/ansi_term/display/type.ANSIStrings.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../ansi_term/type.ANSIStrings.html...
+ + + \ No newline at end of file diff --git a/docs/ansi_term/enum.Color.html b/docs/ansi_term/enum.Color.html new file mode 100644 index 00000000..8aed9586 --- /dev/null +++ b/docs/ansi_term/enum.Color.html @@ -0,0 +1,92 @@ +A colour is one specific type of ANSI escape code, and can refer +to either the foreground or background colour.
+These use the standard numeric sequences. +See http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
+Colour #0 (foreground code 30
, background code 40
).
This is not necessarily the background colour, and using it as one may +render the text hard to read on terminals with dark backgrounds.
+Colour #1 (foreground code 31
, background code 41
).
Colour #2 (foreground code 32
, background code 42
).
Colour #3 (foreground code 33
, background code 43
).
Colour #4 (foreground code 34
, background code 44
).
Colour #5 (foreground code 35
, background code 45
).
Colour #6 (foreground code 36
, background code 46
).
Colour #7 (foreground code 37
, background code 47
).
As above, this is not necessarily the foreground colour, and may be +hard to read on terminals with light backgrounds.
+Fixed(u8)
A colour number from 0 to 255, for use in 256-colour terminal +environments.
+Black
to White
variants respectively.
+These colours can usually be changed in the terminal emulator.It might make more sense to look at a colour chart.
+A 24-bit RGB color, as specified by ISO-8613-3.
+impl Colour
[src]pub fn prefix(self) -> Prefix
[src]The prefix for this colour.
+pub fn infix(self, other: Colour) -> Infix
[src]The infix between this colour and another.
+pub fn suffix(self) -> Suffix
[src]The suffix for this colour.
+impl Colour
[src]pub fn normal(self) -> Style
[src]Return a Style
with the foreground colour set to this colour.
pub fn bold(self) -> Style
[src]Returns a Style
with the bold property set.
pub fn dimmed(self) -> Style
[src]Returns a Style
with the dimmed property set.
pub fn italic(self) -> Style
[src]Returns a Style
with the italic property set.
pub fn underline(self) -> Style
[src]Returns a Style
with the underline property set.
pub fn blink(self) -> Style
[src]Returns a Style
with the blink property set.
pub fn reverse(self) -> Style
[src]Returns a Style
with the reverse property set.
pub fn hidden(self) -> Style
[src]Returns a Style
with the hidden property set.
pub fn strikethrough(self) -> Style
[src]Returns a Style
with the strikethrough property set.
pub fn on(self, background: Colour) -> Style
[src]Returns a Style
with the background colour property set.
impl Colour
[src]pub fn paint<'a, I, S: 'a + ToOwned + ?Sized>(
self,
input: I
) -> ANSIGenericString<'a, S> where
I: Into<Cow<'a, S>>,
<S as ToOwned>::Owned: Debug,
[src]Paints the given text with this colour, returning an ANSI string.
+This is a short-cut so you don’t have to use Blue.normal()
just
+to get blue text.
+use ansi_term::Colour::Blue; +println!("{}", Blue.paint("da ba dee"));
impl Clone for Colour
[src]impl Copy for Colour
[src]impl Debug for Colour
[src]impl From<Colour> for Style
[src]fn from(colour: Colour) -> Style
[src]You can turn a Colour
into a Style
with the foreground colour set
+with the From
trait.
+use ansi_term::{Style, Colour}; +let green_foreground = Style::default().fg(Colour::Green); +assert_eq!(green_foreground, Colour::Green.normal()); +assert_eq!(green_foreground, Colour::Green.into()); +assert_eq!(green_foreground, Style::from(Colour::Green));
impl PartialEq<Colour> for Colour
[src]impl StructuralPartialEq for Colour
[src]impl RefUnwindSafe for Colour
impl Send for Colour
impl Sync for Colour
impl Unpin for Colour
impl UnwindSafe for Colour
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<T> ToOwned for T where
T: Clone,
[src]type Owned = T
The resulting type after obtaining ownership.
+fn to_owned(&self) -> T
[src]fn clone_into(&self, target: &mut T)
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]A colour is one specific type of ANSI escape code, and can refer +to either the foreground or background colour.
+These use the standard numeric sequences. +See http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
+Colour #0 (foreground code 30
, background code 40
).
This is not necessarily the background colour, and using it as one may +render the text hard to read on terminals with dark backgrounds.
+Colour #1 (foreground code 31
, background code 41
).
Colour #2 (foreground code 32
, background code 42
).
Colour #3 (foreground code 33
, background code 43
).
Colour #4 (foreground code 34
, background code 44
).
Colour #5 (foreground code 35
, background code 45
).
Colour #6 (foreground code 36
, background code 46
).
Colour #7 (foreground code 37
, background code 47
).
As above, this is not necessarily the foreground colour, and may be +hard to read on terminals with light backgrounds.
+Fixed(u8)
A colour number from 0 to 255, for use in 256-colour terminal +environments.
+Black
to White
variants respectively.
+These colours can usually be changed in the terminal emulator.It might make more sense to look at a colour chart.
+A 24-bit RGB color, as specified by ISO-8613-3.
+impl Colour
[src]pub fn prefix(self) -> Prefix
[src]The prefix for this colour.
+pub fn infix(self, other: Colour) -> Infix
[src]The infix between this colour and another.
+pub fn suffix(self) -> Suffix
[src]The suffix for this colour.
+impl Colour
[src]pub fn normal(self) -> Style
[src]Return a Style
with the foreground colour set to this colour.
pub fn bold(self) -> Style
[src]Returns a Style
with the bold property set.
pub fn dimmed(self) -> Style
[src]Returns a Style
with the dimmed property set.
pub fn italic(self) -> Style
[src]Returns a Style
with the italic property set.
pub fn underline(self) -> Style
[src]Returns a Style
with the underline property set.
pub fn blink(self) -> Style
[src]Returns a Style
with the blink property set.
pub fn reverse(self) -> Style
[src]Returns a Style
with the reverse property set.
pub fn hidden(self) -> Style
[src]Returns a Style
with the hidden property set.
pub fn strikethrough(self) -> Style
[src]Returns a Style
with the strikethrough property set.
pub fn on(self, background: Colour) -> Style
[src]Returns a Style
with the background colour property set.
impl Colour
[src]pub fn paint<'a, I, S: 'a + ToOwned + ?Sized>(
self,
input: I
) -> ANSIGenericString<'a, S> where
I: Into<Cow<'a, S>>,
<S as ToOwned>::Owned: Debug,
[src]Paints the given text with this colour, returning an ANSI string.
+This is a short-cut so you don’t have to use Blue.normal()
just
+to get blue text.
+use ansi_term::Colour::Blue; +println!("{}", Blue.paint("da ba dee"));
impl Clone for Colour
[src]impl Copy for Colour
[src]impl Debug for Colour
[src]impl From<Colour> for Style
[src]fn from(colour: Colour) -> Style
[src]You can turn a Colour
into a Style
with the foreground colour set
+with the From
trait.
+use ansi_term::{Style, Colour}; +let green_foreground = Style::default().fg(Colour::Green); +assert_eq!(green_foreground, Colour::Green.normal()); +assert_eq!(green_foreground, Colour::Green.into()); +assert_eq!(green_foreground, Style::from(Colour::Green));
impl PartialEq<Colour> for Colour
[src]impl StructuralPartialEq for Colour
[src]impl RefUnwindSafe for Colour
impl Send for Colour
impl Sync for Colour
impl Unpin for Colour
impl UnwindSafe for Colour
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<T> ToOwned for T where
T: Clone,
[src]type Owned = T
The resulting type after obtaining ownership.
+fn to_owned(&self) -> T
[src]fn clone_into(&self, target: &mut T)
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]pub fn ANSIByteStrings<'a>(arg: &'a [ANSIByteString<'a>]) -> ANSIByteStrings<'a>
A function to construct an ANSIByteStrings
instance.
pub fn ANSIStrings<'a>(arg: &'a [ANSIString<'a>]) -> ANSIStrings<'a>
A function to construct an ANSIStrings
instance.
This is a library for controlling colours and formatting, such as +red bold text or blue underlined text, on ANSI terminals.
+There are two main data structures in this crate that you need to be
+concerned with: ANSIString
and Style
. A Style
holds stylistic
+information: colours, whether the text should be bold, or blinking, or
+whatever. There are also Colour
variants that represent simple foreground
+colour styles. An ANSIString
is a string paired with a Style
.
(Yes, it’s British English, but you won’t have to write “colour” very often.
+Style
is used the majority of the time.)
To format a string, call the paint
method on a Style
or a Colour
,
+passing in the string you want to format as the argument. For example,
+here’s how to get some red text:
+use ansi_term::Colour::Red; +println!("This is in red: {}", Red.paint("a red string"));
It’s important to note that the paint
method does not actually return a
+string with the ANSI control characters surrounding it. Instead, it returns
+an ANSIString
value that has a Display
implementation that, when
+formatted, returns the characters. This allows strings to be printed with a
+minimum of String
allocations being performed behind the scenes.
If you do want to get at the escape codes, then you can convert the
+ANSIString
to a string as you would any other Display
value:
+use ansi_term::Colour::Red; +use std::string::ToString; +let red_string = Red.paint("a red string").to_string();
For anything more complex than plain foreground colour changes, you need to
+construct Style
objects themselves, rather than beginning with a Colour
.
+You can do this by chaining methods based on a new Style
, created with
+Style::new()
. Each method creates a new style that has that specific
+property set. For example:
+use ansi_term::Style; +println!("How about some {} and {}?", + Style::new().bold().paint("bold"), + Style::new().underline().paint("underline"));
For brevity, these methods have also been implemented for Colour
values,
+so you can give your styles a foreground colour without having to begin with
+an empty Style
value:
+use ansi_term::Colour::{Blue, Yellow}; +println!("Demonstrating {} and {}!", + Blue.bold().paint("blue bold"), + Yellow.underline().paint("yellow underline")); +println!("Yellow on blue: {}", Yellow.on(Blue).paint("wow!"));
The complete list of styles you can use are: bold
, dimmed
, italic
,
+underline
, blink
, reverse
, hidden
, strikethrough
, and on
for
+background colours.
In some cases, you may find it easier to change the foreground on an
+existing Style
rather than starting from the appropriate Colour
.
+You can do this using the fg
method:
+use ansi_term::Style; +use ansi_term::Colour::{Blue, Cyan, Yellow}; +println!("Yellow on blue: {}", Style::new().on(Blue).fg(Yellow).paint("yow!")); +println!("Also yellow on blue: {}", Cyan.on(Blue).fg(Yellow).paint("zow!"));
Finally, you can turn a Colour
into a Style
with the normal
method.
+This will produce the exact same ANSIString
as if you just used the
+paint
method on the Colour
directly, but it’s useful in certain cases:
+for example, you may have a method that returns Styles
, and need to
+represent both the “red bold” and “red, but not bold” styles with values of
+the same type. The Style
struct also has a Default
implementation if you
+want to have a style with nothing set.
+use ansi_term::Style; +use ansi_term::Colour::Red; +Red.normal().paint("yet another red string"); +Style::default().paint("a completely regular string");
You can access the extended range of 256 colours by using the Fixed
colour
+variant, which takes an argument of the colour number to use. This can be
+included wherever you would use a Colour
:
+use ansi_term::Colour::Fixed; +Fixed(134).paint("A sort of light purple"); +Fixed(221).on(Fixed(124)).paint("Mustard in the ketchup");
The first sixteen of these values are the same as the normal and bold
+standard colour variants. There’s nothing stopping you from using these as
+Fixed
colours instead, but there’s nothing to be gained by doing so
+either.
You can also access full 24-bit color by using the RGB
colour variant,
+which takes separate u8
arguments for red, green, and blue:
+use ansi_term::Colour::RGB; +RGB(70, 130, 180).paint("Steel blue");
The benefit of writing ANSI escape codes to the terminal is that they +stack: you do not need to end every coloured string with a reset code if +the text that follows it is of a similar style. For example, if you want to +have some blue text followed by some blue bold text, it’s possible to send +the ANSI code for blue, followed by the ANSI code for bold, and finishing +with a reset code without having to have an extra one between the two +strings.
+This crate can optimise the ANSI codes that get printed in situations like
+this, making life easier for your terminal renderer. The ANSIStrings
+struct takes a slice of several ANSIString
values, and will iterate over
+each of them, printing only the codes for the styles that need to be updated
+as part of its formatting routine.
The following code snippet uses this to enclose a binary number displayed in +red bold text inside some red, but not bold, brackets:
+ ++use ansi_term::Colour::Red; +use ansi_term::{ANSIString, ANSIStrings}; +let some_value = format!("{:b}", 42); +let strings: &[ANSIString<'static>] = &[ + Red.paint("["), + Red.bold().paint(some_value), + Red.paint("]"), +]; +println!("Value: {}", ANSIStrings(strings));
There are several things to note here. Firstly, the paint
method can take
+either an owned String
or a borrowed &str
. Internally, an ANSIString
+holds a copy-on-write (Cow
) string value to deal with both owned and
+borrowed strings at the same time. This is used here to display a String
,
+the result of the format!
call, using the same mechanism as some
+statically-available &str
slices. Secondly, that the ANSIStrings
value
+works in the same way as its singular counterpart, with a Display
+implementation that only performs the formatting when required.
This library also supports formatting [u8]
byte strings; this supports
+applications working with text in an unknown encoding. Style
and
+Color
support painting [u8]
values, resulting in an ANSIByteString
.
+This type does not implement Display
, as it may not contain UTF-8, but
+it does provide a method write_to
to write the result to any
+io::Write
:
+use ansi_term::Colour::Green; +Green.paint("user data".as_bytes()).write_to(&mut std::io::stdout()).unwrap();
Similarly, the type ANSIByteStrings
supports writing a list of
+ANSIByteString
values with minimal escape sequences:
+use ansi_term::Colour::Green; +use ansi_term::ANSIByteStrings; +ANSIByteStrings(&[ + Green.paint("user data 1\n".as_bytes()), + Green.bold().paint("user data 2\n".as_bytes()), +]).write_to(&mut std::io::stdout()).unwrap();
ANSIGenericString | An |
ANSIGenericStrings | A set of |
Infix | Like |
Prefix | Like |
Style | A style is a collection of properties that can format a string +using ANSI escape codes. + |
Suffix | Like |
Color | A colour is one specific type of ANSI escape code, and can refer +to either the foreground or background colour. + |
Colour | A colour is one specific type of ANSI escape code, and can refer +to either the foreground or background colour. + |
ANSIByteStrings | A function to construct an |
ANSIStrings | A function to construct an |
ANSIByteString | An |
ANSIByteStrings | A set of |
ANSIString | An ANSI String is a string coupled with the |
ANSIStrings | A set of |
An ANSIGenericString
includes a generic string type and a Style
to
+display that string. ANSIString
and ANSIByteString
are aliases for
+this type on str
and [u8]
, respectively.
impl<'a> ANSIGenericString<'a, [u8]>
[src]pub fn write_to<W: Write>(&self, w: &mut W) -> Result<()>
[src]Write an ANSIByteString
to an io::Write
. This writes the escape
+sequences for the associated Style
around the bytes.
impl<'a, S: 'a + ToOwned + ?Sized> Clone for ANSIGenericString<'a, S> where
<S as ToOwned>::Owned: Debug,
[src]Cloning an ANSIGenericString
will clone its underlying string.
+use ansi_term::ANSIString; + +let plain_string = ANSIString::from("a plain string"); +let clone_string = plain_string.clone(); +assert_eq!(clone_string, plain_string);
fn clone(&self) -> ANSIGenericString<'a, S>
[src]fn clone_from(&mut self, source: &Self)
1.0.0[src]impl<'a, S: Debug + 'a + ToOwned + ?Sized> Debug for ANSIGenericString<'a, S> where
<S as ToOwned>::Owned: Debug,
[src]impl<'a, S: 'a + ToOwned + ?Sized> Deref for ANSIGenericString<'a, S> where
<S as ToOwned>::Owned: Debug,
[src]impl<'a, I, S: 'a + ToOwned + ?Sized> From<I> for ANSIGenericString<'a, S> where
I: Into<Cow<'a, S>>,
<S as ToOwned>::Owned: Debug,
[src]fn from(input: I) -> ANSIGenericString<'a, S>
[src]impl<'a, S: PartialEq + 'a + ToOwned + ?Sized> PartialEq<ANSIGenericString<'a, S>> for ANSIGenericString<'a, S> where
<S as ToOwned>::Owned: Debug,
[src]fn eq(&self, other: &ANSIGenericString<'a, S>) -> bool
[src]fn ne(&self, other: &ANSIGenericString<'a, S>) -> bool
[src]impl<'a, S: 'a + ToOwned + ?Sized> StructuralPartialEq for ANSIGenericString<'a, S> where
<S as ToOwned>::Owned: Debug,
[src]impl<'a, S: ?Sized> RefUnwindSafe for ANSIGenericString<'a, S> where
S: RefUnwindSafe,
<S as ToOwned>::Owned: RefUnwindSafe,
impl<'a, S: ?Sized> Send for ANSIGenericString<'a, S> where
S: Sync,
<S as ToOwned>::Owned: Send,
impl<'a, S: ?Sized> Sync for ANSIGenericString<'a, S> where
S: Sync,
<S as ToOwned>::Owned: Sync,
impl<'a, S: ?Sized> Unpin for ANSIGenericString<'a, S> where
<S as ToOwned>::Owned: Unpin,
impl<'a, S: ?Sized> UnwindSafe for ANSIGenericString<'a, S> where
S: RefUnwindSafe,
<S as ToOwned>::Owned: UnwindSafe,
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<T> ToOwned for T where
T: Clone,
[src]type Owned = T
The resulting type after obtaining ownership.
+fn to_owned(&self) -> T
[src]fn clone_into(&self, target: &mut T)
[src]impl<T> ToString for T where
T: Display + ?Sized,
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]A set of ANSIGenericString
s collected together, in order to be
+written with a minimum of control characters.
impl<'a> ANSIGenericStrings<'a, [u8]>
[src]pub fn write_to<W: Write>(&self, w: &mut W) -> Result<()>
[src]Write ANSIByteStrings
to an io::Write
. This writes the minimal
+escape sequences for the associated Style
s around each set of
+bytes.
impl<'a, S: ?Sized> RefUnwindSafe for ANSIGenericStrings<'a, S> where
S: RefUnwindSafe,
<S as ToOwned>::Owned: RefUnwindSafe,
impl<'a, S: ?Sized> Send for ANSIGenericStrings<'a, S> where
S: Sync,
<S as ToOwned>::Owned: Sync,
impl<'a, S: ?Sized> Sync for ANSIGenericStrings<'a, S> where
S: Sync,
<S as ToOwned>::Owned: Sync,
impl<'a, S: ?Sized> Unpin for ANSIGenericStrings<'a, S>
impl<'a, S: ?Sized> UnwindSafe for ANSIGenericStrings<'a, S> where
S: RefUnwindSafe,
<S as ToOwned>::Owned: RefUnwindSafe,
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<T> ToString for T where
T: Display + ?Sized,
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]Like ANSIString
, but only displays the difference between two
+styles.
impl Clone for Infix
[src]impl Copy for Infix
[src]impl Debug for Infix
[src]impl Display for Infix
[src]impl RefUnwindSafe for Infix
impl Send for Infix
impl Sync for Infix
impl Unpin for Infix
impl UnwindSafe for Infix
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<T> ToOwned for T where
T: Clone,
[src]type Owned = T
The resulting type after obtaining ownership.
+fn to_owned(&self) -> T
[src]fn clone_into(&self, target: &mut T)
[src]impl<T> ToString for T where
T: Display + ?Sized,
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]Like ANSIString
, but only displays the style prefix.
impl Clone for Prefix
[src]impl Copy for Prefix
[src]impl Debug for Prefix
[src]impl Display for Prefix
[src]impl RefUnwindSafe for Prefix
impl Send for Prefix
impl Sync for Prefix
impl Unpin for Prefix
impl UnwindSafe for Prefix
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<T> ToOwned for T where
T: Clone,
[src]type Owned = T
The resulting type after obtaining ownership.
+fn to_owned(&self) -> T
[src]fn clone_into(&self, target: &mut T)
[src]impl<T> ToString for T where
T: Display + ?Sized,
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]A style is a collection of properties that can format a string +using ANSI escape codes.
+foreground: Option<Colour>
The style's foreground colour, if it has one.
+background: Option<Colour>
The style's background colour, if it has one.
+is_bold: bool
Whether this style is bold.
+is_dimmed: bool
Whether this style is dimmed.
+is_italic: bool
Whether this style is italic.
+is_underline: bool
Whether this style is underlined.
+is_blink: bool
Whether this style is blinking.
+is_reverse: bool
Whether this style has reverse colours.
+Whether this style is hidden.
+is_strikethrough: bool
Whether this style is struckthrough.
+impl Style
[src]pub fn prefix(self) -> Prefix
[src]The prefix for this style.
+pub fn infix(self, other: Style) -> Infix
[src]The infix between this style and another.
+pub fn suffix(self) -> Suffix
[src]The suffix for this style.
+impl Style
[src]pub fn new() -> Style
[src]Creates a new Style with no differences.
+pub fn bold(&self) -> Style
[src]Returns a Style
with the bold property set.
pub fn dimmed(&self) -> Style
[src]Returns a Style
with the dimmed property set.
pub fn italic(&self) -> Style
[src]Returns a Style
with the italic property set.
pub fn underline(&self) -> Style
[src]Returns a Style
with the underline property set.
pub fn blink(&self) -> Style
[src]Returns a Style
with the blink property set.
pub fn reverse(&self) -> Style
[src]Returns a Style
with the reverse property set.
pub fn hidden(&self) -> Style
[src]Returns a Style
with the hidden property set.
pub fn strikethrough(&self) -> Style
[src]Returns a Style
with the hidden property set.
pub fn fg(&self, foreground: Colour) -> Style
[src]Returns a Style
with the foreground colour property set.
pub fn on(&self, background: Colour) -> Style
[src]Returns a Style
with the background colour property set.
pub fn is_plain(self) -> bool
[src]Return true if this Style
has no actual styles, and can be written
+without any control characters.
impl Style
[src]pub fn paint<'a, I, S: 'a + ToOwned + ?Sized>(
self,
input: I
) -> ANSIGenericString<'a, S> where
I: Into<Cow<'a, S>>,
<S as ToOwned>::Owned: Debug,
[src]Paints the given text with this colour, returning an ANSI string.
+impl Clone for Style
[src]impl Copy for Style
[src]impl Debug for Style
[src]Styles have a special Debug
implementation that only shows the fields that
+are set. Fields that haven’t been touched aren’t included in the output.
This behaviour gets bypassed when using the alternate formatting mode
+format!("{:#?}")
.
+use ansi_term::Colour::{Red, Blue}; +assert_eq!("Style { fg(Red), on(Blue), bold, italic }", + format!("{:?}", Red.on(Blue).bold().italic()));
impl Default for Style
[src]fn default() -> Style
[src]Returns a style with no properties set. Formatting text using this +style returns the exact same text.
+ ++use ansi_term::Style; +assert_eq!(None, Style::default().foreground); +assert_eq!(None, Style::default().background); +assert_eq!(false, Style::default().is_bold); +assert_eq!("txt", Style::default().paint("txt").to_string());
impl From<Colour> for Style
[src]fn from(colour: Colour) -> Style
[src]You can turn a Colour
into a Style
with the foreground colour set
+with the From
trait.
+use ansi_term::{Style, Colour}; +let green_foreground = Style::default().fg(Colour::Green); +assert_eq!(green_foreground, Colour::Green.normal()); +assert_eq!(green_foreground, Colour::Green.into()); +assert_eq!(green_foreground, Style::from(Colour::Green));
impl PartialEq<Style> for Style
[src]impl StructuralPartialEq for Style
[src]impl RefUnwindSafe for Style
impl Send for Style
impl Sync for Style
impl Unpin for Style
impl UnwindSafe for Style
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<T> ToOwned for T where
T: Clone,
[src]type Owned = T
The resulting type after obtaining ownership.
+fn to_owned(&self) -> T
[src]fn clone_into(&self, target: &mut T)
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]Like ANSIString
, but only displays the style suffix.
impl Clone for Suffix
[src]impl Copy for Suffix
[src]impl Debug for Suffix
[src]impl Display for Suffix
[src]impl RefUnwindSafe for Suffix
impl Send for Suffix
impl Sync for Suffix
impl Unpin for Suffix
impl UnwindSafe for Suffix
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<T> ToOwned for T where
T: Clone,
[src]type Owned = T
The resulting type after obtaining ownership.
+fn to_owned(&self) -> T
[src]fn clone_into(&self, target: &mut T)
[src]impl<T> ToString for T where
T: Display + ?Sized,
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]Redirecting to ../../ansi_term/enum.Colour.html...
+ + + \ No newline at end of file diff --git a/docs/ansi_term/style/struct.Style.html b/docs/ansi_term/style/struct.Style.html new file mode 100644 index 00000000..7502ec04 --- /dev/null +++ b/docs/ansi_term/style/struct.Style.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../ansi_term/struct.Style.html...
+ + + \ No newline at end of file diff --git a/docs/ansi_term/type.ANSIByteString.html b/docs/ansi_term/type.ANSIByteString.html new file mode 100644 index 00000000..8b806cf5 --- /dev/null +++ b/docs/ansi_term/type.ANSIByteString.html @@ -0,0 +1,5 @@ +type ANSIByteString<'a> = ANSIGenericString<'a, [u8]>;
An ANSIByteString
represents a formatted series of bytes. Use
+ANSIByteString
when styling text with an unknown encoding.
impl<'a> ANSIByteString<'a>
[src]type ANSIByteStrings<'a> = ANSIGenericStrings<'a, [u8]>;
A set of ANSIByteString
s collected together, in order to be
+written with a minimum of control characters.
impl<'a> ANSIByteStrings<'a>
[src]type ANSIString<'a> = ANSIGenericString<'a, str>;
An ANSI String is a string coupled with the Style
to display it
+in a terminal.
Although not technically a string itself, it can be turned into
+one with the to_string
method.
+use ansi_term::ANSIString; +use ansi_term::Colour::Red; + +let red_string = Red.paint("a red string"); +println!("{}", red_string);
+use ansi_term::ANSIString; + +let plain_string = ANSIString::from("a plain string"); +assert_eq!(&*plain_string, "a plain string");
type ANSIStrings<'a> = ANSIGenericStrings<'a, str>;
A set of ANSIString
s collected together, in order to be written with a
+minimum of control characters.
possible stream sources
+impl Clone for Stream
[src]fn clone(&self) -> Stream
[src]fn clone_from(&mut self, source: &Self)
1.0.0[src]impl Copy for Stream
[src]impl Debug for Stream
[src]impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]pub fn is(stream: Stream) -> bool
returns true if this is a tty
+pub fn isnt(stream: Stream) -> bool
returns true if this is not a tty
+atty is a simple utility that answers one question
+++is this a tty?
+
usage is just as simple
+ ++if atty::is(atty::Stream::Stdout) { + println!("i'm a tty") +}
+if atty::isnt(atty::Stream::Stdout) { + println!("i'm not a tty") +}
Stream | possible stream sources + |
is | returns true if this is a tty + |
isnt | returns true if this is not a tty + |
A typesafe bitmask flag generator useful for sets of C-style bitmask flags. +It can be used for creating typesafe wrappers around C APIs.
+The bitflags!
macro generates a struct
that manages a set of flags. The
+flags should only be defined for integer types, otherwise unexpected type
+errors may occur at compile time.
+#[macro_use] +extern crate bitflags; + +bitflags! { + struct Flags: u32 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + const ABC = Self::A.bits | Self::B.bits | Self::C.bits; + } +} + +fn main() { + let e1 = Flags::A | Flags::C; + let e2 = Flags::B | Flags::C; + assert_eq!((e1 | e2), Flags::ABC); // union + assert_eq!((e1 & e2), Flags::C); // intersection + assert_eq!((e1 - e2), Flags::A); // set difference + assert_eq!(!e2, Flags::A); // set complement +}
See example_generated::Flags
for documentation of code
+generated by the above bitflags!
expansion.
The generated struct
s can also be extended with type and trait
+implementations:
+#[macro_use] +extern crate bitflags; + +use std::fmt; + +bitflags! { + struct Flags: u32 { + const A = 0b00000001; + const B = 0b00000010; + } +} + +impl Flags { + pub fn clear(&mut self) { + self.bits = 0; // The `bits` field can be accessed from within the + // same module where the `bitflags!` macro was invoked. + } +} + +impl fmt::Display for Flags { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "hi!") + } +} + +fn main() { + let mut flags = Flags::A | Flags::B; + flags.clear(); + assert!(flags.is_empty()); + assert_eq!(format!("{}", flags), "hi!"); + assert_eq!(format!("{:?}", Flags::A | Flags::B), "A | B"); + assert_eq!(format!("{:?}", Flags::B), "B"); +}
The generated struct and its associated flag constants are not exported
+out of the current module by default. A definition can be exported out of
+the current module by adding pub
before flags
:
+#[macro_use] +extern crate bitflags; + +mod example { + bitflags! { + pub struct Flags1: u32 { + const A = 0b00000001; + } + } + bitflags! { + struct Flags2: u32 { + const B = 0b00000010; + } + } +} + +fn main() { + let flag1 = example::Flags1::A; + let flag2 = example::Flags2::B; // error: const `B` is private +}
Attributes can be attached to the generated struct
by placing them
+before the flags
keyword.
The Copy
, Clone
, PartialEq
, Eq
, PartialOrd
, Ord
and Hash
+traits automatically derived for the struct
using the derive
attribute.
+Additional traits can be derived by providing an explicit derive
+attribute on flags
.
The Extend
and FromIterator
traits are implemented for the struct
,
+too: Extend
adds the union of the instances of the struct
iterated over,
+while FromIterator
calculates the union.
The Binary
, Debug
, LowerHex
, Octal
and UpperHex
trait is also
+implemented by displaying the bits value of the internal struct.
The following operator traits are implemented for the generated struct
:
BitOr
and BitOrAssign
: unionBitAnd
and BitAndAssign
: intersectionBitXor
and BitXorAssign
: toggleSub
and SubAssign
: set differenceNot
: set complementThe following methods are defined for the generated struct
:
empty
: an empty set of flagsall
: the set of all defined flagsbits
: the raw value of the flags currently storedfrom_bits
: convert from underlying bit representation, unless that
+representation contains bits that do not correspond to a
+defined flagfrom_bits_truncate
: convert from underlying bit representation, dropping
+any bits that do not correspond to defined flagsfrom_bits_unchecked
: convert from underlying bit representation, keeping
+all bits (even those not corresponding to defined
+flags)is_empty
: true
if no flags are currently storedis_all
: true
if currently set flags exactly equal all defined flagsintersects
: true
if there are flags common to both self
and other
contains
: true
all of the flags in other
are contained within self
insert
: inserts the specified flags in-placeremove
: removes the specified flags in-placetoggle
: the specified flags will be inserted if not present, and removed
+if they are.set
: inserts or removes the specified flags depending on the passed valueThe Default
trait is not automatically implemented for the generated struct.
If your default value is equal to 0
(which is the same value as calling empty()
+on the generated struct), you can simply derive Default
:
+#[macro_use] +extern crate bitflags; + +bitflags! { + // Results in default value with bits: 0 + #[derive(Default)] + struct Flags: u32 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + } +} + +fn main() { + let derived_default: Flags = Default::default(); + assert_eq!(derived_default.bits(), 0); +}
If your default value is not equal to 0
you need to implement Default
yourself:
+#[macro_use] +extern crate bitflags; + +bitflags! { + struct Flags: u32 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + } +} + +// explicit `Default` implementation +impl Default for Flags { + fn default() -> Flags { + Flags::A | Flags::C + } +} + +fn main() { + let implemented_default: Flags = Default::default(); + assert_eq!(implemented_default, (Flags::A | Flags::C)); +}
Flags with a value equal to zero will have some strange behavior that one should be aware of.
+ ++#[macro_use] +extern crate bitflags; + +bitflags! { + struct Flags: u32 { + const NONE = 0b00000000; + const SOME = 0b00000001; + } +} + +fn main() { + let empty = Flags::empty(); + let none = Flags::NONE; + let some = Flags::SOME; + + // Zero flags are treated as always present + assert!(empty.contains(Flags::NONE)); + assert!(none.contains(Flags::NONE)); + assert!(some.contains(Flags::NONE)); + + // Zero flags will be ignored when testing for emptiness + assert!(none.is_empty()); +}
bitflags | The macro used to generate the flag structure. + |
Redirecting to macro.bitflags.html...
+ + + \ No newline at end of file diff --git a/docs/bitflags/macro.bitflags.html b/docs/bitflags/macro.bitflags.html new file mode 100644 index 00000000..e8ca86f8 --- /dev/null +++ b/docs/bitflags/macro.bitflags.html @@ -0,0 +1,92 @@ +The macro used to generate the flag structure.
+See the crate level docs for complete documentation.
++#[macro_use] +extern crate bitflags; + +bitflags! { + struct Flags: u32 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + const ABC = Self::A.bits | Self::B.bits | Self::C.bits; + } +} + +fn main() { + let e1 = Flags::A | Flags::C; + let e2 = Flags::B | Flags::C; + assert_eq!((e1 | e2), Flags::ABC); // union + assert_eq!((e1 & e2), Flags::C); // intersection + assert_eq!((e1 - e2), Flags::A); // set difference + assert_eq!(!e2, Flags::A); // set complement +}
The generated struct
s can also be extended with type and trait
+implementations:
+#[macro_use] +extern crate bitflags; + +use std::fmt; + +bitflags! { + struct Flags: u32 { + const A = 0b00000001; + const B = 0b00000010; + } +} + +impl Flags { + pub fn clear(&mut self) { + self.bits = 0; // The `bits` field can be accessed from within the + // same module where the `bitflags!` macro was invoked. + } +} + +impl fmt::Display for Flags { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "hi!") + } +} + +fn main() { + let mut flags = Flags::A | Flags::B; + flags.clear(); + assert!(flags.is_empty()); + assert_eq!(format!("{}", flags), "hi!"); + assert_eq!(format!("{:?}", Flags::A | Flags::B), "A | B"); + assert_eq!(format!("{:?}", Flags::B), "B"); +}
Redirecting to ../../../clap/enum.AppSettings.html...
+ + + \ No newline at end of file diff --git a/docs/clap/app/struct.App.html b/docs/clap/app/struct.App.html new file mode 100644 index 00000000..7fb5a751 --- /dev/null +++ b/docs/clap/app/struct.App.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../clap/struct.App.html...
+ + + \ No newline at end of file diff --git a/docs/clap/args/arg/struct.Arg.html b/docs/clap/args/arg/struct.Arg.html new file mode 100644 index 00000000..66cac627 --- /dev/null +++ b/docs/clap/args/arg/struct.Arg.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../../clap/struct.Arg.html...
+ + + \ No newline at end of file diff --git a/docs/clap/args/arg_matches/struct.ArgMatches.html b/docs/clap/args/arg_matches/struct.ArgMatches.html new file mode 100644 index 00000000..7cb34723 --- /dev/null +++ b/docs/clap/args/arg_matches/struct.ArgMatches.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../../clap/struct.ArgMatches.html...
+ + + \ No newline at end of file diff --git a/docs/clap/args/arg_matches/struct.OsValues.html b/docs/clap/args/arg_matches/struct.OsValues.html new file mode 100644 index 00000000..aebaf61e --- /dev/null +++ b/docs/clap/args/arg_matches/struct.OsValues.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../../clap/struct.OsValues.html...
+ + + \ No newline at end of file diff --git a/docs/clap/args/arg_matches/struct.Values.html b/docs/clap/args/arg_matches/struct.Values.html new file mode 100644 index 00000000..f99b25d0 --- /dev/null +++ b/docs/clap/args/arg_matches/struct.Values.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../../clap/struct.Values.html...
+ + + \ No newline at end of file diff --git a/docs/clap/args/group/struct.ArgGroup.html b/docs/clap/args/group/struct.ArgGroup.html new file mode 100644 index 00000000..6084eb59 --- /dev/null +++ b/docs/clap/args/group/struct.ArgGroup.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../../clap/struct.ArgGroup.html...
+ + + \ No newline at end of file diff --git a/docs/clap/args/settings/enum.ArgSettings.html b/docs/clap/args/settings/enum.ArgSettings.html new file mode 100644 index 00000000..a5496ac6 --- /dev/null +++ b/docs/clap/args/settings/enum.ArgSettings.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../../clap/enum.ArgSettings.html...
+ + + \ No newline at end of file diff --git a/docs/clap/args/subcommand/struct.SubCommand.html b/docs/clap/args/subcommand/struct.SubCommand.html new file mode 100644 index 00000000..88a4e642 --- /dev/null +++ b/docs/clap/args/subcommand/struct.SubCommand.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../../clap/struct.SubCommand.html...
+ + + \ No newline at end of file diff --git a/docs/clap/completions/shell/enum.Shell.html b/docs/clap/completions/shell/enum.Shell.html new file mode 100644 index 00000000..c4ffe766 --- /dev/null +++ b/docs/clap/completions/shell/enum.Shell.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../../clap/enum.Shell.html...
+ + + \ No newline at end of file diff --git a/docs/clap/enum.AppSettings.html b/docs/clap/enum.AppSettings.html new file mode 100644 index 00000000..d59a9861 --- /dev/null +++ b/docs/clap/enum.AppSettings.html @@ -0,0 +1,590 @@ +Application level settings, which affect how App
operates
NOTE: When these settings are used, they apply only to current command, and are not +propagated down or up through child or parent subcommands
+Specifies that any invalid UTF-8 code points should not be treated as an error.
+This is the default behavior of clap
.
NOTE: Using argument values with invalid UTF-8 code points requires using
+ArgMatches::os_value_of
, ArgMatches::os_values_of
, ArgMatches::lossy_value_of
,
+or ArgMatches::lossy_values_of
for those particular arguments which may contain invalid
+UTF-8 values
NOTE: This rule only applies to argument values, as flags, options, and
+SubCommand
s themselves only allow valid UTF-8 code points.
Non Windows systems only
++use std::ffi::OsString; +use std::os::unix::ffi::{OsStrExt,OsStringExt}; + +let r = App::new("myprog") + //.setting(AppSettings::AllowInvalidUtf8) + .arg_from_usage("<arg> 'some positional arg'") + .get_matches_from_safe( + vec![ + OsString::from("myprog"), + OsString::from_vec(vec![0xe9])]); + +assert!(r.is_ok()); +let m = r.unwrap(); +assert_eq!(m.value_of_os("arg").unwrap().as_bytes(), &[0xe9]);
Essentially sets [Arg::overrides_with("itself")
] for all arguments.
WARNING: Positional arguments cannot override themselves (or we would never be able
+to advance to the next positional). This setting ignores positional arguments.
+[Arg::overrides_with("itself")
]: ./struct.Arg.html#method.overrides_with
Specifies that leading hyphens are allowed in argument values, such as negative numbers
+like -10
. (which would otherwise be parsed as another flag or option)
NOTE: Use this setting with caution as it silences certain circumstances which would
+otherwise be an error (such as accidentally forgetting to specify a value for leading
+option). It is preferred to set this on a per argument basis, via Arg::allow_hyphen_values
+// Imagine you needed to represent negative numbers as well, such as -10 +let m = App::new("nums") + .setting(AppSettings::AllowLeadingHyphen) + .arg(Arg::with_name("neg").index(1)) + .get_matches_from(vec![ + "nums", "-20" + ]); + +assert_eq!(m.value_of("neg"), Some("-20"));
Allows negative numbers to pass as values. This is similar to
+AllowLeadingHyphen
except that it only allows numbers, all
+other undefined leading hyphens will fail to parse.
+let res = App::new("myprog") + .version("v1.1") + .setting(AppSettings::AllowNegativeNumbers) + .arg(Arg::with_name("num")) + .get_matches_from_safe(vec![ + "myprog", "-20" + ]); +assert!(res.is_ok()); +let m = res.unwrap(); +assert_eq!(m.value_of("num").unwrap(), "-20");
Allows one to implement two styles of CLIs where positionals can be used out of order.
+The first example is a CLI where the second to last positional argument is optional, but
+the final positional argument is required. Such as $ prog [optional] <required>
where one
+of the two following usages is allowed:
$ prog [optional] <required>
$ prog <required>
This would otherwise not be allowed. This is useful when [optional]
has a default value.
Note: when using this style of "missing positionals" the final positional must be
+required if --
will not be used to skip to the final positional argument.
Note: This style also only allows a single positional argument to be "skipped" without
+the use of --
. To skip more than one, see the second example.
The second example is when one wants to skip multiple optional positional arguments, and use
+of the --
operator is OK (but not required if all arguments will be specified anyways).
For example, imagine a CLI which has three positional arguments [foo] [bar] [baz]...
where
+baz
accepts multiple values (similar to man ARGS...
style training arguments).
With this setting the following invocations are possible:
+$ prog foo bar baz1 baz2 baz3
$ prog foo -- baz1 baz2 baz3
$ prog -- baz1 baz2 baz3
Style number one from above:
+ ++// Assume there is an external subcommand named "subcmd" +let m = App::new("myprog") + .setting(AppSettings::AllowMissingPositional) + .arg(Arg::with_name("arg1")) + .arg(Arg::with_name("arg2") + .required(true)) + .get_matches_from(vec![ + "prog", "other" + ]); + +assert_eq!(m.value_of("arg1"), None); +assert_eq!(m.value_of("arg2"), Some("other"));
Now the same example, but using a default value for the first optional positional argument
+ ++// Assume there is an external subcommand named "subcmd" +let m = App::new("myprog") + .setting(AppSettings::AllowMissingPositional) + .arg(Arg::with_name("arg1") + .default_value("something")) + .arg(Arg::with_name("arg2") + .required(true)) + .get_matches_from(vec![ + "prog", "other" + ]); + +assert_eq!(m.value_of("arg1"), Some("something")); +assert_eq!(m.value_of("arg2"), Some("other"));
Style number two from above:
+ ++// Assume there is an external subcommand named "subcmd" +let m = App::new("myprog") + .setting(AppSettings::AllowMissingPositional) + .arg(Arg::with_name("foo")) + .arg(Arg::with_name("bar")) + .arg(Arg::with_name("baz").multiple(true)) + .get_matches_from(vec![ + "prog", "foo", "bar", "baz1", "baz2", "baz3" + ]); + +assert_eq!(m.value_of("foo"), Some("foo")); +assert_eq!(m.value_of("bar"), Some("bar")); +assert_eq!(m.values_of("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
Now notice if we don't specify foo
or baz
but use the --
operator.
+// Assume there is an external subcommand named "subcmd" +let m = App::new("myprog") + .setting(AppSettings::AllowMissingPositional) + .arg(Arg::with_name("foo")) + .arg(Arg::with_name("bar")) + .arg(Arg::with_name("baz").multiple(true)) + .get_matches_from(vec![ + "prog", "--", "baz1", "baz2", "baz3" + ]); + +assert_eq!(m.value_of("foo"), None); +assert_eq!(m.value_of("bar"), None); +assert_eq!(m.values_of("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
Specifies that an unexpected positional argument,
+which would otherwise cause a ErrorKind::UnknownArgument
error,
+should instead be treated as a SubCommand
within the ArgMatches
struct.
NOTE: Use this setting with caution, +as a truly unexpected argument (i.e. one that is NOT an external subcommand) +will not cause an error and instead be treated as a potential subcommand. +One should check for such cases manually and inform the user appropriately.
++// Assume there is an external subcommand named "subcmd" +let m = App::new("myprog") + .setting(AppSettings::AllowExternalSubcommands) + .get_matches_from(vec![ + "myprog", "subcmd", "--option", "value", "-fff", "--flag" + ]); + +// All trailing arguments will be stored under the subcommand's sub-matches using an empty +// string argument name +match m.subcommand() { + (external, Some(ext_m)) => { + let ext_args: Vec<&str> = ext_m.values_of("").unwrap().collect(); + assert_eq!(external, "subcmd"); + assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); + }, + _ => {}, +}
Specifies that use of a valid argument negates subcommands being used after. By default
+clap
allows arguments between subcommands such as
+<cmd> [cmd_args] <cmd2> [cmd2_args] <cmd3> [cmd3_args]
. This setting disables that
+functionality and says that arguments can only follow the final subcommand. For instance
+using this setting makes only the following invocations possible:
<cmd> <cmd2> <cmd3> [cmd3_args]
<cmd> <cmd2> [cmd2_args]
<cmd> [cmd_args]
+App::new("myprog") + .setting(AppSettings::ArgsNegateSubcommands)
Specifies that the help text should be displayed (and then exit gracefully),
+if no arguments are present at runtime (i.e. an empty run such as, $ myprog
.
NOTE: SubCommand
s count as arguments
NOTE: Setting Arg::default_value
effectively disables this option as it will
+ensure that some argument is always present.
+App::new("myprog") + .setting(AppSettings::ArgRequiredElseHelp)
Uses colorized help messages.
+NOTE: Must be compiled with the color
cargo feature
This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms)
++App::new("myprog") + .setting(AppSettings::ColoredHelp) + .get_matches();
Enables colored output only when the output is going to a terminal or TTY.
+NOTE: This is the default behavior of clap
.
NOTE: Must be compiled with the color
cargo feature.
This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms).
++App::new("myprog") + .setting(AppSettings::ColorAuto) + .get_matches();
Enables colored output regardless of whether or not the output is going to a terminal/TTY.
+NOTE: Must be compiled with the color
cargo feature.
This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms).
++App::new("myprog") + .setting(AppSettings::ColorAlways) + .get_matches();
Disables colored output no matter if the output is going to a terminal/TTY, or not.
+NOTE: Must be compiled with the color
cargo feature
This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms)
++App::new("myprog") + .setting(AppSettings::ColorNever) + .get_matches();
Disables the automatic collapsing of positional args into [ARGS]
inside the usage string
+App::new("myprog") + .setting(AppSettings::DontCollapseArgsInUsage) + .get_matches();
Disables the automatic delimiting of values when --
or AppSettings::TrailingVarArg
+was used.
NOTE: The same thing can be done manually by setting the final positional argument to
+Arg::use_delimiter(false)
. Using this setting is safer, because it's easier to locate
+when making changes.
+App::new("myprog") + .setting(AppSettings::DontDelimitTrailingValues) + .get_matches();
Disables -h
and --help
App
without affecting any of the SubCommand
s
+(Defaults to false
; application does have help flags)
+let res = App::new("myprog") + .setting(AppSettings::DisableHelpFlags) + .get_matches_from_safe(vec![ + "myprog", "-h" + ]); +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
+let res = App::new("myprog") + .setting(AppSettings::DisableHelpFlags) + .subcommand(SubCommand::with_name("test")) + .get_matches_from_safe(vec![ + "myprog", "test", "-h" + ]); +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::HelpDisplayed);
Disables the help
subcommand
+let res = App::new("myprog") + .version("v1.1") + .setting(AppSettings::DisableHelpSubcommand) + // Normally, creating a subcommand causes a `help` subcommand to automatically + // be generated as well + .subcommand(SubCommand::with_name("test")) + .get_matches_from_safe(vec![ + "myprog", "help" + ]); +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
Disables -V
and --version
App
without affecting any of the SubCommand
s
+(Defaults to false
; application does have a version flag)
+let res = App::new("myprog") + .version("v1.1") + .setting(AppSettings::DisableVersion) + .get_matches_from_safe(vec![ + "myprog", "-V" + ]); +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
+let res = App::new("myprog") + .version("v1.1") + .setting(AppSettings::DisableVersion) + .subcommand(SubCommand::with_name("test")) + .get_matches_from_safe(vec![ + "myprog", "test", "-V" + ]); +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::VersionDisplayed);
Displays the arguments and SubCommand
s in the help message in the order that they were
+declared in, and not alphabetically which is the default.
+App::new("myprog") + .setting(AppSettings::DeriveDisplayOrder) + .get_matches();
Specifies to use the version of the current command for all child SubCommand
s.
+(Defaults to false
; subcommands have independent version strings from their parents.)
NOTE: The version for the current command and this setting must be set prior to +adding any child subcommands
++App::new("myprog") + .version("v1.1") + .setting(AppSettings::GlobalVersion) + .subcommand(SubCommand::with_name("test")) + .get_matches(); +// running `$ myprog test --version` will display +// "myprog-test v1.1"
Specifies that this SubCommand
should be hidden from help messages
+App::new("myprog") + .subcommand(SubCommand::with_name("test") + .setting(AppSettings::Hidden))
Tells clap
not to print possible values when displaying help information.
+This can be useful if there are many values, or they are explained elsewhere.
Tries to match unknown args to partial subcommands
or their aliases. For example to
+match a subcommand named test
, one could use t
, te
, tes
, and test
.
NOTE: The match must not be ambiguous at all in order to succeed. i.e. to match te
+to test
there could not also be a subcommand or alias temp
because both start with te
CAUTION: This setting can interfere with positional/free arguments, take care when
+designing CLIs which allow inferred subcommands and have potential positional/free
+arguments whose values could start with the same characters as subcommands. If this is the
+case, it's recommended to use settings such as AppSeettings::ArgsNegateSubcommands
in
+conjunction with this setting.
+let m = App::new("prog") + .setting(AppSettings::InferSubcommands) + .subcommand(SubCommand::with_name("test")) + .get_matches_from(vec![ + "prog", "te" + ]); +assert_eq!(m.subcommand_name(), Some("test"));
Specifies that the parser should not assume the first argument passed is the binary name. +This is normally the case when using a "daemon" style mode, or an interactive CLI where one +one would not normally type the binary or program name for each command.
++let m = App::new("myprog") + .setting(AppSettings::NoBinaryName) + .arg(Arg::from_usage("<cmd>... 'commands to run'")) + .get_matches_from(vec!["command", "set"]); + +let cmds: Vec<&str> = m.values_of("cmd").unwrap().collect(); +assert_eq!(cmds, ["command", "set"]);
Places the help string for all arguments on the line after the argument.
++App::new("myprog") + .setting(AppSettings::NextLineHelp) + .get_matches();
No longer required to propagate values
+DEPRECATED: This setting is no longer required in order to propagate values up or down
+Specifies that the parser should propagate global arg's values down or up through any used +child subcommands. Meaning, if a subcommand wasn't used, the values won't be propagated to +said subcommand.
++let m = App::new("myprog") + .arg(Arg::from_usage("[cmd] 'command to run'") + .global(true)) + .subcommand(SubCommand::with_name("foo")) + .get_matches_from(vec!["myprog", "set", "foo"]); + +assert_eq!(m.value_of("cmd"), Some("set")); + +let sub_m = m.subcommand_matches("foo").unwrap(); +assert_eq!(sub_m.value_of("cmd"), Some("set"));
Now doing the same thing, but not using any subcommands will result in the value not being +propagated down.
+ ++let m = App::new("myprog") + .arg(Arg::from_usage("[cmd] 'command to run'") + .global(true)) + .subcommand(SubCommand::with_name("foo")) + .get_matches_from(vec!["myprog", "set"]); + +assert_eq!(m.value_of("cmd"), Some("set")); + +assert!(m.subcommand_matches("foo").is_none());
Allows SubCommand
s to override all requirements of the parent command.
+For example if you had a subcommand or top level application with a required argument
+that is only required as long as there is no subcommand present,
+using this setting would allow you to set those arguments to Arg::required(true)
+and yet receive no error so long as the user uses a valid subcommand instead.
NOTE: This defaults to false (using subcommand does not negate requirements)
+This first example shows that it is an error to not use a required argument
+ ++let err = App::new("myprog") + .setting(AppSettings::SubcommandsNegateReqs) + .arg(Arg::with_name("opt").required(true)) + .subcommand(SubCommand::with_name("test")) + .get_matches_from_safe(vec![ + "myprog" + ]); +assert!(err.is_err()); +assert_eq!(err.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
This next example shows that it is no longer error to not use a required argument if a +valid subcommand is used.
+ ++let noerr = App::new("myprog") + .setting(AppSettings::SubcommandsNegateReqs) + .arg(Arg::with_name("opt").required(true)) + .subcommand(SubCommand::with_name("test")) + .get_matches_from_safe(vec![ + "myprog", "test" + ]); +assert!(noerr.is_ok());
Specifies that the help text should be displayed (before exiting gracefully) if no
+SubCommand
s are present at runtime (i.e. an empty run such as $ myprog
).
NOTE: This should not be used with AppSettings::SubcommandRequired
as they do
+nearly same thing; this prints the help text, and the other prints an error.
NOTE: If the user specifies arguments at runtime, but no subcommand the help text will
+still be displayed and exit. If this is not the desired result, consider using
+AppSettings::ArgRequiredElseHelp
instead.
+App::new("myprog") + .setting(AppSettings::SubcommandRequiredElseHelp)
Specifies that any invalid UTF-8 code points should be treated as an error and fail
+with a ErrorKind::InvalidUtf8
error.
NOTE: This rule only applies to argument values; Things such as flags, options, and
+SubCommand
s themselves only allow valid UTF-8 code points.
Non Windows systems only
++use std::ffi::OsString; +use std::os::unix::ffi::OsStringExt; + +let m = App::new("myprog") + .setting(AppSettings::StrictUtf8) + .arg_from_usage("<arg> 'some positional arg'") + .get_matches_from_safe( + vec![ + OsString::from("myprog"), + OsString::from_vec(vec![0xe9])]); + +assert!(m.is_err()); +assert_eq!(m.unwrap_err().kind, ErrorKind::InvalidUtf8);
Allows specifying that if no SubCommand
is present at runtime,
+error and exit gracefully.
NOTE: This defaults to false
(subcommands do not need to be present)
+let err = App::new("myprog") + .setting(AppSettings::SubcommandRequired) + .subcommand(SubCommand::with_name("test")) + .get_matches_from_safe(vec![ + "myprog", + ]); +assert!(err.is_err()); +assert_eq!(err.unwrap_err().kind, ErrorKind::MissingSubcommand);
Specifies that the final positional argument is a "VarArg" and that clap
should not
+attempt to parse any further args.
The values of the trailing positional argument will contain all args from itself on.
+NOTE: The final positional argument must have Arg::multiple(true)
or the usage
+string equivalent.
+let m = App::new("myprog") + .setting(AppSettings::TrailingVarArg) + .arg(Arg::from_usage("<cmd>... 'commands to run'")) + .get_matches_from(vec!["myprog", "arg1", "-r", "val1"]); + +let trail: Vec<&str> = m.values_of("cmd").unwrap().collect(); +assert_eq!(trail, ["arg1", "-r", "val1"]);
Groups flags and options together, presenting a more unified help message
+(a la getopts
or docopt
style).
The default is that the auto-generated help message will group flags, and options +separately.
+NOTE: This setting is cosmetic only and does not affect any functionality.
++App::new("myprog") + .setting(AppSettings::UnifiedHelpMessage) + .get_matches(); +// running `myprog --help` will display a unified "docopt" or "getopts" style help message
Disables -V
and --version
for all SubCommand
s
+(Defaults to false
; subcommands do have version flags.)
NOTE: This setting must be set prior to adding any subcommands.
++let res = App::new("myprog") + .version("v1.1") + .setting(AppSettings::VersionlessSubcommands) + .subcommand(SubCommand::with_name("test")) + .get_matches_from_safe(vec![ + "myprog", "test", "-V" + ]); +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
Will display a message "Press [ENTER]/[RETURN] to continue..." and wait for user before +exiting
+This is most useful when writing an application which is run from a GUI shortcut, or on +Windows where a user tries to open the binary by double-clicking instead of using the +command line.
+NOTE: This setting is not recursive with SubCommand
s, meaning if you wish this
+behavior for all subcommands, you must set this on each command (needing this is extremely
+rare)
+App::new("myprog") + .setting(AppSettings::WaitOnError)
impl Clone for AppSettings
[src]fn clone(&self) -> AppSettings
[src]fn clone_from(&mut self, source: &Self)
1.0.0[src]impl Copy for AppSettings
[src]impl Debug for AppSettings
[src]impl FromStr for AppSettings
[src]type Err = String
The associated error which can be returned from parsing.
+fn from_str(s: &str) -> Result<Self, Self::Err>
[src]impl PartialEq<AppSettings> for AppSettings
[src]fn eq(&self, other: &AppSettings) -> bool
[src]#[must_use]fn ne(&self, other: &Rhs) -> bool
1.0.0[src]impl StructuralPartialEq for AppSettings
[src]impl RefUnwindSafe for AppSettings
impl Send for AppSettings
impl Sync for AppSettings
impl Unpin for AppSettings
impl UnwindSafe for AppSettings
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<T> ToOwned for T where
T: Clone,
[src]type Owned = T
The resulting type after obtaining ownership.
+fn to_owned(&self) -> T
[src]fn clone_into(&self, target: &mut T)
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]Various settings that apply to arguments and may be set, unset, and checked via getter/setter
+methods Arg::set
, Arg::unset
, and Arg::is_set
The argument must be used
+The argument may be used multiple times such as --flag --flag
The argument allows empty values such as --option ""
The argument should be propagated down through all child SubCommand
s
The argument should not be shown in help text
+The argument accepts a value, such as --option <value>
Determines if the argument allows values to be grouped via a delimiter
+Prints the help text on the line after the argument
+Requires the use of a value delimiter for all multiple values
+Hides the possible values from the help string
+Allows vals that start with a '-'
+Require options use --option=val
syntax
Specifies that the arg is the last positional argument and may be accessed early via --
+syntax
Hides the default value from the help string
+Makes Arg::possible_values
case insensitive
Hides ENV values in the help message
+The argument should not be shown in short help text
+The argument should not be shown in long help text
+impl Clone for ArgSettings
[src]fn clone(&self) -> ArgSettings
[src]fn clone_from(&mut self, source: &Self)
1.0.0[src]impl Copy for ArgSettings
[src]impl Debug for ArgSettings
[src]impl FromStr for ArgSettings
[src]type Err = String
The associated error which can be returned from parsing.
+fn from_str(s: &str) -> Result<Self, Self::Err>
[src]impl PartialEq<ArgSettings> for ArgSettings
[src]fn eq(&self, other: &ArgSettings) -> bool
[src]#[must_use]fn ne(&self, other: &Rhs) -> bool
1.0.0[src]impl StructuralPartialEq for ArgSettings
[src]impl RefUnwindSafe for ArgSettings
impl Send for ArgSettings
impl Sync for ArgSettings
impl Unpin for ArgSettings
impl UnwindSafe for ArgSettings
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<T> ToOwned for T where
T: Clone,
[src]type Owned = T
The resulting type after obtaining ownership.
+fn to_owned(&self) -> T
[src]fn clone_into(&self, target: &mut T)
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]Command line argument parser kind of error
+Occurs when an Arg
has a set of possible values,
+and the user provides a value which isn't in that set.
+let result = App::new("prog") + .arg(Arg::with_name("speed") + .possible_value("fast") + .possible_value("slow")) + .get_matches_from_safe(vec!["prog", "other"]); +assert!(result.is_err()); +assert_eq!(result.unwrap_err().kind, ErrorKind::InvalidValue);
Occurs when a user provides a flag, option, argument or subcommand which isn't defined.
++let result = App::new("prog") + .arg(Arg::from_usage("--flag 'some flag'")) + .get_matches_from_safe(vec!["prog", "--other"]); +assert!(result.is_err()); +assert_eq!(result.unwrap_err().kind, ErrorKind::UnknownArgument);
Occurs when the user provides an unrecognized SubCommand
which meets the threshold for
+being similar enough to an existing subcommand.
+If it doesn't meet the threshold, or the 'suggestions' feature is disabled,
+the more general UnknownArgument
error is returned.
+let result = App::new("prog") + .subcommand(SubCommand::with_name("config") + .about("Used for configuration") + .arg(Arg::with_name("config_file") + .help("The configuration file to use") + .index(1))) + .get_matches_from_safe(vec!["prog", "confi"]); +assert!(result.is_err()); +assert_eq!(result.unwrap_err().kind, ErrorKind::InvalidSubcommand);
Occurs when the user provides an unrecognized SubCommand
which either
+doesn't meet the threshold for being similar enough to an existing subcommand,
+or the 'suggestions' feature is disabled.
+Otherwise the more detailed InvalidSubcommand
error is returned.
This error typically happens when passing additional subcommand names to the help
+subcommand. Otherwise, the more general UnknownArgument
error is used.
+let result = App::new("prog") + .subcommand(SubCommand::with_name("config") + .about("Used for configuration") + .arg(Arg::with_name("config_file") + .help("The configuration file to use") + .index(1))) + .get_matches_from_safe(vec!["prog", "help", "nothing"]); +assert!(result.is_err()); +assert_eq!(result.unwrap_err().kind, ErrorKind::UnrecognizedSubcommand);
Occurs when the user provides an empty value for an option that does not allow empty +values.
++let res = App::new("prog") + .arg(Arg::with_name("color") + .long("color") + .empty_values(false)) + .get_matches_from_safe(vec!["prog", "--color="]); +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue);
Occurs when the user provides a value for an argument with a custom validation and the +value fails that validation.
++fn is_numeric(val: String) -> Result<(), String> { + match val.parse::<i64>() { + Ok(..) => Ok(()), + Err(..) => Err(String::from("Value wasn't a number!")), + } +} + +let result = App::new("prog") + .arg(Arg::with_name("num") + .validator(is_numeric)) + .get_matches_from_safe(vec!["prog", "NotANumber"]); +assert!(result.is_err()); +assert_eq!(result.unwrap_err().kind, ErrorKind::ValueValidation);
Occurs when a user provides more values for an argument than were defined by setting
+Arg::max_values
.
+let result = App::new("prog") + .arg(Arg::with_name("arg") + .multiple(true) + .max_values(2)) + .get_matches_from_safe(vec!["prog", "too", "many", "values"]); +assert!(result.is_err()); +assert_eq!(result.unwrap_err().kind, ErrorKind::TooManyValues);
Occurs when the user provides fewer values for an argument than were defined by setting
+Arg::min_values
.
+let result = App::new("prog") + .arg(Arg::with_name("some_opt") + .long("opt") + .min_values(3)) + .get_matches_from_safe(vec!["prog", "--opt", "too", "few"]); +assert!(result.is_err()); +assert_eq!(result.unwrap_err().kind, ErrorKind::TooFewValues);
Occurs when the user provides a different number of values for an argument than what's
+been defined by setting Arg::number_of_values
or than was implicitly set by
+Arg::value_names
.
+let result = App::new("prog") + .arg(Arg::with_name("some_opt") + .long("opt") + .takes_value(true) + .number_of_values(2)) + .get_matches_from_safe(vec!["prog", "--opt", "wrong"]); +assert!(result.is_err()); +assert_eq!(result.unwrap_err().kind, ErrorKind::WrongNumberOfValues);
Occurs when the user provides two values which conflict with each other and can't be used +together.
++let result = App::new("prog") + .arg(Arg::with_name("debug") + .long("debug") + .conflicts_with("color")) + .arg(Arg::with_name("color") + .long("color")) + .get_matches_from_safe(vec!["prog", "--debug", "--color"]); +assert!(result.is_err()); +assert_eq!(result.unwrap_err().kind, ErrorKind::ArgumentConflict);
Occurs when the user does not provide one or more required arguments.
++let result = App::new("prog") + .arg(Arg::with_name("debug") + .required(true)) + .get_matches_from_safe(vec!["prog"]); +assert!(result.is_err()); +assert_eq!(result.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
Occurs when a subcommand is required (as defined by AppSettings::SubcommandRequired
),
+but the user does not provide one.
+let err = App::new("prog") + .setting(AppSettings::SubcommandRequired) + .subcommand(SubCommand::with_name("test")) + .get_matches_from_safe(vec![ + "myprog", + ]); +assert!(err.is_err()); +assert_eq!(err.unwrap_err().kind, ErrorKind::MissingSubcommand);
Occurs when either an argument or SubCommand
is required, as defined by
+AppSettings::ArgRequiredElseHelp
, but the user did not provide one.
+let result = App::new("prog") + .setting(AppSettings::ArgRequiredElseHelp) + .subcommand(SubCommand::with_name("config") + .about("Used for configuration") + .arg(Arg::with_name("config_file") + .help("The configuration file to use"))) + .get_matches_from_safe(vec!["prog"]); +assert!(result.is_err()); +assert_eq!(result.unwrap_err().kind, ErrorKind::MissingArgumentOrSubcommand);
Occurs when the user provides multiple values to an argument which doesn't allow that.
++let result = App::new("prog") + .arg(Arg::with_name("debug") + .long("debug") + .multiple(false)) + .get_matches_from_safe(vec!["prog", "--debug", "--debug"]); +assert!(result.is_err()); +assert_eq!(result.unwrap_err().kind, ErrorKind::UnexpectedMultipleUsage);
Occurs when the user provides a value containing invalid UTF-8 for an argument and
+AppSettings::StrictUtf8
is set.
Non-Windows platforms only (such as Linux, Unix, macOS, etc.)
++let result = App::new("prog") + .setting(AppSettings::StrictUtf8) + .arg(Arg::with_name("utf8") + .short("u") + .takes_value(true)) + .get_matches_from_safe(vec![OsString::from("myprog"), + OsString::from("-u"), + OsString::from_vec(vec![0xE9])]); +assert!(result.is_err()); +assert_eq!(result.unwrap_err().kind, ErrorKind::InvalidUtf8);
Not a true "error" as it means --help
or similar was used.
+The help message will be sent to stdout
.
Note: If the help is displayed due to an error (such as missing subcommands) it will
+be sent to stderr
instead of stdout
.
+let result = App::new("prog") + .get_matches_from_safe(vec!["prog", "--help"]); +assert!(result.is_err()); +assert_eq!(result.unwrap_err().kind, ErrorKind::HelpDisplayed);
Not a true "error" as it means --version
or similar was used.
+The message will be sent to stdout
.
+let result = App::new("prog") + .get_matches_from_safe(vec!["prog", "--version"]); +assert!(result.is_err()); +assert_eq!(result.unwrap_err().kind, ErrorKind::VersionDisplayed);
Occurs when using the [value_t!
] and [values_t!
] macros to convert an argument value
+into type T
, but the argument you requested wasn't used. I.e. you asked for an argument
+with name config
to be converted, but config
wasn't used by the user.
+[value_t!
]: ./macro.value_t!.html
+[values_t!
]: ./macro.values_t!.html
Represents an [I/O error].
+Can occur when writing to stderr
or stdout
or reading a configuration file.
+[I/O error]: https://doc.rust-lang.org/std/io/struct.Error.html
Represents a Format error (which is a part of Display
).
+Typically caused by writing to stderr
or stdout
.
impl Clone for ErrorKind
[src]impl Copy for ErrorKind
[src]impl Debug for ErrorKind
[src]impl PartialEq<ErrorKind> for ErrorKind
[src]impl StructuralPartialEq for ErrorKind
[src]impl RefUnwindSafe for ErrorKind
impl Send for ErrorKind
impl Sync for ErrorKind
impl Unpin for ErrorKind
impl UnwindSafe for ErrorKind
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<T> ToOwned for T where
T: Clone,
[src]type Owned = T
The resulting type after obtaining ownership.
+fn to_owned(&self) -> T
[src]fn clone_into(&self, target: &mut T)
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]Describes which shell to produce a completions file for
+Generates a .bash completion file for the Bourne Again SHell (BASH)
+Generates a .fish completion file for the Friendly Interactive SHell (fish)
+Generates a completion file for the Z SHell (ZSH)
+Generates a completion file for PowerShell
+Generates a completion file for Elvish
+impl Shell
[src]impl Clone for Shell
[src]impl Copy for Shell
[src]impl Debug for Shell
[src]impl Display for Shell
[src]impl FromStr for Shell
[src]impl RefUnwindSafe for Shell
impl Send for Shell
impl Sync for Shell
impl Unpin for Shell
impl UnwindSafe for Shell
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<T> ToOwned for T where
T: Clone,
[src]type Owned = T
The resulting type after obtaining ownership.
+fn to_owned(&self) -> T
[src]fn clone_into(&self, target: &mut T)
[src]impl<T> ToString for T where
T: Display + ?Sized,
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]Redirecting to ../../clap/enum.ErrorKind.html...
+ + + \ No newline at end of file diff --git a/docs/clap/errors/struct.Error.html b/docs/clap/errors/struct.Error.html new file mode 100644 index 00000000..8783fd1a --- /dev/null +++ b/docs/clap/errors/struct.Error.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../clap/struct.Error.html...
+ + + \ No newline at end of file diff --git a/docs/clap/errors/type.Result.html b/docs/clap/errors/type.Result.html new file mode 100644 index 00000000..7ed1fa4c --- /dev/null +++ b/docs/clap/errors/type.Result.html @@ -0,0 +1,10 @@ + + + + + + +Redirecting to ../../clap/type.Result.html...
+ + + \ No newline at end of file diff --git a/docs/clap/index.html b/docs/clap/index.html new file mode 100644 index 00000000..74ad45f2 --- /dev/null +++ b/docs/clap/index.html @@ -0,0 +1,482 @@ +clap
is a simple-to-use, efficient, and full-featured library for parsing command line
+arguments and subcommands when writing console/terminal applications.
clap
is used to parse and validate the string of command line arguments provided by the user
+at runtime. You provide the list of valid possibilities, and clap
handles the rest. This means
+you focus on your applications functionality, and less on the parsing and validating of
+arguments.
clap
also provides the traditional version and help switches (or flags) 'for free' meaning
+automatically with no configuration. It does this by checking the list of valid possibilities you
+supplied and adding only the ones you haven't already defined. If you are using subcommands,
+clap
will also auto-generate a help
subcommand for you in addition to the traditional flags.
Once clap
parses the user provided string of arguments, it returns the matches along with any
+applicable values. If the user made an error or typo, clap
informs them of the mistake and
+exits gracefully (or returns a Result
type and allows you to perform any clean up prior to
+exit). Because of this, you can make reasonable assumptions in your code about the validity of
+the arguments.
The following examples show a quick example of some of the very basic functionality of clap
.
+For more advanced usage, such as requirements, conflicts, groups, multiple values and
+occurrences see the documentation, examples/ directory of
+this repository or the video tutorials.
NOTE: All of these examples are functionally the same, but show different styles in which to
+use clap
The first example shows a method that allows more advanced configuration options (not shown in +this small example), or even dynamically generating arguments when desired. The downside is it's +more verbose.
+ ++// (Full example with detailed comments in examples/01b_quick_example.rs) +// +// This example demonstrates clap's full 'builder pattern' style of creating arguments which is +// more verbose, but allows easier editing, and at times more advanced options, or the possibility +// to generate arguments dynamically. +extern crate clap; +use clap::{Arg, App, SubCommand}; + +fn main() { + let matches = App::new("My Super Program") + .version("1.0") + .author("Kevin K. <kbknapp@gmail.com>") + .about("Does awesome things") + .arg(Arg::with_name("config") + .short("c") + .long("config") + .value_name("FILE") + .help("Sets a custom config file") + .takes_value(true)) + .arg(Arg::with_name("INPUT") + .help("Sets the input file to use") + .required(true) + .index(1)) + .arg(Arg::with_name("v") + .short("v") + .multiple(true) + .help("Sets the level of verbosity")) + .subcommand(SubCommand::with_name("test") + .about("controls testing features") + .version("1.3") + .author("Someone E. <someone_else@other.com>") + .arg(Arg::with_name("debug") + .short("d") + .help("print debug information verbosely"))) + .get_matches(); + + // Gets a value for config if supplied by user, or defaults to "default.conf" + let config = matches.value_of("config").unwrap_or("default.conf"); + println!("Value for config: {}", config); + + // Calling .unwrap() is safe here because "INPUT" is required (if "INPUT" wasn't + // required we could have used an 'if let' to conditionally get the value) + println!("Using input file: {}", matches.value_of("INPUT").unwrap()); + + // Vary the output based on how many times the user used the "verbose" flag + // (i.e. 'myprog -v -v -v' or 'myprog -vvv' vs 'myprog -v' + match matches.occurrences_of("v") { + 0 => println!("No verbose info"), + 1 => println!("Some verbose info"), + 2 => println!("Tons of verbose info"), + 3 | _ => println!("Don't be crazy"), + } + + // You can handle information about subcommands by requesting their matches by name + // (as below), requesting just the name used, or both at the same time + if let Some(matches) = matches.subcommand_matches("test") { + if matches.is_present("debug") { + println!("Printing debug info..."); + } else { + println!("Printing normally..."); + } + } + + // more program logic goes here... +}
The next example shows a far less verbose method, but sacrifices some of the advanced +configuration options (not shown in this small example). This method also takes a very minor +runtime penalty.
+ ++// (Full example with detailed comments in examples/01a_quick_example.rs) +// +// This example demonstrates clap's "usage strings" method of creating arguments +// which is less verbose +extern crate clap; +use clap::{Arg, App, SubCommand}; + +fn main() { + let matches = App::new("myapp") + .version("1.0") + .author("Kevin K. <kbknapp@gmail.com>") + .about("Does awesome things") + .args_from_usage( + "-c, --config=[FILE] 'Sets a custom config file' + <INPUT> 'Sets the input file to use' + -v... 'Sets the level of verbosity'") + .subcommand(SubCommand::with_name("test") + .about("controls testing features") + .version("1.3") + .author("Someone E. <someone_else@other.com>") + .arg_from_usage("-d, --debug 'Print debug information'")) + .get_matches(); + + // Same as previous example... +}
This third method shows how you can use a YAML file to build your CLI and keep your Rust source +tidy or support multiple localized translations by having different YAML files for each +localization.
+First, create the cli.yml
file to hold your CLI options, but it could be called anything we
+like:
name: myapp
+version: "1.0"
+author: Kevin K. <kbknapp@gmail.com>
+about: Does awesome things
+args:
+ - config:
+ short: c
+ long: config
+ value_name: FILE
+ help: Sets a custom config file
+ takes_value: true
+ - INPUT:
+ help: Sets the input file to use
+ required: true
+ index: 1
+ - verbose:
+ short: v
+ multiple: true
+ help: Sets the level of verbosity
+subcommands:
+ - test:
+ about: controls testing features
+ version: "1.3"
+ author: Someone E. <someone_else@other.com>
+ args:
+ - debug:
+ short: d
+ help: print debug information
+
+Since this feature requires additional dependencies that not everyone may want, it is not +compiled in by default and we need to enable a feature flag in Cargo.toml:
+Simply change your clap = "~2.27.0"
to clap = {version = "~2.27.0", features = ["yaml"]}
.
At last we create our main.rs
file just like we would have with the previous two examples:
+// (Full example with detailed comments in examples/17_yaml.rs) +// +// This example demonstrates clap's building from YAML style of creating arguments which is far +// more clean, but takes a very small performance hit compared to the other two methods. +#[macro_use] +extern crate clap; +use clap::App; + +fn main() { + // The YAML file is found relative to the current file, similar to how modules are found + let yaml = load_yaml!("cli.yml"); + let matches = App::from_yaml(yaml).get_matches(); + + // Same as previous examples... +}
Finally there is a macro version, which is like a hybrid approach offering the speed of the +builder pattern (the first example), but without all the verbosity.
+ ++#[macro_use] +extern crate clap; + +fn main() { + let matches = clap_app!(myapp => + (version: "1.0") + (author: "Kevin K. <kbknapp@gmail.com>") + (about: "Does awesome things") + (@arg CONFIG: -c --config +takes_value "Sets a custom config file") + (@arg INPUT: +required "Sets the input file to use") + (@arg debug: -d ... "Sets the level of debugging information") + (@subcommand test => + (about: "controls testing features") + (version: "1.3") + (author: "Someone E. <someone_else@other.com>") + (@arg verbose: -v --verbose "Print test information verbosely") + ) + ).get_matches(); + + // Same as before... +}
If you were to compile any of the above programs and run them with the flag --help
or -h
(or
+help
subcommand, since we defined test
as a subcommand) the following would be output
$ myprog --help
+My Super Program 1.0
+Kevin K. <kbknapp@gmail.com>
+Does awesome things
+
+USAGE:
+ MyApp [FLAGS] [OPTIONS] <INPUT> [SUBCOMMAND]
+
+FLAGS:
+ -h, --help Prints this message
+ -v Sets the level of verbosity
+ -V, --version Prints version information
+
+OPTIONS:
+ -c, --config <FILE> Sets a custom config file
+
+ARGS:
+ INPUT The input file to use
+
+SUBCOMMANDS:
+ help Prints this message
+ test Controls testing features
+
+NOTE: You could also run myapp test --help
to see similar output and options for the
+test
subcommand.
To try out the pre-built example, use the following steps:
+$ git clone https://github.com/clap-rs/clap && cd clap-rs/tests
$ cargo build --release
$ ./target/release/claptests --help
To test out clap
's default auto-generated help/version follow these steps:
$ cargo new fake --bin && cd fake
clap
to your Cargo.toml
[dependencies]
+clap = "2"
+
+src/main.rs
+extern crate clap; +use clap::App; + +fn main() { + App::new("fake").version("v1.0-beta").get_matches(); +}
$ cargo build --release
$ ./target/release/fake --help
or $ ./target/release/fake --version
For full usage, add clap
as a dependency in your Cargo.toml
(it is highly recommended to
+use the ~major.minor.patch
style versions in your Cargo.toml
, for more information see
+Compatibility Policy) to use from crates.io:
[dependencies]
+clap = "~2.27.0"
+
+Or get the latest changes from the master branch at github:
+[dependencies.clap]
+git = "https://github.com/clap-rs/clap.git"
+
+Add extern crate clap;
to your crate root.
Define a list of valid arguments for your program (see the +documentation or examples/ directory of this repo)
+Then run cargo build
or cargo update && cargo build
for your project.
suggestions
: Turns on the Did you mean '--myoption'?
feature for when users make typos. (builds dependency strsim
)color
: Turns on colored error messages. This feature only works on non-Windows OSs. (builds dependency ansi-term
and atty
)wrap_help
: Wraps the help at the actual terminal width when
+available, instead of 120 characters. (builds dependency textwrap
+with feature term_size
)To disable these, add this to your Cargo.toml
:
[dependencies.clap]
+version = "~2.27.0"
+default-features = false
+
+You can also selectively enable only the features you'd like to include, by adding:
+[dependencies.clap]
+version = "~2.27.0"
+default-features = false
+
+# Cherry-pick the features you'd like to use
+features = [ "suggestions", "color" ]
+
+yaml-rust
)clap
features that may change from release to releaseThe following graphic depicts clap
s dependency graph (generated using
+cargo-graph).
features
to enable)You can find complete documentation on the docs.rs for this project.
+You can also find usage examples in the examples/ directory of this repo.
+There's also the video tutorial series Argument Parsing with Rust v2.
+These videos slowly trickle out as I finish them and currently a work in progress.
+Contributions are always welcome! And there is a multitude of ways in which you can help +depending on what you like to do, or are good at. Anything from documentation, code cleanup, +issue completion, new features, you name it, even filing issues is contributing and greatly +appreciated!
+Another really great way to help is if you find an interesting, or helpful way in which to use
+clap
. You can either add it to the examples/ directory, or file an issue and tell
+me. I'm all about giving credit where credit is due :)
Please read CONTRIBUTING.md before you start contributing.
+To test with all features both enabled and disabled, you can run theese commands:
+$ cargo test --no-default-features
+$ cargo test --features "yaml unstable"
+
+Alternatively, if you have just
installed you can run the
+prebuilt recipes. Not using just
is perfectly fine as well, it simply bundles commands
+automatically.
For example, to test the code, as above simply run:
+$ just run-tests
+
+From here on, I will list the appropriate cargo
command as well as the just
command.
Sometimes it's helpful to only run a subset of the tests, which can be done via:
+$ cargo test --test <test_name>
+
+# Or
+
+$ just run-test <test_name>
+
+During the CI process clap
runs against many different lints using
+clippy
. In order to check if these lints pass on
+your own computer prior to submitting a PR you'll need a nightly compiler.
In order to check the code for lints run either:
+$ rustup override add nightly
+$ cargo build --features lints
+$ rustup override remove
+
+# Or
+
+$ just lint
+
+Another helpful technique is to see the clap
debug output while developing features. In order
+to see the debug output while running the full test suite or individual tests, run:
$ cargo test --features debug
+
+# Or for individual tests
+$ cargo test --test <test_name> --features debug
+
+# The corresponding just command for individual debugging tests is:
+$ just debug <test_name>
+
+There are a few goals of clap
that I'd like to maintain throughout contributions. If your
+proposed changes break, or go against any of these goals we'll discuss the changes further
+before merging (but will not be ignored, all contributes are welcome!). These are by no means
+hard-and-fast rules, as I'm no expert and break them myself from time to time (even if by
+mistake or ignorance).
clap
should be low since the main program
+is the star of the showpanic!
on developer error, exit gracefully on end-user errorBecause clap
takes SemVer
and compatibility seriously, this is the official policy regarding
+breaking changes and previous versions of Rust.
clap
will pin the minimum required version of Rust to the CI builds. Bumping the minimum
+version of Rust is considered a minor breaking change, meaning at a minimum the minor version
+of clap
will be bumped.
In order to keep from being surprised by breaking changes, it is highly recommended to use
+the ~major.minor.patch
style in your Cargo.toml
:
[dependencies] clap = "~2.27.0"
+
+This will cause only the patch version to be updated upon a cargo update
call, and therefore
+cannot break due to new features, or bumped minimum versions of Rust.
clap
will officially support current stable Rust, minus two releases, but may work with prior
+releases as well. For example, current stable Rust at the time of this writing is 1.21.0,
+meaning clap
is guaranteed to compile with 1.19.0 and beyond. At the 1.22.0 release, clap
+will be guaranteed to compile with 1.20.0 and beyond, etc.
Upon bumping the minimum version of Rust (assuming it's within the stable-2 range), it must be
+clearly annotated in the CHANGELOG.md
clap
is licensed under the MIT license. Please read the LICENSE-MIT file in
+this repository for more information.
_clap_count_exprs | Counts the number of comma-delimited expressions passed to it. The result is a compile-time
+evaluable expression, suitable for use as a static array size, or the value of a |
app_from_crate | Allows you to build the |
arg_enum | Convenience macro to generate more complete enums with variants to be used as a type when
+parsing arguments. This enum also provides a |
clap_app | Build |
crate_authors | Allows you to pull the authors for the app from your Cargo.toml at
+compile time in the form:
+ |
crate_description | Allows you to pull the description from your Cargo.toml at compile time. + |
crate_name | Allows you to pull the name from your Cargo.toml at compile time. + |
crate_version | Allows you to pull the version from your Cargo.toml at compile time as
+ |
load_yaml | A convenience macro for loading the YAML file at compile time (relative to the current file, +like modules work). That YAML object can then be passed to this function. + |
value_t | Convenience macro getting a typed value |
value_t_or_exit | Convenience macro getting a typed value |
values_t | Convenience macro getting a typed value |
values_t_or_exit | Convenience macro getting a typed value |
App | Used to create a representation of a command line program and all possible command line
+arguments. Application settings are set using the "builder pattern" with the
+ |
Arg | The abstract representation of a command line argument. Used to set all the options and +relationships that define a valid argument for the program. + |
ArgGroup |
|
ArgMatches | Used to get information about the arguments that were supplied to the program at runtime by
+the user. New instances of this struct are obtained by using the |
Error | Command Line Argument Parser Error + |
OsValues | An iterator for getting multiple values out of an argument via the [ |
SubCommand | The abstract representation of a command line subcommand. + |
Values | An iterator for getting multiple values out of an argument via the |
YamlLoader |
AppSettings | Application level settings, which affect how |
ArgSettings | Various settings that apply to arguments and may be set, unset, and checked via getter/setter
+methods |
ErrorKind | Command line argument parser kind of error + |
Shell | Describes which shell to produce a completions file for + |
Result | Short hand for |
Redirecting to macro._clap_count_exprs.html...
+ + + \ No newline at end of file diff --git a/docs/clap/macro._clap_count_exprs.html b/docs/clap/macro._clap_count_exprs.html new file mode 100644 index 00000000..bb3ee3c6 --- /dev/null +++ b/docs/clap/macro._clap_count_exprs.html @@ -0,0 +1,13 @@ +Counts the number of comma-delimited expressions passed to it. The result is a compile-time
+evaluable expression, suitable for use as a static array size, or the value of a const
.
+const COUNT: usize = _clap_count_exprs!(a, 5+1, "hi there!".into_string()); +assert_eq!(COUNT, 3);
Redirecting to macro.app_from_crate.html...
+ + + \ No newline at end of file diff --git a/docs/clap/macro.app_from_crate.html b/docs/clap/macro.app_from_crate.html new file mode 100644 index 00000000..72196d04 --- /dev/null +++ b/docs/clap/macro.app_from_crate.html @@ -0,0 +1,18 @@ +Allows you to build the App
instance from your Cargo.toml at compile time.
Equivalent to using the crate_*!
macros with their respective fields.
Provided separator is for the crate_authors!
macro,
+refer to the documentation therefor.
NOTE: Changing the values in your Cargo.toml
does not trigger a re-build automatically,
+and therefore won't change the generated output until you recompile.
Pro Tip: In some cases you can "trick" the compiler into triggering a rebuild when your
+Cargo.toml
is changed by including this in your src/main.rs
file
+include_str!("../Cargo.toml");
+let m = app_from_crate!().get_matches();
Redirecting to macro.arg_enum.html...
+ + + \ No newline at end of file diff --git a/docs/clap/macro.arg_enum.html b/docs/clap/macro.arg_enum.html new file mode 100644 index 00000000..b18bf808 --- /dev/null +++ b/docs/clap/macro.arg_enum.html @@ -0,0 +1,46 @@ +Convenience macro to generate more complete enums with variants to be used as a type when
+parsing arguments. This enum also provides a variants()
function which can be used to
+retrieve a Vec<&'static str>
of the variant names, as well as implementing FromStr
and
+Display
automatically.
NOTE: Case insensitivity is supported for ASCII characters only. It's highly recommended to
+use Arg::case_insensitive(true)
for args that will be used with these enums
NOTE: This macro automatically implements std::str::FromStr
and std::fmt::Display
NOTE: These enums support pub (or not) and uses of the #[derive()]
traits
+arg_enum!{ + #[derive(PartialEq, Debug)] + pub enum Foo { + Bar, + Baz, + Qux + } +} +// Foo enum can now be used via Foo::Bar, or Foo::Baz, etc +// and implements std::str::FromStr to use with the value_t! macros +fn main() { + let m = App::new("app") + .arg(Arg::from_usage("<foo> 'the foo'") + .possible_values(&Foo::variants()) + .case_insensitive(true)) + .get_matches_from(vec![ + "app", "baz" + ]); + let f = value_t!(m, "foo", Foo).unwrap_or_else(|e| e.exit()); + + assert_eq!(f, Foo::Baz); +}
Redirecting to macro.clap_app.html...
+ + + \ No newline at end of file diff --git a/docs/clap/macro.clap_app.html b/docs/clap/macro.clap_app.html new file mode 100644 index 00000000..9ba8c777 --- /dev/null +++ b/docs/clap/macro.clap_app.html @@ -0,0 +1,107 @@ +Build App
, Arg
s, SubCommand
s and Group
s with Usage-string like input
+but without the associated parsing runtime cost.
clap_app!
also supports several shorthand syntaxes.
+let matches = clap_app!(myapp => + (version: "1.0") + (author: "Kevin K. <kbknapp@gmail.com>") + (about: "Does awesome things") + (@arg CONFIG: -c --config +takes_value "Sets a custom config file") + (@arg INPUT: +required "Sets the input file to use") + (@arg debug: -d ... "Sets the level of debugging information") + (@group difficulty => + (@arg hard: -h --hard "Sets hard mode") + (@arg normal: -n --normal "Sets normal mode") + (@arg easy: -e --easy "Sets easy mode") + ) + (@subcommand test => + (about: "controls testing features") + (version: "1.3") + (author: "Someone E. <someone_else@other.com>") + (@arg verbose: -v --verbose "Print test information verbosely") + ) +) +.get_matches();
-c
) sets the Arg::short
--config
) sets Arg::long
+Arg::long
with a hyphen inside (i.e. --config-file
), you
+must use --("config-file")
due to limitations of the Rust macro system....
) sets Arg::multiple(true)
Arg::value_name
and
+Arg::required(true)
such as --config <FILE>
= Arg::value_name("FILE")
and
+Arg::required(true)
Arg::value_name
and
+Arg::required(false)
such as --config [FILE]
= Arg::value_name("FILE")
and
+Arg::required(false)
true
such as +required
= Arg::required(true)
false
such as !required
= Arg::required(false)
#{min, max}
will set Arg::min_values(min)
and Arg::max_values(max)
*
) will set Arg::required(true)
fn
will set Arg::validator
as in {fn}
= Arg::validator(fn)
conflicts_with[FOO]
will set Arg::conflicts_with("FOO")
(note the lack of quotes around
+FOO
in the macro)Arg::conflicts_with
) followed by square brackets and a list of values separated by spaces
+will set that method such as conflicts_with[FOO BAR BAZ]
will set
+Arg::conflicts_with("FOO")
, Arg::conflicts_with("BAR")
, and Arg::conflicts_with("BAZ")
+(note the lack of quotes around the values in the macro)ArgGroup
methods that accept booleans
+true
such as +required
= ArgGroup::required(true)
false
such as !required
= ArgGroup::required(false)
Redirecting to macro.crate_authors.html...
+ + + \ No newline at end of file diff --git a/docs/clap/macro.crate_authors.html b/docs/clap/macro.crate_authors.html new file mode 100644 index 00000000..4df54582 --- /dev/null +++ b/docs/clap/macro.crate_authors.html @@ -0,0 +1,18 @@ +Allows you to pull the authors for the app from your Cargo.toml at
+compile time in the form:
+"author1 lastname <author1@example.com>:author2 lastname <author2@example.com>"
You can replace the colons with a custom separator by supplying a
+replacement string, so, for example,
+crate_authors!(",\n")
would become
+"author1 lastname <author1@example.com>,\nauthor2 lastname <author2@example.com>,\nauthor3 lastname <author3@example.com>"
+let m = App::new("app") + .author(crate_authors!("\n")) + .get_matches();
Redirecting to macro.crate_description.html...
+ + + \ No newline at end of file diff --git a/docs/clap/macro.crate_description.html b/docs/clap/macro.crate_description.html new file mode 100644 index 00000000..7852ced4 --- /dev/null +++ b/docs/clap/macro.crate_description.html @@ -0,0 +1,11 @@ +Allows you to pull the description from your Cargo.toml at compile time.
++let m = App::new("app") + .about(crate_description!()) + .get_matches();
Redirecting to macro.crate_name.html...
+ + + \ No newline at end of file diff --git a/docs/clap/macro.crate_name.html b/docs/clap/macro.crate_name.html new file mode 100644 index 00000000..0a958a8a --- /dev/null +++ b/docs/clap/macro.crate_name.html @@ -0,0 +1,10 @@ +Allows you to pull the name from your Cargo.toml at compile time.
++let m = App::new(crate_name!()) + .get_matches();
Redirecting to macro.crate_version.html...
+ + + \ No newline at end of file diff --git a/docs/clap/macro.crate_version.html b/docs/clap/macro.crate_version.html new file mode 100644 index 00000000..ea476857 --- /dev/null +++ b/docs/clap/macro.crate_version.html @@ -0,0 +1,12 @@ +Allows you to pull the version from your Cargo.toml at compile time as
+MAJOR.MINOR.PATCH_PKGVERSION_PRE
+let m = App::new("app") + .version(crate_version!()) + .get_matches();
Redirecting to macro.load_yaml.html...
+ + + \ No newline at end of file diff --git a/docs/clap/macro.load_yaml.html b/docs/clap/macro.load_yaml.html new file mode 100644 index 00000000..b12d72f6 --- /dev/null +++ b/docs/clap/macro.load_yaml.html @@ -0,0 +1,20 @@ +A convenience macro for loading the YAML file at compile time (relative to the current file, +like modules work). That YAML object can then be passed to this function.
+The YAML file must be properly formatted or this function will panic!(). A good way to
+ensure this doesn't happen is to run your program with the --help
switch. If this passes
+without error, you needn't worry because the YAML is properly formatted.
The following example shows how to load a properly formatted YAML file to build an instance
+of an App
struct.
+let yml = load_yaml!("app.yml"); +let app = App::from_yaml(yml); + +// continued logic goes here, such as `app.get_matches()` etc.
Redirecting to macro.value_t.html...
+ + + \ No newline at end of file diff --git a/docs/clap/macro.value_t.html b/docs/clap/macro.value_t.html new file mode 100644 index 00000000..1e08e8e5 --- /dev/null +++ b/docs/clap/macro.value_t.html @@ -0,0 +1,21 @@ +Convenience macro getting a typed value T
where T
implements std::str::FromStr
from an
+argument value. This macro returns a Result<T,String>
which allows you as the developer to
+decide what you'd like to do on a failed parse. There are two types of errors, parse failures
+and those where the argument wasn't present (such as a non-required argument). You can use
+it to get a single value, or a iterator as with the ArgMatches::values_of
+let matches = App::new("myapp") + .arg_from_usage("[length] 'Set the length to use as a pos whole num, i.e. 20'") + .get_matches(); + +let len = value_t!(matches.value_of("length"), u32).unwrap_or_else(|e| e.exit()); +let also_len = value_t!(matches, "length", u32).unwrap_or_else(|e| e.exit()); + +println!("{} + 2: {}", len, len + 2);
Redirecting to macro.value_t_or_exit.html...
+ + + \ No newline at end of file diff --git a/docs/clap/macro.value_t_or_exit.html b/docs/clap/macro.value_t_or_exit.html new file mode 100644 index 00000000..6c5aabd1 --- /dev/null +++ b/docs/clap/macro.value_t_or_exit.html @@ -0,0 +1,20 @@ +Convenience macro getting a typed value T
where T
implements std::str::FromStr
or
+exiting upon error, instead of returning a Result
type.
NOTE: This macro is for backwards compatibility sake. Prefer
+value_t!(/* ... */).unwrap_or_else(|e| e.exit())
+let matches = App::new("myapp") + .arg_from_usage("[length] 'Set the length to use as a pos whole num, i.e. 20'") + .get_matches(); + +let len = value_t_or_exit!(matches.value_of("length"), u32); +let also_len = value_t_or_exit!(matches, "length", u32); + +println!("{} + 2: {}", len, len + 2);
Redirecting to macro.values_t.html...
+ + + \ No newline at end of file diff --git a/docs/clap/macro.values_t.html b/docs/clap/macro.values_t.html new file mode 100644 index 00000000..70fe2853 --- /dev/null +++ b/docs/clap/macro.values_t.html @@ -0,0 +1,24 @@ +Convenience macro getting a typed value Vec<T>
where T
implements std::str::FromStr
+This macro returns a clap::Result<Vec<T>>
which allows you as the developer to decide
+what you'd like to do on a failed parse.
+let matches = App::new("myapp") + .arg_from_usage("[seq]... 'A sequence of pos whole nums, i.e. 20 45'") + .get_matches(); + +let vals = values_t!(matches.values_of("seq"), u32).unwrap_or_else(|e| e.exit()); +for v in &vals { + println!("{} + 2: {}", v, v + 2); +} + +let vals = values_t!(matches, "seq", u32).unwrap_or_else(|e| e.exit()); +for v in &vals { + println!("{} + 2: {}", v, v + 2); +}
Redirecting to macro.values_t_or_exit.html...
+ + + \ No newline at end of file diff --git a/docs/clap/macro.values_t_or_exit.html b/docs/clap/macro.values_t_or_exit.html new file mode 100644 index 00000000..a57e599f --- /dev/null +++ b/docs/clap/macro.values_t_or_exit.html @@ -0,0 +1,26 @@ +Convenience macro getting a typed value Vec<T>
where T
implements std::str::FromStr
+or exiting upon error.
NOTE: This macro is for backwards compatibility sake. Prefer
+values_t!(/* ... */).unwrap_or_else(|e| e.exit())
+let matches = App::new("myapp") + .arg_from_usage("[seq]... 'A sequence of pos whole nums, i.e. 20 45'") + .get_matches(); + +let vals = values_t_or_exit!(matches.values_of("seq"), u32); +for v in &vals { + println!("{} + 2: {}", v, v + 2); +} + +// type for example only +let vals: Vec<u32> = values_t_or_exit!(matches, "seq", u32); +for v in &vals { + println!("{} + 2: {}", v, v + 2); +}
Used to create a representation of a command line program and all possible command line
+arguments. Application settings are set using the "builder pattern" with the
+App::get_matches
family of methods being the terminal methods that starts the
+runtime-parsing process. These methods then return information about the user supplied
+arguments (or lack there of).
NOTE: There aren't any mandatory "options" that one must set. The "options" may
+also appear in any order (so long as one of the App::get_matches
methods is the last method
+called).
+let m = App::new("My Program") + .author("Me, me@mail.com") + .version("1.0.2") + .about("Explains in brief what the program does") + .arg( + Arg::with_name("in_file").index(1) + ) + .after_help("Longer explanation to appear after the options when \ + displaying the help information from --help or -h") + .get_matches(); + +// Your program logic starts here...
impl<'a, 'b> App<'a, 'b>
[src]pub fn new<S: Into<String>>(n: S) -> Self
[src]Creates a new instance of an application requiring a name. The name may be, but doesn't +have to be same as the binary. The name will be displayed to the user when they request to +print version or help and usage information.
++let prog = App::new("My Program")
pub fn get_name(&self) -> &str
[src]Get the name of the app
+pub fn get_bin_name(&self) -> Option<&str>
[src]Get the name of the binary
+pub fn with_defaults<S: Into<String>>(n: S) -> Self
[src]Can never work; use explicit App::author() and App::version() calls instead
+Creates a new instance of an application requiring a name, but uses the crate_authors!
+and crate_version!
macros to fill in the App::author
and App::version
fields.
+let prog = App::with_defaults("My Program")
pub fn from_yaml(yaml: &'a Yaml) -> App<'a, 'a>
[src]Creates a new instance of App
from a .yml (YAML) file. A full example of supported YAML
+objects can be found in examples/17_yaml.rs
and examples/17_yaml.yml
. One great use
+for using YAML is when supporting multiple languages and dialects, as each language could
+be a distinct YAML file and determined at compiletime via cargo
"features" in your
+Cargo.toml
In order to use this function you must compile clap
with the features = ["yaml"]
in
+your settings for the [dependencies.clap]
table of your Cargo.toml
NOTE: Due to how the YAML objects are built there is a convenience macro for loading +the YAML file at compile time (relative to the current file, like modules work). That YAML +object can then be passed to this function.
+The YAML file must be properly formatted or this function will panic!
. A good way to
+ensure this doesn't happen is to run your program with the --help
switch. If this passes
+without error, you needn't worry because the YAML is properly formatted.
The following example shows how to load a properly formatted YAML file to build an instance
+of an App
struct.
+let yml = load_yaml!("app.yml"); +let app = App::from_yaml(yml); + +// continued logic goes here, such as `app.get_matches()` etc.
pub fn author<S: Into<&'b str>>(self, author: S) -> Self
[src]Sets a string of author(s) that will be displayed to the user when they
+request the help information with --help
or -h
.
Pro-tip: Use clap
s convenience macro crate_authors!
to automatically set your
+application's author(s) to the same thing as your crate at compile time. See the examples/
+directory for more information
See the examples/
+directory for more information
+App::new("myprog") + .author("Me, me@mymain.com")
pub fn bin_name<S: Into<String>>(self, name: S) -> Self
[src]Overrides the system-determined binary name. This should only be used when absolutely +necessary, such as when the binary name for your application is misleading, or perhaps +not how the user should invoke your program.
+Pro-tip: When building things such as third party cargo
subcommands, this setting
+should be used!
NOTE: This command should not be used for SubCommand
s.
+App::new("My Program") + .bin_name("my_binary")
pub fn about<S: Into<&'b str>>(self, about: S) -> Self
[src]Sets a string describing what the program does. This will be displayed when displaying help
+information with -h
.
NOTE: If only about
is provided, and not App::long_about
but the user requests
+--help
clap will still display the contents of about
appropriately
NOTE: Only [App::about
] is used in completion script generation in order to be
+concise
+App::new("myprog") + .about("Does really amazing things to great people")
pub fn long_about<S: Into<&'b str>>(self, about: S) -> Self
[src]Sets a string describing what the program does. This will be displayed when displaying help +information.
+NOTE: If only long_about
is provided, and not App::about
but the user requests
+-h
clap will still display the contents of long_about
appropriately
NOTE: Only App::about
is used in completion script generation in order to be
+concise
+App::new("myprog") + .long_about( +"Does really amazing things to great people. Now let's talk a little + more in depth about how this subcommand really works. It may take about + a few lines of text, but that's ok!")
pub fn name<S: Into<String>>(self, name: S) -> Self
[src]Sets the program's name. This will be displayed when displaying help information.
+Pro-top: This function is particularly useful when configuring a program via
+App::from_yaml
in conjunction with the crate_name!
macro to derive the program's
+name from its Cargo.toml
.
+let yml = load_yaml!("app.yml"); +let app = App::from_yaml(yml) + .name(crate_name!()); + +// continued logic goes here, such as `app.get_matches()` etc.
pub fn after_help<S: Into<&'b str>>(self, help: S) -> Self
[src]Adds additional help information to be displayed in addition to auto-generated help. This +information is displayed after the auto-generated help information. This is often used +to describe how to use the arguments, or caveats to be noted.
++App::new("myprog") + .after_help("Does really amazing things to great people...but be careful with -R")
pub fn before_help<S: Into<&'b str>>(self, help: S) -> Self
[src]Adds additional help information to be displayed in addition to auto-generated help. This +information is displayed before the auto-generated help information. This is often used +for header information.
++App::new("myprog") + .before_help("Some info I'd like to appear before the help info")
pub fn version<S: Into<&'b str>>(self, ver: S) -> Self
[src]Sets a string of the version number to be displayed when displaying version or help
+information with -V
.
NOTE: If only version
is provided, and not App::long_version
but the user
+requests --version
clap will still display the contents of version
appropriately
Pro-tip: Use clap
s convenience macro crate_version!
to automatically set your
+application's version to the same thing as your crate at compile time. See the examples/
+directory for more information
+App::new("myprog") + .version("v0.1.24")
pub fn long_version<S: Into<&'b str>>(self, ver: S) -> Self
[src]Sets a string of the version number to be displayed when displaying version or help
+information with --version
.
NOTE: If only long_version
is provided, and not App::version
but the user
+requests -V
clap will still display the contents of long_version
appropriately
Pro-tip: Use clap
s convenience macro crate_version!
to automatically set your
+application's version to the same thing as your crate at compile time. See the examples/
+directory for more information
+App::new("myprog") + .long_version( +"v0.1.24 + commit: abcdef89726d + revision: 123 + release: 2 + binary: myprog")
pub fn usage<S: Into<&'b str>>(self, usage: S) -> Self
[src]Sets a custom usage string to override the auto-generated usage string.
+This will be displayed to the user when errors are found in argument parsing, or when you
+call ArgMatches::usage
CAUTION: Using this setting disables clap
s "context-aware" usage strings. After this
+setting is set, this will be the only usage string displayed to the user!
NOTE: You do not need to specify the "USAGE: \n\t" portion, as that will
+still be applied by clap
, you only need to specify the portion starting
+with the binary name.
NOTE: This will not replace the entire help message, only the portion +showing the usage.
++App::new("myprog") + .usage("myapp [-clDas] <some_file>")
pub fn help<S: Into<&'b str>>(self, help: S) -> Self
[src]Sets a custom help message and overrides the auto-generated one. This should only be used +when the auto-generated message does not suffice.
+This will be displayed to the user when they use --help
or -h
NOTE: This replaces the entire help message, so nothing will be auto-generated.
+NOTE: This only replaces the help message for the current command, meaning if you
+are using subcommands, those help messages will still be auto-generated unless you
+specify a Arg::help
for them as well.
+App::new("myapp") + .help("myapp v1.0\n\ + Does awesome things\n\ + (C) me@mail.com\n\n\ + + USAGE: myapp <opts> <command>\n\n\ + + Options:\n\ + -h, --help Display this message\n\ + -V, --version Display version info\n\ + -s <stuff> Do something with stuff\n\ + -v Be verbose\n\n\ + + Commmands:\n\ + help Prints this message\n\ + work Do some work")
pub fn help_short<S: AsRef<str> + 'b>(self, s: S) -> Self
[src]Sets the short
for the auto-generated help
argument.
By default clap
automatically assigns h
, but this can be overridden if you have a
+different argument which you'd prefer to use the -h
short with. This can be done by
+defining your own argument with a lowercase h
as the short
.
clap
lazily generates these help
arguments after you've defined any arguments of
+your own.
NOTE: Any leading -
characters will be stripped, and only the first
+non -
character will be used as the short
version
+App::new("myprog") + .help_short("H") // Using an uppercase `H` instead of the default lowercase `h`
pub fn version_short<S: AsRef<str>>(self, s: S) -> Self
[src]Sets the short
for the auto-generated version
argument.
By default clap
automatically assigns V
, but this can be overridden if you have a
+different argument which you'd prefer to use the -V
short with. This can be done by
+defining your own argument with an uppercase V
as the short
.
clap
lazily generates these version
arguments after you've defined any arguments of
+your own.
NOTE: Any leading -
characters will be stripped, and only the first
+non -
character will be used as the short
version
+App::new("myprog") + .version_short("v") // Using a lowercase `v` instead of the default capital `V`
pub fn help_message<S: Into<&'a str>>(self, s: S) -> Self
[src]Sets the help text for the auto-generated help
argument.
By default clap
sets this to "Prints help information"
, but if you're using a
+different convention for your help messages and would prefer a different phrasing you can
+override it.
+App::new("myprog") + .help_message("Print help information") // Perhaps you want imperative help messages +
pub fn version_message<S: Into<&'a str>>(self, s: S) -> Self
[src]Sets the help text for the auto-generated version
argument.
By default clap
sets this to "Prints version information"
, but if you're using a
+different convention for your help messages and would prefer a different phrasing then you
+can change it.
+App::new("myprog") + .version_message("Print version information") // Perhaps you want imperative help messages
pub fn template<S: Into<&'b str>>(self, s: S) -> Self
[src]Sets the help template to be used, overriding the default format.
+Tags arg given inside curly brackets.
+Valid tags are:
+{bin}
- Binary name.{version}
- Version number.{author}
- Author information.{about}
- General description (from App::about
){usage}
- Automatically generated or given usage string.{all-args}
- Help for all arguments (options, flags, positionals arguments,
+and subcommands) including titles.{unified}
- Unified help for options and flags. Note, you must also set
+AppSettings::UnifiedHelpMessage
to fully merge both options and
+flags, otherwise the ordering is "best effort"{flags}
- Help for flags.{options}
- Help for options.{positionals}
- Help for positionals arguments.{subcommands}
- Help for subcommands.{after-help}
- Help from App::after_help
{before-help}
- Help from App::before_help
+App::new("myprog") + .version("1.0") + .template("{bin} ({version}) - {usage}")
NOTE: The template system is, on purpose, very simple. Therefore the tags have to be +written in lowercase and without spacing.
+pub fn setting(self, setting: AppSettings) -> Self
[src]Enables a single command, or SubCommand
, level settings.
See AppSettings
for a full list of possibilities and examples.
+App::new("myprog") + .setting(AppSettings::SubcommandRequired) + .setting(AppSettings::WaitOnError)
pub fn settings(self, settings: &[AppSettings]) -> Self
[src]Enables multiple command, or SubCommand
, level settings
See AppSettings
for a full list of possibilities and examples.
+App::new("myprog") + .settings(&[AppSettings::SubcommandRequired, + AppSettings::WaitOnError])
pub fn global_setting(self, setting: AppSettings) -> Self
[src]Enables a single setting that is propagated down through all child SubCommand
s.
See AppSettings
for a full list of possibilities and examples.
NOTE: The setting is only propagated down and not up through parent commands.
++App::new("myprog") + .global_setting(AppSettings::SubcommandRequired)
pub fn global_settings(self, settings: &[AppSettings]) -> Self
[src]Enables multiple settings which are propagated down through all child SubCommand
s.
See AppSettings
for a full list of possibilities and examples.
NOTE: The setting is only propagated down and not up through parent commands.
++App::new("myprog") + .global_settings(&[AppSettings::SubcommandRequired, + AppSettings::ColoredHelp])
pub fn unset_setting(self, setting: AppSettings) -> Self
[src]Disables a single command, or SubCommand
, level setting.
See AppSettings
for a full list of possibilities and examples.
+App::new("myprog") + .unset_setting(AppSettings::ColorAuto)
pub fn unset_settings(self, settings: &[AppSettings]) -> Self
[src]Disables multiple command, or SubCommand
, level settings.
See AppSettings
for a full list of possibilities and examples.
+App::new("myprog") + .unset_settings(&[AppSettings::ColorAuto, + AppSettings::AllowInvalidUtf8])
pub fn set_term_width(self, width: usize) -> Self
[src]Sets the terminal width at which to wrap help messages. Defaults to 120
. Using 0
will
+ignore terminal widths and use source formatting.
clap
automatically tries to determine the terminal width on Unix, Linux, macOS and Windows
+if the wrap_help
cargo "feature" has been used while compiling. If the terminal width
+cannot be determined, clap
defaults to 120
.
NOTE: This setting applies globally and not on a per-command basis.
+NOTE: This setting must be set before any subcommands are added!
+Only Unix, Linux, macOS and Windows support automatic determination of terminal width. +Even on those platforms, this setting is useful if for any reason the terminal width +cannot be determined.
++App::new("myprog") + .set_term_width(80)
pub fn max_term_width(self, w: usize) -> Self
[src]Sets the max terminal width at which to wrap help messages. Using 0
will ignore terminal
+widths and use source formatting.
clap
automatically tries to determine the terminal width on Unix, Linux, macOS and Windows
+if the wrap_help
cargo "feature" has been used while compiling, but one might want to
+limit the size (e.g. when the terminal is running fullscreen).
NOTE: This setting applies globally and not on a per-command basis.
+NOTE: This setting must be set before any subcommands are added!
+Only Unix, Linux, macOS and Windows support automatic determination of terminal width.
++App::new("myprog") + .max_term_width(100)
pub fn arg<A: Into<Arg<'a, 'b>>>(self, a: A) -> Self
[src]Adds an argument to the list of valid possibilities.
++App::new("myprog") + // Adding a single "flag" argument with a short and help text, using Arg::with_name() + .arg( + Arg::with_name("debug") + .short("d") + .help("turns on debugging mode") + ) + // Adding a single "option" argument with a short, a long, and help text using the less + // verbose Arg::from_usage() + .arg( + Arg::from_usage("-c --config=[CONFIG] 'Optionally sets a config file to use'") + )
pub fn args(self, args: &[Arg<'a, 'b>]) -> Self
[src]Adds multiple arguments to the list of valid possibilities
++App::new("myprog") + .args( + &[Arg::from_usage("[debug] -d 'turns on debugging info'"), + Arg::with_name("input").index(1).help("the input file to use")] + )
pub fn arg_from_usage(self, usage: &'a str) -> Self
[src]A convenience method for adding a single argument from a usage type string. The string
+used follows the same rules and syntax as Arg::from_usage
NOTE: The downside to using this method is that you can not set any additional
+properties of the Arg
other than what Arg::from_usage
supports.
+App::new("myprog") + .arg_from_usage("-c --config=<FILE> 'Sets a configuration file to use'")
pub fn args_from_usage(self, usage: &'a str) -> Self
[src]Adds multiple arguments at once from a usage string, one per line. See
+Arg::from_usage
for details on the syntax and rules supported.
NOTE: Like App::arg_from_usage
the downside is you only set properties for the
+Arg
s which Arg::from_usage
supports.
+App::new("myprog") + .args_from_usage( + "-c --config=[FILE] 'Sets a configuration file to use' + [debug]... -d 'Sets the debugging level' + <FILE> 'The input file to use'" + )
pub fn alias<S: Into<&'b str>>(self, name: S) -> Self
[src]Allows adding a SubCommand
alias, which function as "hidden" subcommands that
+automatically dispatch as if this subcommand was used. This is more efficient, and easier
+than creating multiple hidden subcommands as one only needs to check for the existence of
+this command, and not all variants.
+let m = App::new("myprog") + .subcommand(SubCommand::with_name("test") + .alias("do-stuff")) + .get_matches_from(vec!["myprog", "do-stuff"]); +assert_eq!(m.subcommand_name(), Some("test"));
pub fn aliases(self, names: &[&'b str]) -> Self
[src]Allows adding SubCommand
aliases, which function as "hidden" subcommands that
+automatically dispatch as if this subcommand was used. This is more efficient, and easier
+than creating multiple hidden subcommands as one only needs to check for the existence of
+this command, and not all variants.
+let m = App::new("myprog") + .subcommand(SubCommand::with_name("test") + .aliases(&["do-stuff", "do-tests", "tests"])) + .arg(Arg::with_name("input") + .help("the file to add") + .index(1) + .required(false)) + .get_matches_from(vec!["myprog", "do-tests"]); +assert_eq!(m.subcommand_name(), Some("test"));
pub fn visible_alias<S: Into<&'b str>>(self, name: S) -> Self
[src]Allows adding a SubCommand
alias that functions exactly like those defined with
+App::alias
, except that they are visible inside the help message.
+let m = App::new("myprog") + .subcommand(SubCommand::with_name("test") + .visible_alias("do-stuff")) + .get_matches_from(vec!["myprog", "do-stuff"]); +assert_eq!(m.subcommand_name(), Some("test"));
pub fn visible_aliases(self, names: &[&'b str]) -> Self
[src]Allows adding multiple SubCommand
aliases that functions exactly like those defined
+with App::aliases
, except that they are visible inside the help message.
+let m = App::new("myprog") + .subcommand(SubCommand::with_name("test") + .visible_aliases(&["do-stuff", "tests"])) + .get_matches_from(vec!["myprog", "do-stuff"]); +assert_eq!(m.subcommand_name(), Some("test"));
pub fn group(self, group: ArgGroup<'a>) -> Self
[src]Adds an ArgGroup
to the application. ArgGroup
s are a family of related arguments.
+By placing them in a logical group, you can build easier requirement and exclusion rules.
+For instance, you can make an entire ArgGroup
required, meaning that one (and only
+one) argument from that group must be present at runtime.
You can also do things such as name an ArgGroup
as a conflict to another argument.
+Meaning any of the arguments that belong to that group will cause a failure if present with
+the conflicting argument.
Another added benefit of ArgGroup
s is that you can extract a value from a group instead
+of determining exactly which argument was used.
Finally, using ArgGroup
s to ensure exclusion between arguments is another very common
+use
The following example demonstrates using an ArgGroup
to ensure that one, and only one,
+of the arguments from the specified group is present at runtime.
+App::new("app") + .args_from_usage( + "--set-ver [ver] 'set the version manually' + --major 'auto increase major' + --minor 'auto increase minor' + --patch 'auto increase patch'") + .group(ArgGroup::with_name("vers") + .args(&["set-ver", "major", "minor","patch"]) + .required(true))
pub fn groups(self, groups: &[ArgGroup<'a>]) -> Self
[src]Adds multiple ArgGroup
s to the App
at once.
+App::new("app") + .args_from_usage( + "--set-ver [ver] 'set the version manually' + --major 'auto increase major' + --minor 'auto increase minor' + --patch 'auto increase patch' + -c [FILE] 'a config file' + -i [IFACE] 'an interface'") + .groups(&[ + ArgGroup::with_name("vers") + .args(&["set-ver", "major", "minor","patch"]) + .required(true), + ArgGroup::with_name("input") + .args(&["c", "i"]) + ])
pub fn subcommand(self, subcmd: App<'a, 'b>) -> Self
[src]Adds a SubCommand
to the list of valid possibilities. Subcommands are effectively
+sub-App
s, because they can contain their own arguments, subcommands, version, usage,
+etc. They also function just like App
s, in that they get their own auto generated help,
+version, and usage.
+App::new("myprog") + .subcommand(SubCommand::with_name("config") + .about("Controls configuration features") + .arg_from_usage("<config> 'Required configuration file to use'"))
pub fn subcommands<I>(self, subcmds: I) -> Self where
I: IntoIterator<Item = App<'a, 'b>>,
[src]Adds multiple subcommands to the list of valid possibilities by iterating over an
+IntoIterator
of SubCommand
s
+.subcommands( vec![ + SubCommand::with_name("config").about("Controls configuration functionality") + .arg(Arg::with_name("config_file").index(1)), + SubCommand::with_name("debug").about("Controls debug functionality")])
pub fn display_order(self, ord: usize) -> Self
[src]Allows custom ordering of SubCommand
s within the help message. Subcommands with a lower
+value will be displayed first in the help message. This is helpful when one would like to
+emphasise frequently used subcommands, or prioritize those towards the top of the list.
+Duplicate values are allowed. Subcommands with duplicate display orders will be
+displayed in alphabetical order.
NOTE: The default is 999 for all subcommands.
++let m = App::new("cust-ord") + .subcommand(SubCommand::with_name("alpha") // typically subcommands are grouped + // alphabetically by name. Subcommands + // without a display_order have a value of + // 999 and are displayed alphabetically with + // all other 999 subcommands + .about("Some help and text")) + .subcommand(SubCommand::with_name("beta") + .display_order(1) // In order to force this subcommand to appear *first* + // all we have to do is give it a value lower than 999. + // Any other subcommands with a value of 1 will be displayed + // alphabetically with this one...then 2 values, then 3, etc. + .about("I should be first!")) + .get_matches_from(vec![ + "cust-ord", "--help" + ]);
The above example displays the following help message
+cust-ord
+
+USAGE:
+ cust-ord [FLAGS] [OPTIONS]
+
+FLAGS:
+ -h, --help Prints help information
+ -V, --version Prints version information
+
+SUBCOMMANDS:
+ beta I should be first!
+ alpha Some help and text
+
+pub fn print_help(&mut self) -> ClapResult<()>
[src]Prints the full help message to io::stdout()
using a BufWriter
using the same
+method as if someone ran -h
to request the help message
NOTE: clap has the ability to distinguish between "short" and "long" help messages
+depending on if the user ran -h
(short) or --help
(long)
+let mut app = App::new("myprog"); +app.print_help();
pub fn print_long_help(&mut self) -> ClapResult<()>
[src]Prints the full help message to io::stdout()
using a BufWriter
using the same
+method as if someone ran --help
to request the help message
NOTE: clap has the ability to distinguish between "short" and "long" help messages
+depending on if the user ran -h
(short) or --help
(long)
+let mut app = App::new("myprog"); +app.print_long_help();
pub fn write_help<W: Write>(&self, w: &mut W) -> ClapResult<()>
[src]Writes the full help message to the user to a io::Write
object in the same method as if
+the user ran -h
NOTE: clap has the ability to distinguish between "short" and "long" help messages
+depending on if the user ran -h
(short) or --help
(long)
NOTE: There is a known bug where this method does not write propagated global arguments
+or autogenerated arguments (i.e. the default help/version args). Prefer
+[App::write_long_help
] instead if possible!
+use std::io; +let mut app = App::new("myprog"); +let mut out = io::stdout(); +app.write_help(&mut out).expect("failed to write to stdout");
pub fn write_long_help<W: Write>(&mut self, w: &mut W) -> ClapResult<()>
[src]Writes the full help message to the user to a io::Write
object in the same method as if
+the user ran --help
NOTE: clap has the ability to distinguish between "short" and "long" help messages
+depending on if the user ran -h
(short) or --help
(long)
+use std::io; +let mut app = App::new("myprog"); +let mut out = io::stdout(); +app.write_long_help(&mut out).expect("failed to write to stdout");
pub fn write_version<W: Write>(&self, w: &mut W) -> ClapResult<()>
[src]Writes the version message to the user to a io::Write
object as if the user ran -V
.
NOTE: clap has the ability to distinguish between "short" and "long" version messages
+depending on if the user ran -V
(short) or --version
(long)
+use std::io; +let mut app = App::new("myprog"); +let mut out = io::stdout(); +app.write_version(&mut out).expect("failed to write to stdout");
pub fn write_long_version<W: Write>(&self, w: &mut W) -> ClapResult<()>
[src]Writes the version message to the user to a io::Write
object
NOTE: clap has the ability to distinguish between "short" and "long" version messages
+depending on if the user ran -V
(short) or --version
(long)
+use std::io; +let mut app = App::new("myprog"); +let mut out = io::stdout(); +app.write_long_version(&mut out).expect("failed to write to stdout");
pub fn gen_completions<T: Into<OsString>, S: Into<String>>(
&mut self,
bin_name: S,
for_shell: Shell,
out_dir: T
)
[src]Generate a completions file for a specified shell at compile time.
+NOTE: to generate the file at compile time you must use a build.rs
"Build Script"
The following example generates a bash completion script via a build.rs
script. In this
+simple example, we'll demo a very small application with only a single subcommand and two
+args. Real applications could be many multiple levels deep in subcommands, and have tens or
+potentially hundreds of arguments.
First, it helps if we separate out our App
definition into a separate file. Whether you
+do this as a function, or bare App definition is a matter of personal preference.
+// src/cli.rs + +use clap::{App, Arg, SubCommand}; + +pub fn build_cli() -> App<'static, 'static> { + App::new("compl") + .about("Tests completions") + .arg(Arg::with_name("file") + .help("some input file")) + .subcommand(SubCommand::with_name("test") + .about("tests things") + .arg(Arg::with_name("case") + .long("case") + .takes_value(true) + .help("the case to test"))) +}
In our regular code, we can simply call this build_cli()
function, then call
+get_matches()
, or any of the other normal methods directly after. For example:
+// src/main.rs + +mod cli; + +fn main() { + let m = cli::build_cli().get_matches(); + + // normal logic continues... +}
Next, we set up our Cargo.toml
to use a build.rs
build script.
# Cargo.toml
+build = "build.rs"
+
+[build-dependencies]
+clap = "2.23"
+
+Next, we place a build.rs
in our project root.
+extern crate clap; + +use clap::Shell; + +include!("src/cli.rs"); + +fn main() { + let outdir = match env::var_os("OUT_DIR") { + None => return, + Some(outdir) => outdir, + }; + let mut app = build_cli(); + app.gen_completions("myapp", // We need to specify the bin name manually + Shell::Bash, // Then say which shell to build completions for + outdir); // Then say where write the completions to +}
Now, once we compile there will be a {bin_name}.bash
file in the directory.
+Assuming we compiled with debug mode, it would be somewhere similar to
+<project>/target/debug/build/myapp-<hash>/out/myapp.bash
.
Fish shell completions will use the file format {bin_name}.fish
pub fn gen_completions_to<W: Write, S: Into<String>>(
&mut self,
bin_name: S,
for_shell: Shell,
buf: &mut W
)
[src]Generate a completions file for a specified shell at runtime. Until cargo install
can
+install extra files like a completion script, this may be used e.g. in a command that
+outputs the contents of the completion script, to be redirected into a file by the user.
Assuming a separate cli.rs
like the example above,
+we can let users generate a completion script using a command:
+// src/main.rs + +mod cli; +use std::io; + +fn main() { + let matches = cli::build_cli().get_matches(); + + if matches.is_present("generate-bash-completions") { + cli::build_cli().gen_completions_to("myapp", Shell::Bash, &mut io::stdout()); + } + + // normal logic continues... +} +
Usage:
+$ myapp generate-bash-completions > /usr/share/bash-completion/completions/myapp.bash
+
+pub fn get_matches(self) -> ArgMatches<'a>
[src]Starts the parsing process, upon a failed parse an error will be displayed to the user and
+the process will exit with the appropriate error code. By default this method gets all user
+provided arguments from env::args_os
in order to allow for invalid UTF-8 code points,
+which are legal on many platforms.
+let matches = App::new("myprog") + // Args and options go here... + .get_matches();
pub fn get_matches_safe(self) -> ClapResult<ArgMatches<'a>>
[src]Starts the parsing process. This method will return a clap::Result
type instead of exiting
+the process on failed parse. By default this method gets matches from env::args_os
NOTE: This method WILL NOT exit when --help
or --version
(or short versions) are
+used. It will return a clap::Error
, where the kind
is a
+ErrorKind::HelpDisplayed
or ErrorKind::VersionDisplayed
respectively. You must call
+Error::exit
or perform a std::process::exit
.
+let matches = App::new("myprog") + // Args and options go here... + .get_matches_safe() + .unwrap_or_else( |e| e.exit() );
pub fn get_matches_from<I, T>(self, itr: I) -> ArgMatches<'a> where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
[src]Starts the parsing process. Like App::get_matches
this method does not return a clap::Result
+and will automatically exit with an error message. This method, however, lets you specify
+what iterator to use when performing matches, such as a Vec
of your making.
NOTE: The first argument will be parsed as the binary name unless
+AppSettings::NoBinaryName
is used
+let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + +let matches = App::new("myprog") + // Args and options go here... + .get_matches_from(arg_vec);
pub fn get_matches_from_safe<I, T>(self, itr: I) -> ClapResult<ArgMatches<'a>> where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
[src]Starts the parsing process. A combination of App::get_matches_from
, and
+App::get_matches_safe
NOTE: This method WILL NOT exit when --help
or --version
(or short versions) are
+used. It will return a clap::Error
, where the kind
is a ErrorKind::HelpDisplayed
+or ErrorKind::VersionDisplayed
respectively. You must call Error::exit
or
+perform a std::process::exit
yourself.
NOTE: The first argument will be parsed as the binary name unless
+AppSettings::NoBinaryName
is used
+let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + +let matches = App::new("myprog") + // Args and options go here... + .get_matches_from_safe(arg_vec) + .unwrap_or_else( |e| { panic!("An error occurs: {}", e) });
pub fn get_matches_from_safe_borrow<I, T>(
&mut self,
itr: I
) -> ClapResult<ArgMatches<'a>> where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
[src]Starts the parsing process without consuming the App
struct self
. This is normally not
+the desired functionality, instead prefer App::get_matches_from_safe
which does
+consume self
.
NOTE: The first argument will be parsed as the binary name unless
+AppSettings::NoBinaryName
is used
+let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + +let mut app = App::new("myprog"); + // Args and options go here... +let matches = app.get_matches_from_safe_borrow(arg_vec) + .unwrap_or_else( |e| { panic!("An error occurs: {}", e) });
impl<'a, 'b> Clone for App<'a, 'b>
[src]fn clone(&self) -> Self
[src]fn clone_from(&mut self, source: &Self)
1.0.0[src]impl<'n, 'e> Display for App<'n, 'e>
[src]impl<'a> From<&'a Yaml> for App<'a, 'a>
[src]impl<'a, 'b> !RefUnwindSafe for App<'a, 'b>
impl<'a, 'b> !Send for App<'a, 'b>
impl<'a, 'b> !Sync for App<'a, 'b>
impl<'a, 'b> Unpin for App<'a, 'b>
impl<'a, 'b> !UnwindSafe for App<'a, 'b>
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<T> ToOwned for T where
T: Clone,
[src]type Owned = T
The resulting type after obtaining ownership.
+fn to_owned(&self) -> T
[src]fn clone_into(&self, target: &mut T)
[src]impl<T> ToString for T where
T: Display + ?Sized,
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]The abstract representation of a command line argument. Used to set all the options and +relationships that define a valid argument for the program.
+There are two methods for constructing Arg
s, using the builder pattern and setting options
+manually, or using a usage string which is far less verbose but has fewer options. You can also
+use a combination of the two methods to achieve the best of both worlds.
+// Using the traditional builder pattern and setting each option manually +let cfg = Arg::with_name("config") + .short("c") + .long("config") + .takes_value(true) + .value_name("FILE") + .help("Provides a config file to myprog"); +// Using a usage string (setting a similar argument to the one above) +let input = Arg::from_usage("-i, --input=[FILE] 'Provides an input file to the program'");
impl<'a, 'b> Arg<'a, 'b>
[src]pub fn with_name(n: &'a str) -> Self
[src]Creates a new instance of Arg
using a unique string name. The name will be used to get
+information about whether or not the argument was used at runtime, get values, set
+relationships with other args, etc..
NOTE: In the case of arguments that take values (i.e. Arg::takes_value(true)
)
+and positional arguments (i.e. those without a preceding -
or --
) the name will also
+be displayed when the user prints the usage/help information of the program.
+Arg::with_name("config")
pub fn from_yaml(y: &BTreeMap<Yaml, Yaml>) -> Arg
[src]Creates a new instance of Arg
from a .yml (YAML) file.
+let yml = load_yaml!("arg.yml"); +let arg = Arg::from_yaml(yml);
pub fn from_usage(u: &'a str) -> Self
[src]Creates a new instance of Arg
from a usage string. Allows creation of basic settings
+for the Arg
. The syntax is flexible, but there are some rules to follow.
NOTE: Not all settings may be set using the usage string method. Some properties are +only available via the builder pattern.
+NOTE: Only ASCII values are officially supported in Arg::from_usage
strings. Some
+UTF-8 codepoints may work just fine, but this is not guaranteed.
Usage strings typically following the form:
+[explicit name] [short] [long] [value names] [help string]
+
+This is not a hard rule as the attributes can appear in other orders. There are also +several additional sigils which denote additional settings. Below are the details of each +portion of the string.
+This is an optional field, if it's omitted the argument will use one of the additional +fields as the name using the following priority order:
+clap
determines explicit names as the first string of characters between either []
or
+<>
where []
has the dual notation of meaning the argument is optional, and <>
meaning
+the argument is required.
Explicit names may be followed by:
+...
Example explicit names as follows (ename
for an optional argument, and rname
for a
+required argument):
[ename] -s, --long 'some flag'
+<rname> -r, --longer 'some other flag'
+
+This is set by placing a single character after a leading -
.
Shorts may be followed by
+...
,
which is cosmetic onlyExample shorts are as follows (-s
, and -r
):
-s, --long 'some flag'
+<rname> -r [val], --longer 'some option'
+
+This is set by placing a word (no spaces) after a leading --
.
Shorts may be followed by
+...
Example longs are as follows (--some
, and --rapid
):
-s, --some 'some flag'
+--rapid=[FILE] 'some option'
+
+This is set by placing a word(s) between []
or <>
optionally after =
(although this
+is cosmetic only and does not affect functionality). If an explicit name has not been
+set, using <>
will denote a required argument, and []
will denote an optional argument
Values may be followed by
+...
More than one value will also implicitly set the arguments number of values, i.e. having
+two values, --option [val1] [val2]
specifies that in order for option to be satisified it
+must receive exactly two values
Example values are as follows (FILE
, and SPEED
):
-s, --some [FILE] 'some option'
+--rapid=<SPEED>... 'some required multiple option'
+
+The help string is denoted between a pair of single quotes ''
and may contain any
+characters.
Example help strings are as follows:
+-s, --some [FILE] 'some option'
+--rapid=<SPEED>... 'some required multiple option'
+
+Multiple notation ...
(three consecutive dots/periods) specifies that this argument may
+be used multiple times. Do not confuse multiple occurrences (...
) with multiple values.
+--option val1 val2
is a single occurrence with multiple values. --flag --flag
is
+multiple occurrences (and then you can obviously have instances of both as well)
+App::new("prog") + .args(&[ + Arg::from_usage("--config <FILE> 'a required file for the configuration and no short'"), + Arg::from_usage("-d, --debug... 'turns on debugging information and allows multiples'"), + Arg::from_usage("[input] 'an optional input file to use'") +])
pub fn short<S: AsRef<str>>(self, s: S) -> Self
[src]Sets the short version of the argument without the preceding -
.
By default clap
automatically assigns V
and h
to the auto-generated version
and
+help
arguments respectively. You may use the uppercase V
or lowercase h
for your own
+arguments, in which case clap
simply will not assign those to the auto-generated
+version
or help
arguments.
NOTE: Any leading -
characters will be stripped, and only the first
+non -
character will be used as the short
version
To set short
use a single valid UTF-8 code point. If you supply a leading -
such as
+-c
, the -
will be stripped.
+Arg::with_name("config") + .short("c")
Setting short
allows using the argument via a single hyphen (-
) such as -c
+let m = App::new("prog") + .arg(Arg::with_name("config") + .short("c")) + .get_matches_from(vec![ + "prog", "-c" + ]); + +assert!(m.is_present("config"));
pub fn long(self, l: &'b str) -> Self
[src]Sets the long version of the argument without the preceding --
.
By default clap
automatically assigns version
and help
to the auto-generated
+version
and help
arguments respectively. You may use the word version
or help
for
+the long form of your own arguments, in which case clap
simply will not assign those to
+the auto-generated version
or help
arguments.
NOTE: Any leading -
characters will be stripped
To set long
use a word containing valid UTF-8 codepoints. If you supply a double leading
+--
such as --config
they will be stripped. Hyphens in the middle of the word, however,
+will not be stripped (i.e. config-file
is allowed)
+Arg::with_name("cfg") + .long("config")
Setting long
allows using the argument via a double hyphen (--
) such as --config
+let m = App::new("prog") + .arg(Arg::with_name("cfg") + .long("config")) + .get_matches_from(vec![ + "prog", "--config" + ]); + +assert!(m.is_present("cfg"));
pub fn alias<S: Into<&'b str>>(self, name: S) -> Self
[src]Allows adding a Arg
alias, which function as "hidden" arguments that
+automatically dispatch as if this argument was used. This is more efficient, and easier
+than creating multiple hidden arguments as one only needs to check for the existence of
+this command, and not all variants.
+let m = App::new("prog") + .arg(Arg::with_name("test") + .long("test") + .alias("alias") + .takes_value(true)) + .get_matches_from(vec![ + "prog", "--alias", "cool" + ]); +assert!(m.is_present("test")); +assert_eq!(m.value_of("test"), Some("cool"));
pub fn aliases(self, names: &[&'b str]) -> Self
[src]Allows adding Arg
aliases, which function as "hidden" arguments that
+automatically dispatch as if this argument was used. This is more efficient, and easier
+than creating multiple hidden subcommands as one only needs to check for the existence of
+this command, and not all variants.
+let m = App::new("prog") + .arg(Arg::with_name("test") + .long("test") + .aliases(&["do-stuff", "do-tests", "tests"]) + .help("the file to add") + .required(false)) + .get_matches_from(vec![ + "prog", "--do-tests" + ]); +assert!(m.is_present("test"));
pub fn visible_alias<S: Into<&'b str>>(self, name: S) -> Self
[src]Allows adding a Arg
alias that functions exactly like those defined with
+[Arg::alias
], except that they are visible inside the help message.
+let m = App::new("prog") + .arg(Arg::with_name("test") + .visible_alias("something-awesome") + .long("test") + .takes_value(true)) + .get_matches_from(vec![ + "prog", "--something-awesome", "coffee" + ]); +assert!(m.is_present("test")); +assert_eq!(m.value_of("test"), Some("coffee"));
pub fn visible_aliases(self, names: &[&'b str]) -> Self
[src]Allows adding multiple Arg
aliases that functions exactly like those defined
+with [Arg::aliases
], except that they are visible inside the help message.
+let m = App::new("prog") + .arg(Arg::with_name("test") + .long("test") + .visible_aliases(&["something", "awesome", "cool"])) + .get_matches_from(vec![ + "prog", "--awesome" + ]); +assert!(m.is_present("test"));
pub fn help(self, h: &'b str) -> Self
[src]Sets the short help text of the argument that will be displayed to the user when they print
+the help information with -h
. Typically, this is a short (one line) description of the
+arg.
NOTE: If only Arg::help
is provided, and not Arg::long_help
but the user requests
+--help
clap will still display the contents of help
appropriately
NOTE: Only Arg::help
is used in completion script generation in order to be concise
Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to +include a newline in the help text and have the following text be properly aligned with all +the other help text.
+ ++Arg::with_name("config") + .help("The config file used by the myprog")
Setting help
displays a short message to the side of the argument when the user passes
+-h
or --help
(by default).
+let m = App::new("prog") + .arg(Arg::with_name("cfg") + .long("config") + .help("Some help text describing the --config arg")) + .get_matches_from(vec![ + "prog", "--help" + ]);
The above example displays
+helptest
+
+USAGE:
+ helptest [FLAGS]
+
+FLAGS:
+ --config Some help text describing the --config arg
+-h, --help Prints help information
+-V, --version Prints version information
+
+pub fn long_help(self, h: &'b str) -> Self
[src]Sets the long help text of the argument that will be displayed to the user when they print
+the help information with --help
. Typically this a more detailed (multi-line) message
+that describes the arg.
NOTE: If only long_help
is provided, and not Arg::help
but the user requests -h
+clap will still display the contents of long_help
appropriately
NOTE: Only Arg::help
is used in completion script generation in order to be concise
Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to +include a newline in the help text and have the following text be properly aligned with all +the other help text.
+ ++Arg::with_name("config") + .long_help( +"The config file used by the myprog must be in JSON format +with only valid keys and may not contain other nonsense +that cannot be read by this program. Obviously I'm going on +and on, so I'll stop now.")
Setting help
displays a short message to the side of the argument when the user passes
+-h
or --help
(by default).
+let m = App::new("prog") + .arg(Arg::with_name("cfg") + .long("config") + .long_help( +"The config file used by the myprog must be in JSON format +with only valid keys and may not contain other nonsense +that cannot be read by this program. Obviously I'm going on +and on, so I'll stop now.")) + .get_matches_from(vec![ + "prog", "--help" + ]);
The above example displays
+helptest
+
+USAGE:
+ helptest [FLAGS]
+
+FLAGS:
+ --config
+ The config file used by the myprog must be in JSON format
+ with only valid keys and may not contain other nonsense
+ that cannot be read by this program. Obviously I'm going on
+ and on, so I'll stop now.
+
+-h, --help
+ Prints help information
+
+-V, --version
+ Prints version information
+
+pub fn last(self, l: bool) -> Self
[src]Specifies that this arg is the last, or final, positional argument (i.e. has the highest
+index) and is only able to be accessed via the --
syntax (i.e. $ prog args -- last_arg
). Even, if no other arguments are left to parse, if the user omits the --
syntax
+they will receive an UnknownArgument
error. Setting an argument to .last(true)
also
+allows one to access this arg early using the --
syntax. Accessing an arg early, even with
+the --
syntax is otherwise not possible.
NOTE: This will change the usage string to look like $ prog [FLAGS] [-- <ARG>]
if
+ARG
is marked as .last(true)
.
NOTE: This setting will imply AppSettings::DontCollapseArgsInUsage
because failing
+to set this can make the usage string very confusing.
NOTE: This setting only applies to positional arguments, and has no affect on FLAGS / +OPTIONS
+CAUTION: Setting an argument to .last(true)
and having child subcommands is not
+recommended with the exception of also using AppSettings::ArgsNegateSubcommands
+(or AppSettings::SubcommandsNegateReqs
if the argument marked .last(true)
is also
+marked .required(true)
)
+Arg::with_name("args") + .last(true)
Setting Arg::last(true)
ensures the arg has the highest index of all positional args
+and requires that the --
syntax be used to access it early.
+let res = App::new("prog") + .arg(Arg::with_name("first")) + .arg(Arg::with_name("second")) + .arg(Arg::with_name("third").last(true)) + .get_matches_from_safe(vec![ + "prog", "one", "--", "three" + ]); + +assert!(res.is_ok()); +let m = res.unwrap(); +assert_eq!(m.value_of("third"), Some("three")); +assert!(m.value_of("second").is_none());
Even if the positional argument marked .last(true)
is the only argument left to parse,
+failing to use the --
syntax results in an error.
+let res = App::new("prog") + .arg(Arg::with_name("first")) + .arg(Arg::with_name("second")) + .arg(Arg::with_name("third").last(true)) + .get_matches_from_safe(vec![ + "prog", "one", "two", "three" + ]); + +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
pub fn required(self, r: bool) -> Self
[src]Sets whether or not the argument is required by default. Required by default means it is
+required, when no other conflicting rules have been evaluated. Conflicting rules take
+precedence over being required. Default: false
NOTE: Flags (i.e. not positional, or arguments that take values) cannot be required by +default. This is simply because if a flag should be required, it should simply be implied +as no additional information is required from user. Flags by their very nature are simply +yes/no, or true/false.
++Arg::with_name("config") + .required(true)
Setting Arg::required(true)
requires that the argument be used at runtime.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .required(true) + .takes_value(true) + .long("config")) + .get_matches_from_safe(vec![ + "prog", "--config", "file.conf" + ]); + +assert!(res.is_ok());
Setting Arg::required(true)
and not supplying that argument is an error.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .required(true) + .takes_value(true) + .long("config")) + .get_matches_from_safe(vec![ + "prog" + ]); + +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
pub fn require_equals(self, r: bool) -> Self
[src]Requires that options use the --option=val
syntax (i.e. an equals between the option and
+associated value) Default: false
NOTE: This setting also removes the default of allowing empty values and implies
+Arg::empty_values(false)
.
+Arg::with_name("config") + .long("config") + .takes_value(true) + .require_equals(true)
Setting Arg::require_equals(true)
requires that the option have an equals sign between
+it and the associated value.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .require_equals(true) + .takes_value(true) + .long("config")) + .get_matches_from_safe(vec![ + "prog", "--config=file.conf" + ]); + +assert!(res.is_ok());
Setting Arg::require_equals(true)
and not supplying the equals will cause an error
+unless Arg::empty_values(true)
is set.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .require_equals(true) + .takes_value(true) + .long("config")) + .get_matches_from_safe(vec![ + "prog", "--config", "file.conf" + ]); + +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue);
pub fn allow_hyphen_values(self, a: bool) -> Self
[src]Allows values which start with a leading hyphen (-
)
WARNING: Take caution when using this setting combined with Arg::multiple(true)
, as
+this becomes ambiguous $ prog --arg -- -- val
. All three --, --, val
will be values
+when the user may have thought the second --
would constitute the normal, "Only
+positional args follow" idiom. To fix this, consider using Arg::number_of_values(1)
WARNING: When building your CLIs, consider the effects of allowing leading hyphens and
+the user passing in a value that matches a valid short. For example prog -opt -F
where
+-F
is supposed to be a value, yet -F
is also a valid short for another arg. Care should
+should be taken when designing these args. This is compounded by the ability to "stack"
+short args. I.e. if -val
is supposed to be a value, but -v
, -a
, and -l
are all valid
+shorts.
+Arg::with_name("pattern") + .allow_hyphen_values(true)
+let m = App::new("prog") + .arg(Arg::with_name("pat") + .allow_hyphen_values(true) + .takes_value(true) + .long("pattern")) + .get_matches_from(vec![ + "prog", "--pattern", "-file" + ]); + +assert_eq!(m.value_of("pat"), Some("-file"));
Not setting Arg::allow_hyphen_values(true)
and supplying a value which starts with a
+hyphen is an error.
+let res = App::new("prog") + .arg(Arg::with_name("pat") + .takes_value(true) + .long("pattern")) + .get_matches_from_safe(vec![ + "prog", "--pattern", "-file" + ]); + +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
pub fn required_unless(self, name: &'a str) -> Self
[src]Sets an arg that override this arg's required setting. (i.e. this arg will be required +unless this other argument is present).
+Pro Tip: Using Arg::required_unless
implies Arg::required
and is therefore not
+mandatory to also set.
+Arg::with_name("config") + .required_unless("debug")
Setting Arg::required_unless(name)
requires that the argument be used at runtime
+unless name
is present. In the following example, the required argument is not
+provided, but it's not an error because the unless
arg has been supplied.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .required_unless("dbg") + .takes_value(true) + .long("config")) + .arg(Arg::with_name("dbg") + .long("debug")) + .get_matches_from_safe(vec![ + "prog", "--debug" + ]); + +assert!(res.is_ok());
Setting Arg::required_unless(name)
and not supplying name
or this arg is an error.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .required_unless("dbg") + .takes_value(true) + .long("config")) + .arg(Arg::with_name("dbg") + .long("debug")) + .get_matches_from_safe(vec![ + "prog" + ]); + +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
pub fn required_unless_all(self, names: &[&'a str]) -> Self
[src]Sets args that override this arg's required setting. (i.e. this arg will be required unless +all these other arguments are present).
+NOTE: If you wish for this argument to only be required if one of these args are
+present see Arg::required_unless_one
+Arg::with_name("config") + .required_unless_all(&["cfg", "dbg"])
Setting Arg::required_unless_all(names)
requires that the argument be used at runtime
+unless all the args in names
are present. In the following example, the required
+argument is not provided, but it's not an error because all the unless
args have been
+supplied.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .required_unless_all(&["dbg", "infile"]) + .takes_value(true) + .long("config")) + .arg(Arg::with_name("dbg") + .long("debug")) + .arg(Arg::with_name("infile") + .short("i") + .takes_value(true)) + .get_matches_from_safe(vec![ + "prog", "--debug", "-i", "file" + ]); + +assert!(res.is_ok());
Setting Arg::required_unless_all(names)
and not supplying all of names
or this
+arg is an error.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .required_unless_all(&["dbg", "infile"]) + .takes_value(true) + .long("config")) + .arg(Arg::with_name("dbg") + .long("debug")) + .arg(Arg::with_name("infile") + .short("i") + .takes_value(true)) + .get_matches_from_safe(vec![ + "prog" + ]); + +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
pub fn required_unless_one(self, names: &[&'a str]) -> Self
[src]Sets args that override this arg's required setting. (i.e. this arg will be required +unless at least one of these other arguments are present).
+NOTE: If you wish for this argument to only be required if all of these args are
+present see Arg::required_unless_all
+Arg::with_name("config") + .required_unless_all(&["cfg", "dbg"])
Setting Arg::required_unless_one(names)
requires that the argument be used at runtime
+unless at least one of the args in names
are present. In the following example, the
+required argument is not provided, but it's not an error because one the unless
args
+have been supplied.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .required_unless_one(&["dbg", "infile"]) + .takes_value(true) + .long("config")) + .arg(Arg::with_name("dbg") + .long("debug")) + .arg(Arg::with_name("infile") + .short("i") + .takes_value(true)) + .get_matches_from_safe(vec![ + "prog", "--debug" + ]); + +assert!(res.is_ok());
Setting Arg::required_unless_one(names)
and not supplying at least one of names
+or this arg is an error.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .required_unless_one(&["dbg", "infile"]) + .takes_value(true) + .long("config")) + .arg(Arg::with_name("dbg") + .long("debug")) + .arg(Arg::with_name("infile") + .short("i") + .takes_value(true)) + .get_matches_from_safe(vec![ + "prog" + ]); + +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
pub fn conflicts_with(self, name: &'a str) -> Self
[src]Sets a conflicting argument by name. I.e. when using this argument, +the following argument can't be present and vice versa.
+NOTE: Conflicting rules take precedence over being required by default. Conflict rules +only need to be set for one of the two arguments, they do not need to be set for each.
+NOTE: Defining a conflict is two-way, but does not need to defined for both arguments +(i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need +need to also do B.conflicts_with(A))
++Arg::with_name("config") + .conflicts_with("debug")
Setting conflicting argument, and having both arguments present at runtime is an error.
+ ++let res = App::new("prog") + .arg(Arg::with_name("cfg") + .takes_value(true) + .conflicts_with("debug") + .long("config")) + .arg(Arg::with_name("debug") + .long("debug")) + .get_matches_from_safe(vec![ + "prog", "--debug", "--config", "file.conf" + ]); + +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::ArgumentConflict);
pub fn conflicts_with_all(self, names: &[&'a str]) -> Self
[src]The same as Arg::conflicts_with
but allows specifying multiple two-way conlicts per
+argument.
NOTE: Conflicting rules take precedence over being required by default. Conflict rules +only need to be set for one of the two arguments, they do not need to be set for each.
+NOTE: Defining a conflict is two-way, but does not need to defined for both arguments +(i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need +need to also do B.conflicts_with(A))
++Arg::with_name("config") + .conflicts_with_all(&["debug", "input"])
Setting conflicting argument, and having any of the arguments present at runtime with a +conflicting argument is an error.
+ ++let res = App::new("prog") + .arg(Arg::with_name("cfg") + .takes_value(true) + .conflicts_with_all(&["debug", "input"]) + .long("config")) + .arg(Arg::with_name("debug") + .long("debug")) + .arg(Arg::with_name("input") + .index(1)) + .get_matches_from_safe(vec![ + "prog", "--config", "file.conf", "file.txt" + ]); + +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::ArgumentConflict);
pub fn overrides_with(self, name: &'a str) -> Self
[src]Sets a overridable argument by name. I.e. this argument and the following argument +will override each other in POSIX style (whichever argument was specified at runtime +last "wins")
+NOTE: When an argument is overridden it is essentially as if it never was used, any +conflicts, requirements, etc. are evaluated after all "overrides" have been removed
+WARNING: Positional arguments cannot override themselves (or we would never be able +to advance to the next positional). If a positional agument lists itself as an override, +it is simply ignored.
++let m = App::new("prog") + .arg(Arg::from_usage("-f, --flag 'some flag'") + .conflicts_with("debug")) + .arg(Arg::from_usage("-d, --debug 'other flag'")) + .arg(Arg::from_usage("-c, --color 'third flag'") + .overrides_with("flag")) + .get_matches_from(vec![ + "prog", "-f", "-d", "-c"]); + // ^~~~~~~~~~~~^~~~~ flag is overridden by color + +assert!(m.is_present("color")); +assert!(m.is_present("debug")); // even though flag conflicts with debug, it's as if flag + // was never used because it was overridden with color +assert!(!m.is_present("flag"));
Care must be taken when using this setting, and having an arg override with itself. This +is common practice when supporting things like shell aliases, config files, etc. +However, when combined with multiple values, it can get dicy. +Here is how clap handles such situations:
+When a flag overrides itself, it's as if the flag was only ever used once (essentially +preventing a "Unexpected multiple usage" error):
+ ++let m = App::new("posix") + .arg(Arg::from_usage("--flag 'some flag'").overrides_with("flag")) + .get_matches_from(vec!["posix", "--flag", "--flag"]); +assert!(m.is_present("flag")); +assert_eq!(m.occurrences_of("flag"), 1);
Making a arg multiple(true)
and override itself is essentially meaningless. Therefore
+clap ignores an override of self if it's a flag and it already accepts multiple occurrences.
+let m = App::new("posix") + .arg(Arg::from_usage("--flag... 'some flag'").overrides_with("flag")) + .get_matches_from(vec!["", "--flag", "--flag", "--flag", "--flag"]); +assert!(m.is_present("flag")); +assert_eq!(m.occurrences_of("flag"), 4);
Now notice with options (which do not set multiple(true)
), it's as if only the last
+occurrence happened.
+let m = App::new("posix") + .arg(Arg::from_usage("--opt [val] 'some option'").overrides_with("opt")) + .get_matches_from(vec!["", "--opt=some", "--opt=other"]); +assert!(m.is_present("opt")); +assert_eq!(m.occurrences_of("opt"), 1); +assert_eq!(m.value_of("opt"), Some("other"));
Just like flags, options with multiple(true)
set, will ignore the "override self" setting.
+let m = App::new("posix") + .arg(Arg::from_usage("--opt [val]... 'some option'") + .overrides_with("opt")) + .get_matches_from(vec!["", "--opt", "first", "over", "--opt", "other", "val"]); +assert!(m.is_present("opt")); +assert_eq!(m.occurrences_of("opt"), 2); +assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["first", "over", "other", "val"]);
A safe thing to do if you'd like to support an option which supports multiple values, but
+also is "overridable" by itself, is to use use_delimiter(false)
and not use
+multiple(true)
while telling users to seperate values with a comma (i.e. val1,val2
)
+let m = App::new("posix") + .arg(Arg::from_usage("--opt [val] 'some option'") + .overrides_with("opt") + .use_delimiter(false)) + .get_matches_from(vec!["", "--opt=some,other", "--opt=one,two"]); +assert!(m.is_present("opt")); +assert_eq!(m.occurrences_of("opt"), 1); +assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["one,two"]);
pub fn overrides_with_all(self, names: &[&'a str]) -> Self
[src]Sets multiple mutually overridable arguments by name. I.e. this argument and the following +argument will override each other in POSIX style (whichever argument was specified at +runtime last "wins")
+NOTE: When an argument is overridden it is essentially as if it never was used, any +conflicts, requirements, etc. are evaluated after all "overrides" have been removed
++let m = App::new("prog") + .arg(Arg::from_usage("-f, --flag 'some flag'") + .conflicts_with("color")) + .arg(Arg::from_usage("-d, --debug 'other flag'")) + .arg(Arg::from_usage("-c, --color 'third flag'") + .overrides_with_all(&["flag", "debug"])) + .get_matches_from(vec![ + "prog", "-f", "-d", "-c"]); + // ^~~~~~^~~~~~~~~ flag and debug are overridden by color + +assert!(m.is_present("color")); // even though flag conflicts with color, it's as if flag + // and debug were never used because they were overridden + // with color +assert!(!m.is_present("debug")); +assert!(!m.is_present("flag"));
pub fn requires(self, name: &'a str) -> Self
[src]Sets an argument by name that is required when this one is present I.e. when +using this argument, the following argument must be present.
+NOTE: Conflicting rules and override rules take precedence over being required
++Arg::with_name("config") + .requires("input")
Setting Arg::requires(name)
requires that the argument be used at runtime if the
+defining argument is used. If the defining argument isn't used, the other argument isn't
+required
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .takes_value(true) + .requires("input") + .long("config")) + .arg(Arg::with_name("input") + .index(1)) + .get_matches_from_safe(vec![ + "prog" + ]); + +assert!(res.is_ok()); // We didn't use cfg, so input wasn't required
Setting Arg::requires(name)
and not supplying that argument is an error.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .takes_value(true) + .requires("input") + .long("config")) + .arg(Arg::with_name("input") + .index(1)) + .get_matches_from_safe(vec![ + "prog", "--config", "file.conf" + ]); + +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
pub fn requires_if(self, val: &'b str, arg: &'a str) -> Self
[src]Allows a conditional requirement. The requirement will only become valid if this arg's value
+equals val
.
NOTE: If using YAML the values should be laid out as follows
+requires_if:
+ - [val, arg]
+
++Arg::with_name("config") + .requires_if("val", "arg")
Setting [Arg::requires_if(val, arg)
] requires that the arg
be used at runtime if the
+defining argument's value is equal to val
. If the defining argument is anything other than
+val
, the other argument isn't required.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .takes_value(true) + .requires_if("my.cfg", "other") + .long("config")) + .arg(Arg::with_name("other")) + .get_matches_from_safe(vec![ + "prog", "--config", "some.cfg" + ]); + +assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required
Setting [Arg::requires_if(val, arg)
] and setting the value to val
but not supplying
+arg
is an error.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .takes_value(true) + .requires_if("my.cfg", "input") + .long("config")) + .arg(Arg::with_name("input")) + .get_matches_from_safe(vec![ + "prog", "--config", "my.cfg" + ]); + +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
pub fn requires_ifs(self, ifs: &[(&'b str, &'a str)]) -> Self
[src]Allows multiple conditional requirements. The requirement will only become valid if this arg's value
+equals val
.
NOTE: If using YAML the values should be laid out as follows
+requires_if:
+ - [val, arg]
+ - [val2, arg2]
+
++Arg::with_name("config") + .requires_ifs(&[ + ("val", "arg"), + ("other_val", "arg2"), + ])
Setting [Arg::requires_ifs(&["val", "arg"])
] requires that the arg
be used at runtime if the
+defining argument's value is equal to val
. If the defining argument's value is anything other
+than val
, arg
isn't required.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .takes_value(true) + .requires_ifs(&[ + ("special.conf", "opt"), + ("other.conf", "other"), + ]) + .long("config")) + .arg(Arg::with_name("opt") + .long("option") + .takes_value(true)) + .arg(Arg::with_name("other")) + .get_matches_from_safe(vec![ + "prog", "--config", "special.conf" + ]); + +assert!(res.is_err()); // We used --config=special.conf so --option <val> is required +assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
pub fn required_if(self, arg: &'a str, val: &'b str) -> Self
[src]Allows specifying that an argument is required conditionally. The requirement will only
+become valid if the specified arg
's value equals val
.
NOTE: If using YAML the values should be laid out as follows
+required_if:
+ - [arg, val]
+
++Arg::with_name("config") + .required_if("other_arg", "value")
Setting [Arg::required_if(arg, val)
] makes this arg required if the arg
is used at
+runtime and it's value is equal to val
. If the arg
's value is anything other than val
,
+this argument isn't required.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .takes_value(true) + .required_if("other", "special") + .long("config")) + .arg(Arg::with_name("other") + .long("other") + .takes_value(true)) + .get_matches_from_safe(vec![ + "prog", "--other", "not-special" + ]); + +assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required
Setting [Arg::required_if(arg, val)
] and having arg
used with a value of val
but not
+using this arg is an error.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .takes_value(true) + .required_if("other", "special") + .long("config")) + .arg(Arg::with_name("other") + .long("other") + .takes_value(true)) + .get_matches_from_safe(vec![ + "prog", "--other", "special" + ]); + +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
pub fn required_ifs(self, ifs: &[(&'a str, &'b str)]) -> Self
[src]Allows specifying that an argument is required based on multiple conditions. The
+conditions are set up in a (arg, val)
style tuple. The requirement will only become valid
+if one of the specified arg
's value equals it's corresponding val
.
NOTE: If using YAML the values should be laid out as follows
+required_if:
+ - [arg, val]
+ - [arg2, val2]
+
++Arg::with_name("config") + .required_ifs(&[ + ("extra", "val"), + ("option", "spec") + ])
Setting [Arg::required_ifs(&[(arg, val)])
] makes this arg required if any of the arg
s
+are used at runtime and it's corresponding value is equal to val
. If the arg
's value is
+anything other than val
, this argument isn't required.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .required_ifs(&[ + ("extra", "val"), + ("option", "spec") + ]) + .takes_value(true) + .long("config")) + .arg(Arg::with_name("extra") + .takes_value(true) + .long("extra")) + .arg(Arg::with_name("option") + .takes_value(true) + .long("option")) + .get_matches_from_safe(vec![ + "prog", "--option", "other" + ]); + +assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required
Setting [Arg::required_ifs(&[(arg, val)])
] and having any of the arg
s used with it's
+value of val
but not using this arg is an error.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .required_ifs(&[ + ("extra", "val"), + ("option", "spec") + ]) + .takes_value(true) + .long("config")) + .arg(Arg::with_name("extra") + .takes_value(true) + .long("extra")) + .arg(Arg::with_name("option") + .takes_value(true) + .long("option")) + .get_matches_from_safe(vec![ + "prog", "--option", "spec" + ]); + +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
pub fn requires_all(self, names: &[&'a str]) -> Self
[src]Sets multiple arguments by names that are required when this one is present I.e. when +using this argument, the following arguments must be present.
+NOTE: Conflicting rules and override rules take precedence over being required +by default.
++Arg::with_name("config") + .requires_all(&["input", "output"])
Setting [Arg::requires_all(&[arg, arg2])
] requires that all the arguments be used at
+runtime if the defining argument is used. If the defining argument isn't used, the other
+argument isn't required
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .takes_value(true) + .requires("input") + .long("config")) + .arg(Arg::with_name("input") + .index(1)) + .arg(Arg::with_name("output") + .index(2)) + .get_matches_from_safe(vec![ + "prog" + ]); + +assert!(res.is_ok()); // We didn't use cfg, so input and output weren't required
Setting [Arg::requires_all(&[arg, arg2])
] and not supplying all the arguments is an
+error.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .takes_value(true) + .requires_all(&["input", "output"]) + .long("config")) + .arg(Arg::with_name("input") + .index(1)) + .arg(Arg::with_name("output") + .index(2)) + .get_matches_from_safe(vec![ + "prog", "--config", "file.conf", "in.txt" + ]); + +assert!(res.is_err()); +// We didn't use output +assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
[Arg::requires_all(&[arg, arg2])
]: ./struct.Arg.html#method.requires_all
pub fn takes_value(self, tv: bool) -> Self
[src]Specifies that the argument takes a value at run time.
+NOTE: values for arguments may be specified in any of the following methods
+-o value
or --option value
-o=value
or --option=value
-ovalue
NOTE: By default, args which allow multiple values are delimited by commas, meaning
+--option=val1,val2,val3
is three values for the --option
argument. If you wish to
+change the delimiter to another character you can use Arg::value_delimiter(char)
,
+alternatively you can turn delimiting values OFF by using Arg::use_delimiter(false)
+Arg::with_name("config") + .takes_value(true)
+let m = App::new("prog") + .arg(Arg::with_name("mode") + .long("mode") + .takes_value(true)) + .get_matches_from(vec![ + "prog", "--mode", "fast" + ]); + +assert!(m.is_present("mode")); +assert_eq!(m.value_of("mode"), Some("fast"));
pub fn hide_possible_values(self, hide: bool) -> Self
[src]Specifies if the possible values of an argument should be displayed in the help text or
+not. Defaults to false
(i.e. show possible values)
This is useful for args with many values, or ones which are explained elsewhere in the +help text.
++Arg::with_name("config") + .hide_possible_values(true)
+let m = App::new("prog") + .arg(Arg::with_name("mode") + .long("mode") + .possible_values(&["fast", "slow"]) + .takes_value(true) + .hide_possible_values(true)); +
If we were to run the above program with --help
the [values: fast, slow]
portion of
+the help text would be omitted.
pub fn hide_default_value(self, hide: bool) -> Self
[src]Specifies if the default value of an argument should be displayed in the help text or
+not. Defaults to false
(i.e. show default value)
This is useful when default behavior of an arg is explained elsewhere in the help text.
++Arg::with_name("config") + .hide_default_value(true)
+let m = App::new("connect") + .arg(Arg::with_name("host") + .long("host") + .default_value("localhost") + .hide_default_value(true)); +
If we were to run the above program with --help
the [default: localhost]
portion of
+the help text would be omitted.
pub fn index(self, idx: u64) -> Self
[src]Specifies the index of a positional argument starting at 1.
+NOTE: The index refers to position according to other positional argument. It does +not define position in the argument list as a whole.
+NOTE: If no Arg::short
, or Arg::long
have been defined, you can optionally
+leave off the index
method, and the index will be assigned in order of evaluation.
+Utilizing the index
method allows for setting indexes out of order
NOTE: When utilized with Arg::multiple(true)
, only the last positional argument
+may be defined as multiple (i.e. with the highest index)
Although not in this method directly, App
will panic!
if indexes are skipped (such
+as defining index(1)
and index(3)
but not index(2)
, or a positional argument is
+defined as multiple and is not the highest index
+Arg::with_name("config") + .index(1)
+let m = App::new("prog") + .arg(Arg::with_name("mode") + .index(1)) + .arg(Arg::with_name("debug") + .long("debug")) + .get_matches_from(vec![ + "prog", "--debug", "fast" + ]); + +assert!(m.is_present("mode")); +assert_eq!(m.value_of("mode"), Some("fast")); // notice index(1) means "first positional" + // *not* first argument
pub fn multiple(self, multi: bool) -> Self
[src]Specifies that the argument may appear more than once. For flags, this results
+in the number of occurrences of the flag being recorded. For example -ddd
or -d -d -d
+would count as three occurrences. For options there is a distinct difference in multiple
+occurrences vs multiple values.
For example, --opt val1 val2
is one occurrence, but two values. Whereas
+--opt val1 --opt val2
is two occurrences.
WARNING:
+Setting multiple(true)
for an option with no other details, allows multiple values
+and multiple occurrences because it isn't possible to have more occurrences than values
+for options. Because multiple values are allowed, --option val1 val2 val3
is perfectly
+valid, be careful when designing a CLI where positional arguments are expected after a
+option which accepts multiple values, as clap
will continue parsing values until it
+reaches the max or specific number of values defined, or another flag or option.
Pro Tip:
+It's possible to define an option which allows multiple occurrences, but only one value per
+occurrence. To do this use Arg::number_of_values(1)
in coordination with
+Arg::multiple(true)
.
WARNING:
+When using args with multiple(true)
on options or positionals (i.e. those args that
+accept values) and subcommands, one needs to consider the possibility of an argument value
+being the same as a valid subcommand. By default clap
will parse the argument in question
+as a value only if a value is possible at that moment. Otherwise it will be parsed as a
+subcommand. In effect, this means using multiple(true)
with no additional parameters and
+a possible value that coincides with a subcommand name, the subcommand cannot be called
+unless another argument is passed first.
As an example, consider a CLI with an option --ui-paths=<paths>...
and subcommand signer
The following would be parsed as values to --ui-paths
.
$ program --ui-paths path1 path2 signer
+
+This is because --ui-paths
accepts multiple values. clap
will continue parsing values
+until another argument is reached and it knows --ui-paths
is done.
By adding additional parameters to --ui-paths
we can solve this issue. Consider adding
+Arg::number_of_values(1)
as discussed above. The following are all valid, and signer
+is parsed as both a subcommand and a value in the second case.
$ program --ui-paths path1 signer
+$ program --ui-paths path1 --ui-paths signer signer
+
++Arg::with_name("debug") + .short("d") + .multiple(true)
An example with flags
+ ++let m = App::new("prog") + .arg(Arg::with_name("verbose") + .multiple(true) + .short("v")) + .get_matches_from(vec![ + "prog", "-v", "-v", "-v" // note, -vvv would have same result + ]); + +assert!(m.is_present("verbose")); +assert_eq!(m.occurrences_of("verbose"), 3);
An example with options
+ ++let m = App::new("prog") + .arg(Arg::with_name("file") + .multiple(true) + .takes_value(true) + .short("F")) + .get_matches_from(vec![ + "prog", "-F", "file1", "file2", "file3" + ]); + +assert!(m.is_present("file")); +assert_eq!(m.occurrences_of("file"), 1); // notice only one occurrence +let files: Vec<_> = m.values_of("file").unwrap().collect(); +assert_eq!(files, ["file1", "file2", "file3"]);
This is functionally equivalent to the example above
+ ++let m = App::new("prog") + .arg(Arg::with_name("file") + .multiple(true) + .takes_value(true) + .short("F")) + .get_matches_from(vec![ + "prog", "-F", "file1", "-F", "file2", "-F", "file3" + ]); +let files: Vec<_> = m.values_of("file").unwrap().collect(); +assert_eq!(files, ["file1", "file2", "file3"]); + +assert!(m.is_present("file")); +assert_eq!(m.occurrences_of("file"), 3); // Notice 3 occurrences +let files: Vec<_> = m.values_of("file").unwrap().collect(); +assert_eq!(files, ["file1", "file2", "file3"]);
A common mistake is to define an option which allows multiples, and a positional argument
+ ++let m = App::new("prog") + .arg(Arg::with_name("file") + .multiple(true) + .takes_value(true) + .short("F")) + .arg(Arg::with_name("word") + .index(1)) + .get_matches_from(vec![ + "prog", "-F", "file1", "file2", "file3", "word" + ]); + +assert!(m.is_present("file")); +let files: Vec<_> = m.values_of("file").unwrap().collect(); +assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?! +assert!(!m.is_present("word")); // but we clearly used word!
The problem is clap doesn't know when to stop parsing values for "files". This is further
+compounded by if we'd said word -F file1 file2
it would have worked fine, so it would
+appear to only fail sometimes...not good!
A solution for the example above is to specify that -F
only accepts one value, but is
+allowed to appear multiple times
+let m = App::new("prog") + .arg(Arg::with_name("file") + .multiple(true) + .takes_value(true) + .number_of_values(1) + .short("F")) + .arg(Arg::with_name("word") + .index(1)) + .get_matches_from(vec![ + "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word" + ]); + +assert!(m.is_present("file")); +let files: Vec<_> = m.values_of("file").unwrap().collect(); +assert_eq!(files, ["file1", "file2", "file3"]); +assert!(m.is_present("word")); +assert_eq!(m.value_of("word"), Some("word"));
As a final example, notice if we define Arg::number_of_values(1)
and try to run the
+problem example above, it would have been a runtime error with a pretty message to the
+user :)
+let res = App::new("prog") + .arg(Arg::with_name("file") + .multiple(true) + .takes_value(true) + .number_of_values(1) + .short("F")) + .arg(Arg::with_name("word") + .index(1)) + .get_matches_from_safe(vec![ + "prog", "-F", "file1", "file2", "file3", "word" + ]); + +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
pub fn value_terminator(self, term: &'b str) -> Self
[src]Specifies a value that stops parsing multiple values of a give argument. By default when
+one sets multiple(true)
on an argument, clap will continue parsing values for that
+argument until it reaches another valid argument, or one of the other more specific settings
+for multiple values is used (such as min_values
, max_values
or
+number_of_values
).
NOTE: This setting only applies to options and positional arguments
+NOTE: When the terminator is passed in on the command line, it is not stored as one +of the values
++Arg::with_name("vals") + .takes_value(true) + .multiple(true) + .value_terminator(";")
The following example uses two arguments, a sequence of commands, and the location in which +to perform them
+ ++let m = App::new("prog") + .arg(Arg::with_name("cmds") + .multiple(true) + .allow_hyphen_values(true) + .value_terminator(";")) + .arg(Arg::with_name("location")) + .get_matches_from(vec![ + "prog", "find", "-type", "f", "-name", "special", ";", "/home/clap" + ]); +let cmds: Vec<_> = m.values_of("cmds").unwrap().collect(); +assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]); +assert_eq!(m.value_of("location"), Some("/home/clap"));
pub fn global(self, g: bool) -> Self
[src]Specifies that an argument can be matched to all child SubCommand
s.
NOTE: Global arguments only propagate down, not up (to parent commands), however +their values once a user uses them will be propagated back up to parents. In effect, this +means one should define all global arguments at the top level, however it doesn't matter +where the user uses the global argument.
++Arg::with_name("debug") + .short("d") + .global(true)
For example, assume an application with two subcommands, and you'd like to define a
+--verbose
flag that can be called on any of the subcommands and parent, but you don't
+want to clutter the source with three duplicate Arg
definitions.
+let m = App::new("prog") + .arg(Arg::with_name("verb") + .long("verbose") + .short("v") + .global(true)) + .subcommand(SubCommand::with_name("test")) + .subcommand(SubCommand::with_name("do-stuff")) + .get_matches_from(vec![ + "prog", "do-stuff", "--verbose" + ]); + +assert_eq!(m.subcommand_name(), Some("do-stuff")); +let sub_m = m.subcommand_matches("do-stuff").unwrap(); +assert!(sub_m.is_present("verb"));
pub fn empty_values(self, ev: bool) -> Self
[src]Allows an argument to accept explicitly empty values. An empty value must be specified at
+the command line with an explicit ""
, or ''
NOTE: Defaults to true
(Explicitly empty values are allowed)
NOTE: Implicitly sets Arg::takes_value(true)
when set to false
+Arg::with_name("file") + .long("file") + .empty_values(false)
The default is to allow empty values, such as --option ""
would be an empty value. But
+we can change to make empty values become an error.
+let res = App::new("prog") + .arg(Arg::with_name("cfg") + .long("config") + .short("v") + .empty_values(false)) + .get_matches_from_safe(vec![ + "prog", "--config=" + ]); + +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue);
pub fn hidden(self, h: bool) -> Self
[src]Hides an argument from help message output.
+NOTE: Implicitly sets Arg::hidden_short_help(true)
and Arg::hidden_long_help(true)
+when set to true
NOTE: This does not hide the argument from usage strings on error
++Arg::with_name("debug") + .hidden(true)
Setting hidden(true)
will hide the argument when displaying help text
+let m = App::new("prog") + .arg(Arg::with_name("cfg") + .long("config") + .hidden(true) + .help("Some help text describing the --config arg")) + .get_matches_from(vec![ + "prog", "--help" + ]);
The above example displays
+helptest
+
+USAGE:
+ helptest [FLAGS]
+
+FLAGS:
+-h, --help Prints help information
+-V, --version Prints version information
+
+pub fn possible_values(self, names: &[&'b str]) -> Self
[src]Specifies a list of possible values for this argument. At runtime, clap
verifies that
+only one of the specified values was used, or fails with an error message.
NOTE: This setting only applies to options and positional arguments
++Arg::with_name("mode") + .takes_value(true) + .possible_values(&["fast", "slow", "medium"])
+let m = App::new("prog") + .arg(Arg::with_name("mode") + .long("mode") + .takes_value(true) + .possible_values(&["fast", "slow", "medium"])) + .get_matches_from(vec![ + "prog", "--mode", "fast" + ]); +assert!(m.is_present("mode")); +assert_eq!(m.value_of("mode"), Some("fast"));
The next example shows a failed parse from using a value which wasn't defined as one of the +possible values.
+ ++let res = App::new("prog") + .arg(Arg::with_name("mode") + .long("mode") + .takes_value(true) + .possible_values(&["fast", "slow", "medium"])) + .get_matches_from_safe(vec![ + "prog", "--mode", "wrong" + ]); +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::InvalidValue);
pub fn possible_value(self, name: &'b str) -> Self
[src]Specifies a possible value for this argument, one at a time. At runtime, clap
verifies
+that only one of the specified values was used, or fails with error message.
NOTE: This setting only applies to options and positional arguments
++Arg::with_name("mode") + .takes_value(true) + .possible_value("fast") + .possible_value("slow") + .possible_value("medium")
+let m = App::new("prog") + .arg(Arg::with_name("mode") + .long("mode") + .takes_value(true) + .possible_value("fast") + .possible_value("slow") + .possible_value("medium")) + .get_matches_from(vec![ + "prog", "--mode", "fast" + ]); +assert!(m.is_present("mode")); +assert_eq!(m.value_of("mode"), Some("fast"));
The next example shows a failed parse from using a value which wasn't defined as one of the +possible values.
+ ++let res = App::new("prog") + .arg(Arg::with_name("mode") + .long("mode") + .takes_value(true) + .possible_value("fast") + .possible_value("slow") + .possible_value("medium")) + .get_matches_from_safe(vec![ + "prog", "--mode", "wrong" + ]); +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::InvalidValue);
pub fn case_insensitive(self, ci: bool) -> Self
[src]When used with [Arg::possible_values
] it allows the argument value to pass validation even if
+the case differs from that of the specified possible_value
.
Pro Tip: Use this setting with arg_enum!
+let m = App::new("pv") + .arg(Arg::with_name("option") + .long("--option") + .takes_value(true) + .possible_value("test123") + .case_insensitive(true)) + .get_matches_from(vec![ + "pv", "--option", "TeSt123", + ]); + +assert!(m.value_of("option").unwrap().eq_ignore_ascii_case("test123"));
This setting also works when multiple values can be defined:
+ ++let m = App::new("pv") + .arg(Arg::with_name("option") + .short("-o") + .long("--option") + .takes_value(true) + .possible_value("test123") + .possible_value("test321") + .multiple(true) + .case_insensitive(true)) + .get_matches_from(vec![ + "pv", "--option", "TeSt123", "teST123", "tESt321" + ]); + +let matched_vals = m.values_of("option").unwrap().collect::<Vec<_>>(); +assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]);
pub fn group(self, name: &'a str) -> Self
[src]Specifies the name of the ArgGroup
the argument belongs to.
+Arg::with_name("debug") + .long("debug") + .group("mode")
Multiple arguments can be a member of a single group and then the group checked as if it +was one of said arguments.
+ ++let m = App::new("prog") + .arg(Arg::with_name("debug") + .long("debug") + .group("mode")) + .arg(Arg::with_name("verbose") + .long("verbose") + .group("mode")) + .get_matches_from(vec![ + "prog", "--debug" + ]); +assert!(m.is_present("mode"));
pub fn groups(self, names: &[&'a str]) -> Self
[src]Specifies the names of multiple ArgGroup
's the argument belongs to.
+Arg::with_name("debug") + .long("debug") + .groups(&["mode", "verbosity"])
Arguments can be members of multiple groups and then the group checked as if it +was one of said arguments.
+ ++let m = App::new("prog") + .arg(Arg::with_name("debug") + .long("debug") + .groups(&["mode", "verbosity"])) + .arg(Arg::with_name("verbose") + .long("verbose") + .groups(&["mode", "verbosity"])) + .get_matches_from(vec![ + "prog", "--debug" + ]); +assert!(m.is_present("mode")); +assert!(m.is_present("verbosity"));
pub fn number_of_values(self, qty: u64) -> Self
[src]Specifies how many values are required to satisfy this argument. For example, if you had a
+-f <file>
argument where you wanted exactly 3 'files' you would set
+.number_of_values(3)
, and this argument wouldn't be satisfied unless the user provided
+3 and only 3 values.
NOTE: Does not require Arg::multiple(true)
to be set. Setting
+Arg::multiple(true)
would allow -f <file> <file> <file> -f <file> <file> <file>
where
+as not setting Arg::multiple(true)
would only allow one occurrence of this argument.
+Arg::with_name("file") + .short("f") + .number_of_values(3)
Not supplying the correct number of values is an error
+ ++let res = App::new("prog") + .arg(Arg::with_name("file") + .takes_value(true) + .number_of_values(2) + .short("F")) + .get_matches_from_safe(vec![ + "prog", "-F", "file1" + ]); + +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::WrongNumberOfValues);
pub fn validator<F>(self, f: F) -> Self where
F: Fn(String) -> Result<(), String> + 'static,
[src]Allows one to perform a custom validation on the argument value. You provide a closure
+which accepts a String
value, and return a Result
where the Err(String)
is a
+message displayed to the user.
NOTE: The error message does not need to contain the error:
portion, only the
+message as all errors will appear as
+error: Invalid value for '<arg>': <YOUR MESSAGE>
where <arg>
is replaced by the actual
+arg, and <YOUR MESSAGE>
is the String
you return as the error.
NOTE: There is a small performance hit for using validators, as they are implemented
+with Rc
pointers. And the value to be checked will be allocated an extra time in order
+to to be passed to the closure. This performance hit is extremely minimal in the grand
+scheme of things.
+fn has_at(v: String) -> Result<(), String> { + if v.contains("@") { return Ok(()); } + Err(String::from("The value did not contain the required @ sigil")) +} +let res = App::new("prog") + .arg(Arg::with_name("file") + .index(1) + .validator(has_at)) + .get_matches_from_safe(vec![ + "prog", "some@file" + ]); +assert!(res.is_ok()); +assert_eq!(res.unwrap().value_of("file"), Some("some@file"));
pub fn validator_os<F>(self, f: F) -> Self where
F: Fn(&OsStr) -> Result<(), OsString> + 'static,
[src]Works identically to Validator but is intended to be used with values that could +contain non UTF-8 formatted strings.
++fn has_ampersand(v: &OsStr) -> Result<(), OsString> { + if v.as_bytes().iter().any(|b| *b == b'&') { return Ok(()); } + Err(OsString::from("The value did not contain the required & sigil")) +} +let res = App::new("prog") + .arg(Arg::with_name("file") + .index(1) + .validator_os(has_ampersand)) + .get_matches_from_safe(vec![ + "prog", "Fish & chips" + ]); +assert!(res.is_ok()); +assert_eq!(res.unwrap().value_of("file"), Some("Fish & chips"));
pub fn max_values(self, qty: u64) -> Self
[src]Specifies the maximum number of values are for this argument. For example, if you had a
+-f <file>
argument where you wanted up to 3 'files' you would set .max_values(3)
, and
+this argument would be satisfied if the user provided, 1, 2, or 3 values.
NOTE: This does not implicitly set Arg::multiple(true)
. This is because
+-o val -o val
is multiple occurrences but a single value and -o val1 val2
is a single
+occurrence with multiple values. For positional arguments this does set
+Arg::multiple(true)
because there is no way to determine the difference between multiple
+occurrences and multiple values.
+Arg::with_name("file") + .short("f") + .max_values(3)
Supplying less than the maximum number of values is allowed
+ ++let res = App::new("prog") + .arg(Arg::with_name("file") + .takes_value(true) + .max_values(3) + .short("F")) + .get_matches_from_safe(vec![ + "prog", "-F", "file1", "file2" + ]); + +assert!(res.is_ok()); +let m = res.unwrap(); +let files: Vec<_> = m.values_of("file").unwrap().collect(); +assert_eq!(files, ["file1", "file2"]);
Supplying more than the maximum number of values is an error
+ ++let res = App::new("prog") + .arg(Arg::with_name("file") + .takes_value(true) + .max_values(2) + .short("F")) + .get_matches_from_safe(vec![ + "prog", "-F", "file1", "file2", "file3" + ]); + +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::TooManyValues);
pub fn min_values(self, qty: u64) -> Self
[src]Specifies the minimum number of values for this argument. For example, if you had a
+-f <file>
argument where you wanted at least 2 'files' you would set
+.min_values(2)
, and this argument would be satisfied if the user provided, 2 or more
+values.
NOTE: This does not implicitly set Arg::multiple(true)
. This is because
+-o val -o val
is multiple occurrences but a single value and -o val1 val2
is a single
+occurrence with multiple values. For positional arguments this does set
+Arg::multiple(true)
because there is no way to determine the difference between multiple
+occurrences and multiple values.
+Arg::with_name("file") + .short("f") + .min_values(3)
Supplying more than the minimum number of values is allowed
+ ++let res = App::new("prog") + .arg(Arg::with_name("file") + .takes_value(true) + .min_values(2) + .short("F")) + .get_matches_from_safe(vec![ + "prog", "-F", "file1", "file2", "file3" + ]); + +assert!(res.is_ok()); +let m = res.unwrap(); +let files: Vec<_> = m.values_of("file").unwrap().collect(); +assert_eq!(files, ["file1", "file2", "file3"]);
Supplying less than the minimum number of values is an error
+ ++let res = App::new("prog") + .arg(Arg::with_name("file") + .takes_value(true) + .min_values(2) + .short("F")) + .get_matches_from_safe(vec![ + "prog", "-F", "file1" + ]); + +assert!(res.is_err()); +assert_eq!(res.unwrap_err().kind, ErrorKind::TooFewValues);
pub fn use_delimiter(self, d: bool) -> Self
[src]Specifies whether or not an argument should allow grouping of multiple values via a
+delimiter. I.e. should --option=val1,val2,val3
be parsed as three values (val1
, val2
,
+and val3
) or as a single value (val1,val2,val3
). Defaults to using ,
(comma) as the
+value delimiter for all arguments that accept values (options and positional arguments)
NOTE: The default is false
. When set to true
the default Arg::value_delimiter
+is the comma ,
.
The following example shows the default behavior.
+ ++let delims = App::new("prog") + .arg(Arg::with_name("option") + .long("option") + .use_delimiter(true) + .takes_value(true)) + .get_matches_from(vec![ + "prog", "--option=val1,val2,val3", + ]); + +assert!(delims.is_present("option")); +assert_eq!(delims.occurrences_of("option"), 1); +assert_eq!(delims.values_of("option").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
The next example shows the difference when turning delimiters off. This is the default +behavior
+ ++let nodelims = App::new("prog") + .arg(Arg::with_name("option") + .long("option") + .use_delimiter(false) + .takes_value(true)) + .get_matches_from(vec![ + "prog", "--option=val1,val2,val3", + ]); + +assert!(nodelims.is_present("option")); +assert_eq!(nodelims.occurrences_of("option"), 1); +assert_eq!(nodelims.value_of("option").unwrap(), "val1,val2,val3");
pub fn require_delimiter(self, d: bool) -> Self
[src]Specifies that multiple values may only be set using the delimiter. This means if an +if an option is encountered, and no delimiter is found, it automatically assumed that no +additional values for that option follow. This is unlike the default, where it is generally +assumed that more values will follow regardless of whether or not a delimiter is used.
+NOTE: The default is false
.
NOTE: Setting this to true implies Arg::use_delimiter(true)
NOTE: It's a good idea to inform the user that use of a delimiter is required, either +through help text or other means.
+These examples demonstrate what happens when require_delimiter(true)
is used. Notice
+everything works in this first example, as we use a delimiter, as expected.
+let delims = App::new("prog") + .arg(Arg::with_name("opt") + .short("o") + .takes_value(true) + .multiple(true) + .require_delimiter(true)) + .get_matches_from(vec![ + "prog", "-o", "val1,val2,val3", + ]); + +assert!(delims.is_present("opt")); +assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
In this next example, we will not use a delimiter. Notice it's now an error.
+ ++let res = App::new("prog") + .arg(Arg::with_name("opt") + .short("o") + .takes_value(true) + .multiple(true) + .require_delimiter(true)) + .get_matches_from_safe(vec![ + "prog", "-o", "val1", "val2", "val3", + ]); + +assert!(res.is_err()); +let err = res.unwrap_err(); +assert_eq!(err.kind, ErrorKind::UnknownArgument);
What's happening is -o
is getting val1
, and because delimiters are required yet none
+were present, it stops parsing -o
. At this point it reaches val2
and because no
+positional arguments have been defined, it's an error of an unexpected argument.
In this final example, we contrast the above with clap
's default behavior where the above
+is not an error.
+let delims = App::new("prog") + .arg(Arg::with_name("opt") + .short("o") + .takes_value(true) + .multiple(true)) + .get_matches_from(vec![ + "prog", "-o", "val1", "val2", "val3", + ]); + +assert!(delims.is_present("opt")); +assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
pub fn value_delimiter(self, d: &str) -> Self
[src]Specifies the separator to use when values are clumped together, defaults to ,
(comma).
NOTE: implicitly sets Arg::use_delimiter(true)
NOTE: implicitly sets Arg::takes_value(true)
+let m = App::new("prog") + .arg(Arg::with_name("config") + .short("c") + .long("config") + .value_delimiter(";")) + .get_matches_from(vec![ + "prog", "--config=val1;val2;val3" + ]); + +assert_eq!(m.values_of("config").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"])
pub fn value_names(self, names: &[&'b str]) -> Self
[src]Specify multiple names for values of option arguments. These names are cosmetic only, used
+for help and usage strings only. The names are not used to access arguments. The values
+of the arguments are accessed in numeric order (i.e. if you specify two names one
and
+two
one
will be the first matched value, two
will be the second).
This setting can be very helpful when describing the type of input the user should be
+using, such as FILE
, INTERFACE
, etc. Although not required, it's somewhat convention to
+use all capital letters for the value name.
Pro Tip: It may help to use Arg::next_line_help(true)
if there are long, or
+multiple value names in order to not throw off the help text alignment of all options.
NOTE: This implicitly sets Arg::number_of_values
if the number of value names is
+greater than one. I.e. be aware that the number of "names" you set for the values, will be
+the exact number of values required to satisfy this argument
NOTE: implicitly sets Arg::takes_value(true)
NOTE: Does not require or imply Arg::multiple(true)
.
+Arg::with_name("speed") + .short("s") + .value_names(&["fast", "slow"])
+let m = App::new("prog") + .arg(Arg::with_name("io") + .long("io-files") + .value_names(&["INFILE", "OUTFILE"])) + .get_matches_from(vec![ + "prog", "--help" + ]);
Running the above program produces the following output
+valnames
+
+USAGE:
+ valnames [FLAGS] [OPTIONS]
+
+FLAGS:
+ -h, --help Prints help information
+ -V, --version Prints version information
+
+OPTIONS:
+ --io-files <INFILE> <OUTFILE> Some help text
+
+pub fn value_name(self, name: &'b str) -> Self
[src]Specifies the name for value of option or positional arguments inside of help
+documentation. This name is cosmetic only, the name is not used to access arguments.
+This setting can be very helpful when describing the type of input the user should be
+using, such as FILE
, INTERFACE
, etc. Although not required, it's somewhat convention to
+use all capital letters for the value name.
NOTE: implicitly sets Arg::takes_value(true)
+Arg::with_name("cfg") + .long("config") + .value_name("FILE")
+let m = App::new("prog") + .arg(Arg::with_name("config") + .long("config") + .value_name("FILE")) + .get_matches_from(vec![ + "prog", "--help" + ]);
Running the above program produces the following output
+valnames
+
+USAGE:
+ valnames [FLAGS] [OPTIONS]
+
+FLAGS:
+ -h, --help Prints help information
+ -V, --version Prints version information
+
+OPTIONS:
+ --config <FILE> Some help text
+
+pub fn default_value(self, val: &'a str) -> Self
[src]Specifies the value of the argument when not specified at runtime.
+NOTE: If the user does not use this argument at runtime, ArgMatches::occurrences_of
+will return 0
even though the ArgMatches::value_of
will return the default specified.
NOTE: If the user does not use this argument at runtime ArgMatches::is_present
will
+still return true
. If you wish to determine whether the argument was used at runtime or
+not, consider ArgMatches::occurrences_of
which will return 0
if the argument was not
+used at runtime.
NOTE: This setting is perfectly compatible with Arg::default_value_if
but slightly
+different. Arg::default_value
only takes affect when the user has not provided this arg
+at runtime. Arg::default_value_if
however only takes affect when the user has not provided
+a value at runtime and these other conditions are met as well. If you have set
+Arg::default_value
and Arg::default_value_if
, and the user did not provide a this
+arg at runtime, nor did were the conditions met for Arg::default_value_if
, the
+Arg::default_value
will be applied.
NOTE: This implicitly sets Arg::takes_value(true)
.
NOTE: This setting effectively disables AppSettings::ArgRequiredElseHelp
if used in
+conjunction as it ensures that some argument will always be present.
First we use the default value without providing any value at runtime.
+ ++let m = App::new("prog") + .arg(Arg::with_name("opt") + .long("myopt") + .default_value("myval")) + .get_matches_from(vec![ + "prog" + ]); + +assert_eq!(m.value_of("opt"), Some("myval")); +assert!(m.is_present("opt")); +assert_eq!(m.occurrences_of("opt"), 0);
Next we provide a value at runtime to override the default.
+ ++let m = App::new("prog") + .arg(Arg::with_name("opt") + .long("myopt") + .default_value("myval")) + .get_matches_from(vec![ + "prog", "--myopt=non_default" + ]); + +assert_eq!(m.value_of("opt"), Some("non_default")); +assert!(m.is_present("opt")); +assert_eq!(m.occurrences_of("opt"), 1);
pub fn default_value_os(self, val: &'a OsStr) -> Self
[src]Provides a default value in the exact same manner as [Arg::default_value
]
+only using [OsStr
]s instead.
+[Arg::default_value
]: ./struct.Arg.html#method.default_value
+[OsStr
]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html
pub fn default_value_if(
self,
arg: &'a str,
val: Option<&'b str>,
default: &'b str
) -> Self
[src]Specifies the value of the argument if arg
has been used at runtime. If val
is set to
+None
, arg
only needs to be present. If val
is set to "some-val"
then arg
must be
+present at runtime and have the value val
.
NOTE: This setting is perfectly compatible with Arg::default_value
but slightly
+different. Arg::default_value
only takes affect when the user has not provided this arg
+at runtime. This setting however only takes affect when the user has not provided a value at
+runtime and these other conditions are met as well. If you have set Arg::default_value
+and Arg::default_value_if
, and the user did not provide a this arg at runtime, nor did
+were the conditions met for Arg::default_value_if
, the Arg::default_value
will be
+applied.
NOTE: This implicitly sets Arg::takes_value(true)
.
NOTE: If using YAML the values should be laid out as follows (None
can be represented
+as null
in YAML)
default_value_if:
+ - [arg, val, default]
+
+First we use the default value only if another arg is present at runtime.
+ ++let m = App::new("prog") + .arg(Arg::with_name("flag") + .long("flag")) + .arg(Arg::with_name("other") + .long("other") + .default_value_if("flag", None, "default")) + .get_matches_from(vec![ + "prog", "--flag" + ]); + +assert_eq!(m.value_of("other"), Some("default"));
Next we run the same test, but without providing --flag
.
+let m = App::new("prog") + .arg(Arg::with_name("flag") + .long("flag")) + .arg(Arg::with_name("other") + .long("other") + .default_value_if("flag", None, "default")) + .get_matches_from(vec![ + "prog" + ]); + +assert_eq!(m.value_of("other"), None);
Now lets only use the default value if --opt
contains the value special
.
+let m = App::new("prog") + .arg(Arg::with_name("opt") + .takes_value(true) + .long("opt")) + .arg(Arg::with_name("other") + .long("other") + .default_value_if("opt", Some("special"), "default")) + .get_matches_from(vec![ + "prog", "--opt", "special" + ]); + +assert_eq!(m.value_of("other"), Some("default"));
We can run the same test and provide any value other than special
and we won't get a
+default value.
+let m = App::new("prog") + .arg(Arg::with_name("opt") + .takes_value(true) + .long("opt")) + .arg(Arg::with_name("other") + .long("other") + .default_value_if("opt", Some("special"), "default")) + .get_matches_from(vec![ + "prog", "--opt", "hahaha" + ]); + +assert_eq!(m.value_of("other"), None);
pub fn default_value_if_os(
self,
arg: &'a str,
val: Option<&'b OsStr>,
default: &'b OsStr
) -> Self
[src]Provides a conditional default value in the exact same manner as [Arg::default_value_if
]
+only using [OsStr
]s instead.
+[Arg::default_value_if
]: ./struct.Arg.html#method.default_value_if
+[OsStr
]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html
pub fn default_value_ifs(
self,
ifs: &[(&'a str, Option<&'b str>, &'b str)]
) -> Self
[src]Specifies multiple values and conditions in the same manner as [Arg::default_value_if
].
+The method takes a slice of tuples in the (arg, Option<val>, default)
format.
NOTE: The conditions are stored in order and evaluated in the same order. I.e. the first +if multiple conditions are true, the first one found will be applied and the ultimate value.
+NOTE: If using YAML the values should be laid out as follows
+default_value_if:
+ - [arg, val, default]
+ - [arg2, null, default2]
+
+First we use the default value only if another arg is present at runtime.
+ ++let m = App::new("prog") + .arg(Arg::with_name("flag") + .long("flag")) + .arg(Arg::with_name("opt") + .long("opt") + .takes_value(true)) + .arg(Arg::with_name("other") + .long("other") + .default_value_ifs(&[ + ("flag", None, "default"), + ("opt", Some("channal"), "chan"), + ])) + .get_matches_from(vec![ + "prog", "--opt", "channal" + ]); + +assert_eq!(m.value_of("other"), Some("chan"));
Next we run the same test, but without providing --flag
.
+let m = App::new("prog") + .arg(Arg::with_name("flag") + .long("flag")) + .arg(Arg::with_name("other") + .long("other") + .default_value_ifs(&[ + ("flag", None, "default"), + ("opt", Some("channal"), "chan"), + ])) + .get_matches_from(vec![ + "prog" + ]); + +assert_eq!(m.value_of("other"), None);
We can also see that these values are applied in order, and if more than one condition is +true, only the first evaluated "wins"
+ ++let m = App::new("prog") + .arg(Arg::with_name("flag") + .long("flag")) + .arg(Arg::with_name("opt") + .long("opt") + .takes_value(true)) + .arg(Arg::with_name("other") + .long("other") + .default_value_ifs(&[ + ("flag", None, "default"), + ("opt", Some("channal"), "chan"), + ])) + .get_matches_from(vec![ + "prog", "--opt", "channal", "--flag" + ]); + +assert_eq!(m.value_of("other"), Some("default"));
pub fn default_value_ifs_os(
self,
ifs: &[(&'a str, Option<&'b OsStr>, &'b OsStr)]
) -> Self
[src]Provides multiple conditional default values in the exact same manner as
+[Arg::default_value_ifs
] only using [OsStr
]s instead.
+[Arg::default_value_ifs
]: ./struct.Arg.html#method.default_value_ifs
+[OsStr
]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html
pub fn env(self, name: &'a str) -> Self
[src]Specifies that if the value is not passed in as an argument, that it should be retrieved +from the environment, if available. If it is not present in the environment, then default +rules will apply.
+NOTE: If the user does not use this argument at runtime, ArgMatches::occurrences_of
+will return 0
even though the ArgMatches::value_of
will return the default specified.
NOTE: If the user does not use this argument at runtime ArgMatches::is_present
will
+return true
if the variable is present in the environment . If you wish to determine whether
+the argument was used at runtime or not, consider ArgMatches::occurrences_of
which will
+return 0
if the argument was not used at runtime.
NOTE: This implicitly sets Arg::takes_value(true)
.
NOTE: If Arg::multiple(true)
is set then Arg::use_delimiter(true)
should also be
+set. Otherwise, only a single argument will be returned from the environment variable. The
+default delimiter is ,
and follows all the other delimiter rules.
In this example, we show the variable coming from the environment:
+ ++ +env::set_var("MY_FLAG", "env"); + +let m = App::new("prog") + .arg(Arg::with_name("flag") + .long("flag") + .env("MY_FLAG")) + .get_matches_from(vec![ + "prog" + ]); + +assert_eq!(m.value_of("flag"), Some("env"));
In this example, we show the variable coming from an option on the CLI:
+ ++ +env::set_var("MY_FLAG", "env"); + +let m = App::new("prog") + .arg(Arg::with_name("flag") + .long("flag") + .env("MY_FLAG")) + .get_matches_from(vec![ + "prog", "--flag", "opt" + ]); + +assert_eq!(m.value_of("flag"), Some("opt"));
In this example, we show the variable coming from the environment even with the +presence of a default:
+ ++ +env::set_var("MY_FLAG", "env"); + +let m = App::new("prog") + .arg(Arg::with_name("flag") + .long("flag") + .env("MY_FLAG") + .default_value("default")) + .get_matches_from(vec![ + "prog" + ]); + +assert_eq!(m.value_of("flag"), Some("env"));
In this example, we show the use of multiple values in a single environment variable:
+ ++ +env::set_var("MY_FLAG_MULTI", "env1,env2"); + +let m = App::new("prog") + .arg(Arg::with_name("flag") + .long("flag") + .env("MY_FLAG_MULTI") + .multiple(true) + .use_delimiter(true)) + .get_matches_from(vec![ + "prog" + ]); + +assert_eq!(m.values_of("flag").unwrap().collect::<Vec<_>>(), vec!["env1", "env2"]);
pub fn env_os(self, name: &'a OsStr) -> Self
[src]Specifies that if the value is not passed in as an argument, that it should be retrieved
+from the environment if available in the exact same manner as [Arg::env
] only using
+[OsStr
]s instead.
pub fn hide_env_values(self, hide: bool) -> Self
[src]@TODO @p2 @docs @release: write docs
+pub fn next_line_help(self, nlh: bool) -> Self
[src]When set to true
the help string will be displayed on the line after the argument and
+indented once. This can be helpful for arguments with very long or complex help messages.
+This can also be helpful for arguments with very long flag names, or many/long value names.
NOTE: To apply this setting to all arguments consider using
+AppSettings::NextLineHelp
+let m = App::new("prog") + .arg(Arg::with_name("opt") + .long("long-option-flag") + .short("o") + .takes_value(true) + .value_names(&["value1", "value2"]) + .help("Some really long help and complex\n\ + help that makes more sense to be\n\ + on a line after the option") + .next_line_help(true)) + .get_matches_from(vec![ + "prog", "--help" + ]);
The above example displays the following help message
+nlh
+
+USAGE:
+ nlh [FLAGS] [OPTIONS]
+
+FLAGS:
+ -h, --help Prints help information
+ -V, --version Prints version information
+
+OPTIONS:
+ -o, --long-option-flag <value1> <value2>
+ Some really long help and complex
+ help that makes more sense to be
+ on a line after the option
+
+pub fn display_order(self, ord: usize) -> Self
[src]Allows custom ordering of args within the help message. Args with a lower value will be +displayed first in the help message. This is helpful when one would like to emphasise +frequently used args, or prioritize those towards the top of the list. Duplicate values +are allowed. Args with duplicate display orders will be displayed in alphabetical +order.
+NOTE: The default is 999 for all arguments.
+NOTE: This setting is ignored for positional arguments which are always displayed in +index order.
++let m = App::new("prog") + .arg(Arg::with_name("a") // Typically args are grouped alphabetically by name. + // Args without a display_order have a value of 999 and are + // displayed alphabetically with all other 999 valued args. + .long("long-option") + .short("o") + .takes_value(true) + .help("Some help and text")) + .arg(Arg::with_name("b") + .long("other-option") + .short("O") + .takes_value(true) + .display_order(1) // In order to force this arg to appear *first* + // all we have to do is give it a value lower than 999. + // Any other args with a value of 1 will be displayed + // alphabetically with this one...then 2 values, then 3, etc. + .help("I should be first!")) + .get_matches_from(vec![ + "prog", "--help" + ]);
The above example displays the following help message
+cust-ord
+
+USAGE:
+ cust-ord [FLAGS] [OPTIONS]
+
+FLAGS:
+ -h, --help Prints help information
+ -V, --version Prints version information
+
+OPTIONS:
+ -O, --other-option <b> I should be first!
+ -o, --long-option <a> Some help and text
+
+pub fn raw(self, raw: bool) -> Self
[src]Indicates that all parameters passed after this should not be parsed
+individually, but rather passed in their entirety. It is worth noting
+that setting this requires all values to come after a --
to indicate they
+should all be captured. For example:
--foo something -- -v -v -v -b -b -b --baz -q -u -x
+
+Will result in everything after --
to be considered one raw argument. This behavior
+may not be exactly what you are expecting and using AppSettings::TrailingVarArg
+may be more appropriate.
NOTE: Implicitly sets Arg::multiple(true)
, Arg::allow_hyphen_values(true)
, and
+Arg::last(true)
when set to true
pub fn hidden_short_help(self, hide: bool) -> Self
[src]Hides an argument from short help message output.
+NOTE: This does not hide the argument from usage strings on error
+NOTE: Setting this option will cause next-line-help output style to be used
+when long help (--help
) is called.
+Arg::with_name("debug") + .hidden_short_help(true)
Setting hidden_short_help(true)
will hide the argument when displaying short help text
+let m = App::new("prog") + .arg(Arg::with_name("cfg") + .long("config") + .hidden_short_help(true) + .help("Some help text describing the --config arg")) + .get_matches_from(vec![ + "prog", "-h" + ]);
The above example displays
+helptest
+
+USAGE:
+ helptest [FLAGS]
+
+FLAGS:
+-h, --help Prints help information
+-V, --version Prints version information
+
+However, when --help is called
+ ++let m = App::new("prog") + .arg(Arg::with_name("cfg") + .long("config") + .hidden_short_help(true) + .help("Some help text describing the --config arg")) + .get_matches_from(vec![ + "prog", "--help" + ]);
Then the following would be displayed
+helptest
+
+USAGE:
+ helptest [FLAGS]
+
+FLAGS:
+ --config Some help text describing the --config arg
+-h, --help Prints help information
+-V, --version Prints version information
+
+pub fn hidden_long_help(self, hide: bool) -> Self
[src]Hides an argument from long help message output.
+NOTE: This does not hide the argument from usage strings on error
+NOTE: Setting this option will cause next-line-help output style to be used
+when long help (--help
) is called.
+Arg::with_name("debug") + .hidden_long_help(true)
Setting hidden_long_help(true)
will hide the argument when displaying long help text
+let m = App::new("prog") + .arg(Arg::with_name("cfg") + .long("config") + .hidden_long_help(true) + .help("Some help text describing the --config arg")) + .get_matches_from(vec![ + "prog", "--help" + ]);
The above example displays
+helptest
+
+USAGE:
+ helptest [FLAGS]
+
+FLAGS:
+-h, --help Prints help information
+-V, --version Prints version information
+
+However, when -h is called
+ ++let m = App::new("prog") + .arg(Arg::with_name("cfg") + .long("config") + .hidden_long_help(true) + .help("Some help text describing the --config arg")) + .get_matches_from(vec![ + "prog", "-h" + ]);
Then the following would be displayed
+helptest
+
+USAGE:
+ helptest [FLAGS]
+
+FLAGS:
+ --config Some help text describing the --config arg
+-h, --help Prints help information
+-V, --version Prints version information
+
+pub fn is_set(&self, s: ArgSettings) -> bool
[src]Checks if one of the ArgSettings
settings is set for the argument.
pub fn set(self, s: ArgSettings) -> Self
[src]Sets one of the ArgSettings
settings for the argument.
pub fn unset(self, s: ArgSettings) -> Self
[src]Unsets one of the ArgSettings
settings for the argument.
impl<'a, 'b> Clone for Arg<'a, 'b> where
'a: 'b,
[src]impl<'a, 'b> Default for Arg<'a, 'b> where
'a: 'b,
[src]impl<'a, 'b, 'z> From<&'z Arg<'a, 'b>> for Arg<'a, 'b>
[src]impl<'n, 'e> PartialEq<Arg<'n, 'e>> for Arg<'n, 'e>
[src]impl<'a, 'b> !RefUnwindSafe for Arg<'a, 'b>
impl<'a, 'b> !Send for Arg<'a, 'b>
impl<'a, 'b> !Sync for Arg<'a, 'b>
impl<'a, 'b> Unpin for Arg<'a, 'b>
impl<'a, 'b> !UnwindSafe for Arg<'a, 'b>
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<T> ToOwned for T where
T: Clone,
[src]type Owned = T
The resulting type after obtaining ownership.
+fn to_owned(&self) -> T
[src]fn clone_into(&self, target: &mut T)
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]ArgGroup
s are a family of related arguments and way for you to express, "Any of these
+arguments". By placing arguments in a logical group, you can create easier requirement and
+exclusion rules instead of having to list each argument individually, or when you want a rule
+to apply "any but not all" arguments.
For instance, you can make an entire ArgGroup
required. If ArgGroup::multiple(true)
is
+set, this means that at least one argument from that group must be present. If
+[ArgGroup::multiple(false)
] is set (the default), one and only one must be present.
You can also do things such as name an entire ArgGroup
as a conflict or requirement for
+another argument, meaning any of the arguments that belong to that group will cause a failure
+if present, or must present respectively.
Perhaps the most common use of ArgGroup
s is to require one and only one argument to be
+present out of a given set. Imagine that you had multiple arguments, and you want one of them
+to be required, but making all of them required isn't feasible because perhaps they conflict
+with each other. For example, lets say that you were building an application where one could
+set a given version number by supplying a string with an option argument, i.e.
+--set-ver v1.2.3
, you also wanted to support automatically using a previous version number
+and simply incrementing one of the three numbers. So you create three flags --major
,
+--minor
, and --patch
. All of these arguments shouldn't be used at one time but you want to
+specify that at least one of them is used. For this, you can create a group.
Finally, you may use ArgGroup
s to pull a value from a group of arguments when you don't care
+exactly which argument was actually used at runtime.
The following example demonstrates using an ArgGroup
to ensure that one, and only one, of
+the arguments from the specified group is present at runtime.
+let result = App::new("app") + .args_from_usage( + "--set-ver [ver] 'set the version manually' + --major 'auto increase major' + --minor 'auto increase minor' + --patch 'auto increase patch'") + .group(ArgGroup::with_name("vers") + .args(&["set-ver", "major", "minor", "patch"]) + .required(true)) + .get_matches_from_safe(vec!["app", "--major", "--patch"]); +// Because we used two args in the group it's an error +assert!(result.is_err()); +let err = result.unwrap_err(); +assert_eq!(err.kind, ErrorKind::ArgumentConflict);
This next example shows a passing parse of the same scenario
+ ++let result = App::new("app") + .args_from_usage( + "--set-ver [ver] 'set the version manually' + --major 'auto increase major' + --minor 'auto increase minor' + --patch 'auto increase patch'") + .group(ArgGroup::with_name("vers") + .args(&["set-ver", "major", "minor","patch"]) + .required(true)) + .get_matches_from_safe(vec!["app", "--major"]); +assert!(result.is_ok()); +let matches = result.unwrap(); +// We may not know which of the args was used, so we can test for the group... +assert!(matches.is_present("vers")); +// we could also alternatively check each arg individually (not shown here)
impl<'a> ArgGroup<'a>
[src]pub fn with_name(n: &'a str) -> Self
[src]Creates a new instance of ArgGroup
using a unique string name. The name will be used to
+get values from the group or refer to the group inside of conflict and requirement rules.
+ArgGroup::with_name("config")
pub fn from_yaml(y: &'a Yaml) -> ArgGroup<'a>
[src]Creates a new instance of ArgGroup
from a .yml (YAML) file.
+let yml = load_yaml!("group.yml"); +let ag = ArgGroup::from_yaml(yml);
pub fn arg(self, n: &'a str) -> Self
[src]Adds an argument to this group by name
++let m = App::new("myprog") + .arg(Arg::with_name("flag") + .short("f")) + .arg(Arg::with_name("color") + .short("c")) + .group(ArgGroup::with_name("req_flags") + .arg("flag") + .arg("color")) + .get_matches_from(vec!["myprog", "-f"]); +// maybe we don't know which of the two flags was used... +assert!(m.is_present("req_flags")); +// but we can also check individually if needed +assert!(m.is_present("flag"));
pub fn args(self, ns: &[&'a str]) -> Self
[src]Adds multiple arguments to this group by name
++let m = App::new("myprog") + .arg(Arg::with_name("flag") + .short("f")) + .arg(Arg::with_name("color") + .short("c")) + .group(ArgGroup::with_name("req_flags") + .args(&["flag", "color"])) + .get_matches_from(vec!["myprog", "-f"]); +// maybe we don't know which of the two flags was used... +assert!(m.is_present("req_flags")); +// but we can also check individually if needed +assert!(m.is_present("flag"));
pub fn multiple(self, m: bool) -> Self
[src]Allows more than one of the 'Arg's in this group to be used. (Default: false
)
Notice in this example we use both the -f
and -c
flags which are both part of the
+group
+let m = App::new("myprog") + .arg(Arg::with_name("flag") + .short("f")) + .arg(Arg::with_name("color") + .short("c")) + .group(ArgGroup::with_name("req_flags") + .args(&["flag", "color"]) + .multiple(true)) + .get_matches_from(vec!["myprog", "-f", "-c"]); +// maybe we don't know which of the two flags was used... +assert!(m.is_present("req_flags"));
In this next example, we show the default behavior (i.e. `multiple(false)) which will throw +an error if more than one of the args in the group was used.
+ ++let result = App::new("myprog") + .arg(Arg::with_name("flag") + .short("f")) + .arg(Arg::with_name("color") + .short("c")) + .group(ArgGroup::with_name("req_flags") + .args(&["flag", "color"])) + .get_matches_from_safe(vec!["myprog", "-f", "-c"]); +// Because we used both args in the group it's an error +assert!(result.is_err()); +let err = result.unwrap_err(); +assert_eq!(err.kind, ErrorKind::ArgumentConflict);
pub fn required(self, r: bool) -> Self
[src]Sets the group as required or not. A required group will be displayed in the usage string
+of the application in the format <arg|arg2|arg3>
. A required ArgGroup
simply states
+that one argument from this group must be present at runtime (unless
+conflicting with another argument).
NOTE: This setting only applies to the current App
/ SubCommand
, and not
+globally.
NOTE: By default, ArgGroup::multiple
is set to false
which when combined with
+ArgGroup::required(true)
states, "One and only one arg must be used from this group.
+Use of more than one arg is an error." Vice setting ArgGroup::multiple(true)
which
+states, 'At least one arg from this group must be used. Using multiple is OK."
+let result = App::new("myprog") + .arg(Arg::with_name("flag") + .short("f")) + .arg(Arg::with_name("color") + .short("c")) + .group(ArgGroup::with_name("req_flags") + .args(&["flag", "color"]) + .required(true)) + .get_matches_from_safe(vec!["myprog"]); +// Because we didn't use any of the args in the group, it's an error +assert!(result.is_err()); +let err = result.unwrap_err(); +assert_eq!(err.kind, ErrorKind::MissingRequiredArgument);
pub fn requires(self, n: &'a str) -> Self
[src]Sets the requirement rules of this group. This is not to be confused with a +required group. Requirement rules function just like argument requirement rules, you +can name other arguments or groups that must be present when any one of the arguments from +this group is used.
+NOTE: The name provided may be an argument, or group name
++let result = App::new("myprog") + .arg(Arg::with_name("flag") + .short("f")) + .arg(Arg::with_name("color") + .short("c")) + .arg(Arg::with_name("debug") + .short("d")) + .group(ArgGroup::with_name("req_flags") + .args(&["flag", "color"]) + .requires("debug")) + .get_matches_from_safe(vec!["myprog", "-c"]); +// because we used an arg from the group, and the group requires "-d" to be used, it's an +// error +assert!(result.is_err()); +let err = result.unwrap_err(); +assert_eq!(err.kind, ErrorKind::MissingRequiredArgument);
pub fn requires_all(self, ns: &[&'a str]) -> Self
[src]Sets the requirement rules of this group. This is not to be confused with a +required group. Requirement rules function just like argument requirement rules, you +can name other arguments or groups that must be present when one of the arguments from this +group is used.
+NOTE: The names provided may be an argument, or group name
++let result = App::new("myprog") + .arg(Arg::with_name("flag") + .short("f")) + .arg(Arg::with_name("color") + .short("c")) + .arg(Arg::with_name("debug") + .short("d")) + .arg(Arg::with_name("verb") + .short("v")) + .group(ArgGroup::with_name("req_flags") + .args(&["flag", "color"]) + .requires_all(&["debug", "verb"])) + .get_matches_from_safe(vec!["myprog", "-c", "-d"]); +// because we used an arg from the group, and the group requires "-d" and "-v" to be used, +// yet we only used "-d" it's an error +assert!(result.is_err()); +let err = result.unwrap_err(); +assert_eq!(err.kind, ErrorKind::MissingRequiredArgument);
pub fn conflicts_with(self, n: &'a str) -> Self
[src]Sets the exclusion rules of this group. Exclusion (aka conflict) rules function just like +argument exclusion rules, you can name other arguments or groups that must not be +present when one of the arguments from this group are used.
+NOTE: The name provided may be an argument, or group name
++let result = App::new("myprog") + .arg(Arg::with_name("flag") + .short("f")) + .arg(Arg::with_name("color") + .short("c")) + .arg(Arg::with_name("debug") + .short("d")) + .group(ArgGroup::with_name("req_flags") + .args(&["flag", "color"]) + .conflicts_with("debug")) + .get_matches_from_safe(vec!["myprog", "-c", "-d"]); +// because we used an arg from the group, and the group conflicts with "-d", it's an error +assert!(result.is_err()); +let err = result.unwrap_err(); +assert_eq!(err.kind, ErrorKind::ArgumentConflict);
pub fn conflicts_with_all(self, ns: &[&'a str]) -> Self
[src]Sets the exclusion rules of this group. Exclusion rules function just like +argument exclusion rules, you can name other arguments or groups that must not be +present when one of the arguments from this group are used.
+NOTE: The names provided may be an argument, or group name
++let result = App::new("myprog") + .arg(Arg::with_name("flag") + .short("f")) + .arg(Arg::with_name("color") + .short("c")) + .arg(Arg::with_name("debug") + .short("d")) + .arg(Arg::with_name("verb") + .short("v")) + .group(ArgGroup::with_name("req_flags") + .args(&["flag", "color"]) + .conflicts_with_all(&["debug", "verb"])) + .get_matches_from_safe(vec!["myprog", "-c", "-v"]); +// because we used an arg from the group, and the group conflicts with either "-v" or "-d" +// it's an error +assert!(result.is_err()); +let err = result.unwrap_err(); +assert_eq!(err.kind, ErrorKind::ArgumentConflict);
impl<'a> Clone for ArgGroup<'a>
[src]fn clone(&self) -> Self
[src]fn clone_from(&mut self, source: &Self)
1.0.0[src]impl<'a> Debug for ArgGroup<'a>
[src]impl<'a> Default for ArgGroup<'a>
[src]impl<'a> From<&'a BTreeMap<Yaml, Yaml>> for ArgGroup<'a>
[src]impl<'a, 'z> From<&'z ArgGroup<'a>> for ArgGroup<'a>
[src]impl<'a> RefUnwindSafe for ArgGroup<'a>
impl<'a> Send for ArgGroup<'a>
impl<'a> Sync for ArgGroup<'a>
impl<'a> Unpin for ArgGroup<'a>
impl<'a> UnwindSafe for ArgGroup<'a>
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<T> ToOwned for T where
T: Clone,
[src]type Owned = T
The resulting type after obtaining ownership.
+fn to_owned(&self) -> T
[src]fn clone_into(&self, target: &mut T)
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]Used to get information about the arguments that were supplied to the program at runtime by
+the user. New instances of this struct are obtained by using the App::get_matches
family of
+methods.
+let matches = App::new("MyApp") + .arg(Arg::with_name("out") + .long("output") + .required(true) + .takes_value(true)) + .arg(Arg::with_name("debug") + .short("d") + .multiple(true)) + .arg(Arg::with_name("cfg") + .short("c") + .takes_value(true)) + .get_matches(); // builds the instance of ArgMatches + +// to get information about the "cfg" argument we created, such as the value supplied we use +// various ArgMatches methods, such as ArgMatches::value_of +if let Some(c) = matches.value_of("cfg") { + println!("Value for -c: {}", c); +} + +// The ArgMatches::value_of method returns an Option because the user may not have supplied +// that argument at runtime. But if we specified that the argument was "required" as we did +// with the "out" argument, we can safely unwrap because `clap` verifies that was actually +// used at runtime. +println!("Value for --output: {}", matches.value_of("out").unwrap()); + +// You can check the presence of an argument +if matches.is_present("out") { + // Another way to check if an argument was present, or if it occurred multiple times is to + // use occurrences_of() which returns 0 if an argument isn't found at runtime, or the + // number of times that it occurred, if it was. To allow an argument to appear more than + // once, you must use the .multiple(true) method, otherwise it will only return 1 or 0. + if matches.occurrences_of("debug") > 2 { + println!("Debug mode is REALLY on, don't be crazy"); + } else { + println!("Debug mode kind of on"); + } +}
impl<'a> ArgMatches<'a>
[src]pub fn value_of<S: AsRef<str>>(&self, name: S) -> Option<&str>
[src]Gets the value of a specific option or positional argument (i.e. an argument that takes
+an additional value at runtime). If the option wasn't present at runtime
+it returns None
.
NOTE: If getting a value for an option or positional argument that allows multiples,
+prefer ArgMatches::values_of
as ArgMatches::value_of
will only return the first
+value.
This method will panic!
if the value contains invalid UTF-8 code points.
+let m = App::new("myapp") + .arg(Arg::with_name("output") + .takes_value(true)) + .get_matches_from(vec!["myapp", "something"]); + +assert_eq!(m.value_of("output"), Some("something"));
pub fn value_of_lossy<S: AsRef<str>>(&'a self, name: S) -> Option<Cow<'a, str>>
[src]Gets the lossy value of a specific argument. If the argument wasn't present at runtime
+it returns None
. A lossy value is one which contains invalid UTF-8 code points, those
+invalid points will be replaced with \u{FFFD}
NOTE: If getting a value for an option or positional argument that allows multiples,
+prefer Arg::values_of_lossy
as value_of_lossy()
will only return the first value.
+use std::ffi::OsString; +use std::os::unix::ffi::{OsStrExt,OsStringExt}; + +let m = App::new("utf8") + .arg(Arg::from_usage("<arg> 'some arg'")) + .get_matches_from(vec![OsString::from("myprog"), + // "Hi {0xe9}!" + OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); +assert_eq!(&*m.value_of_lossy("arg").unwrap(), "Hi \u{FFFD}!");
pub fn value_of_os<S: AsRef<str>>(&self, name: S) -> Option<&OsStr>
[src]Gets the OS version of a string value of a specific argument. If the option wasn't present
+at runtime it returns None
. An OS value on Unix-like systems is any series of bytes,
+regardless of whether or not they contain valid UTF-8 code points. Since String
s in
+Rust are guaranteed to be valid UTF-8, a valid filename on a Unix system as an argument
+value may contain invalid UTF-8 code points.
NOTE: If getting a value for an option or positional argument that allows multiples,
+prefer ArgMatches::values_of_os
as Arg::value_of_os
will only return the first
+value.
+use std::ffi::OsString; +use std::os::unix::ffi::{OsStrExt,OsStringExt}; + +let m = App::new("utf8") + .arg(Arg::from_usage("<arg> 'some arg'")) + .get_matches_from(vec![OsString::from("myprog"), + // "Hi {0xe9}!" + OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); +assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']);
pub fn values_of<S: AsRef<str>>(&'a self, name: S) -> Option<Values<'a>>
[src]Gets a Values
struct which implements Iterator
for values of a specific argument
+(i.e. an argument that takes multiple values at runtime). If the option wasn't present at
+runtime it returns None
This method will panic if any of the values contain invalid UTF-8 code points.
++let m = App::new("myprog") + .arg(Arg::with_name("output") + .multiple(true) + .short("o") + .takes_value(true)) + .get_matches_from(vec![ + "myprog", "-o", "val1", "val2", "val3" + ]); +let vals: Vec<&str> = m.values_of("output").unwrap().collect(); +assert_eq!(vals, ["val1", "val2", "val3"]);
pub fn values_of_lossy<S: AsRef<str>>(&'a self, name: S) -> Option<Vec<String>>
[src]Gets the lossy values of a specific argument. If the option wasn't present at runtime
+it returns None
. A lossy value is one where if it contains invalid UTF-8 code points,
+those invalid points will be replaced with \u{FFFD}
+use std::ffi::OsString; +use std::os::unix::ffi::OsStringExt; + +let m = App::new("utf8") + .arg(Arg::from_usage("<arg>... 'some arg'")) + .get_matches_from(vec![OsString::from("myprog"), + // "Hi" + OsString::from_vec(vec![b'H', b'i']), + // "{0xe9}!" + OsString::from_vec(vec![0xe9, b'!'])]); +let mut itr = m.values_of_lossy("arg").unwrap().into_iter(); +assert_eq!(&itr.next().unwrap()[..], "Hi"); +assert_eq!(&itr.next().unwrap()[..], "\u{FFFD}!"); +assert_eq!(itr.next(), None);
pub fn values_of_os<S: AsRef<str>>(&'a self, name: S) -> Option<OsValues<'a>>
[src]Gets a OsValues
struct which is implements Iterator
for OsString
values of a
+specific argument. If the option wasn't present at runtime it returns None
. An OS value
+on Unix-like systems is any series of bytes, regardless of whether or not they contain
+valid UTF-8 code points. Since String
s in Rust are guaranteed to be valid UTF-8, a valid
+filename as an argument value on Linux (for example) may contain invalid UTF-8 code points.
+use std::ffi::{OsStr,OsString}; +use std::os::unix::ffi::{OsStrExt,OsStringExt}; + +let m = App::new("utf8") + .arg(Arg::from_usage("<arg>... 'some arg'")) + .get_matches_from(vec![OsString::from("myprog"), + // "Hi" + OsString::from_vec(vec![b'H', b'i']), + // "{0xe9}!" + OsString::from_vec(vec![0xe9, b'!'])]); + +let mut itr = m.values_of_os("arg").unwrap().into_iter(); +assert_eq!(itr.next(), Some(OsStr::new("Hi"))); +assert_eq!(itr.next(), Some(OsStr::from_bytes(&[0xe9, b'!']))); +assert_eq!(itr.next(), None);
pub fn is_present<S: AsRef<str>>(&self, name: S) -> bool
[src]Returns true
if an argument was present at runtime, otherwise false
.
+let m = App::new("myprog") + .arg(Arg::with_name("debug") + .short("d")) + .get_matches_from(vec![ + "myprog", "-d" + ]); + +assert!(m.is_present("debug"));
pub fn occurrences_of<S: AsRef<str>>(&self, name: S) -> u64
[src]Returns the number of times an argument was used at runtime. If an argument isn't present
+it will return 0
.
NOTE: This returns the number of times the argument was used, not the number of
+values. For example, -o val1 val2 val3 -o val4
would return 2
(2 occurrences, but 4
+values).
+let m = App::new("myprog") + .arg(Arg::with_name("debug") + .short("d") + .multiple(true)) + .get_matches_from(vec![ + "myprog", "-d", "-d", "-d" + ]); + +assert_eq!(m.occurrences_of("debug"), 3);
This next example shows that counts actual uses of the argument, not just -
's
+let m = App::new("myprog") + .arg(Arg::with_name("debug") + .short("d") + .multiple(true)) + .arg(Arg::with_name("flag") + .short("f")) + .get_matches_from(vec![ + "myprog", "-ddfd" + ]); + +assert_eq!(m.occurrences_of("debug"), 3); +assert_eq!(m.occurrences_of("flag"), 1);
pub fn index_of<S: AsRef<str>>(&self, name: S) -> Option<usize>
[src]Gets the starting index of the argument in respect to all other arguments. Indices are +similar to argv indices, but are not exactly 1:1.
+For flags (i.e. those arguments which don't have an associated value), indices refer
+to occurrence of the switch, such as -f
, or --flag
. However, for options the indices
+refer to the values -o val
would therefore not represent two distinct indices, only the
+index for val
would be recorded. This is by design.
Besides the flag/option descrepancy, the primary difference between an argv index and clap +index, is that clap continues counting once all arguments have properly seperated, whereas +an argv index does not.
+The examples should clear this up.
+NOTE: If an argument is allowed multiple times, this method will only give the first +index.
+The argv indices are listed in the comments below. See how they correspond to the clap
+indices. Note that if it's not listed in a clap index, this is becuase it's not saved in
+in an ArgMatches
struct for querying.
+let m = App::new("myapp") + .arg(Arg::with_name("flag") + .short("f")) + .arg(Arg::with_name("option") + .short("o") + .takes_value(true)) + .get_matches_from(vec!["myapp", "-f", "-o", "val"]); + // ARGV idices: ^0 ^1 ^2 ^3 + // clap idices: ^1 ^3 + +assert_eq!(m.index_of("flag"), Some(1)); +assert_eq!(m.index_of("option"), Some(3));
Now notice, if we use one of the other styles of options:
+ ++let m = App::new("myapp") + .arg(Arg::with_name("flag") + .short("f")) + .arg(Arg::with_name("option") + .short("o") + .takes_value(true)) + .get_matches_from(vec!["myapp", "-f", "-o=val"]); + // ARGV idices: ^0 ^1 ^2 + // clap idices: ^1 ^3 + +assert_eq!(m.index_of("flag"), Some(1)); +assert_eq!(m.index_of("option"), Some(3));
Things become much more complicated, or clear if we look at a more complex combination of +flags. Let's also throw in the final option style for good measure.
+ ++let m = App::new("myapp") + .arg(Arg::with_name("flag") + .short("f")) + .arg(Arg::with_name("flag2") + .short("F")) + .arg(Arg::with_name("flag3") + .short("z")) + .arg(Arg::with_name("option") + .short("o") + .takes_value(true)) + .get_matches_from(vec!["myapp", "-fzF", "-oval"]); + // ARGV idices: ^0 ^1 ^2 + // clap idices: ^1,2,3 ^5 + // + // clap sees the above as 'myapp -f -z -F -o val' + // ^0 ^1 ^2 ^3 ^4 ^5 +assert_eq!(m.index_of("flag"), Some(1)); +assert_eq!(m.index_of("flag2"), Some(3)); +assert_eq!(m.index_of("flag3"), Some(2)); +assert_eq!(m.index_of("option"), Some(5));
One final combination of flags/options to see how they combine:
+ ++let m = App::new("myapp") + .arg(Arg::with_name("flag") + .short("f")) + .arg(Arg::with_name("flag2") + .short("F")) + .arg(Arg::with_name("flag3") + .short("z")) + .arg(Arg::with_name("option") + .short("o") + .takes_value(true) + .multiple(true)) + .get_matches_from(vec!["myapp", "-fzFoval"]); + // ARGV idices: ^0 ^1 + // clap idices: ^1,2,3^5 + // + // clap sees the above as 'myapp -f -z -F -o val' + // ^0 ^1 ^2 ^3 ^4 ^5 +assert_eq!(m.index_of("flag"), Some(1)); +assert_eq!(m.index_of("flag2"), Some(3)); +assert_eq!(m.index_of("flag3"), Some(2)); +assert_eq!(m.index_of("option"), Some(5));
The last part to mention is when values are sent in multiple groups with a delimiter.
+ ++let m = App::new("myapp") + .arg(Arg::with_name("option") + .short("o") + .takes_value(true) + .multiple(true)) + .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); + // ARGV idices: ^0 ^1 + // clap idices: ^2 ^3 ^4 + // + // clap sees the above as 'myapp -o val1 val2 val3' + // ^0 ^1 ^2 ^3 ^4 +assert_eq!(m.index_of("option"), Some(2));
pub fn indices_of<S: AsRef<str>>(&'a self, name: S) -> Option<Indices<'a>>
[src]Gets all indices of the argument in respect to all other arguments. Indices are +similar to argv indices, but are not exactly 1:1.
+For flags (i.e. those arguments which don't have an associated value), indices refer
+to occurrence of the switch, such as -f
, or --flag
. However, for options the indices
+refer to the values -o val
would therefore not represent two distinct indices, only the
+index for val
would be recorded. This is by design.
NOTE: For more information about how clap indices compare to argv indices, see
+ArgMatches::index_of
+let m = App::new("myapp") + .arg(Arg::with_name("option") + .short("o") + .takes_value(true) + .use_delimiter(true) + .multiple(true)) + .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); + // ARGV idices: ^0 ^1 + // clap idices: ^2 ^3 ^4 + // + // clap sees the above as 'myapp -o val1 val2 val3' + // ^0 ^1 ^2 ^3 ^4 +assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 3, 4]);
Another quick example is when flags and options are used together
+ ++let m = App::new("myapp") + .arg(Arg::with_name("option") + .short("o") + .takes_value(true) + .multiple(true)) + .arg(Arg::with_name("flag") + .short("f") + .multiple(true)) + .get_matches_from(vec!["myapp", "-o", "val1", "-f", "-o", "val2", "-f"]); + // ARGV idices: ^0 ^1 ^2 ^3 ^4 ^5 ^6 + // clap idices: ^2 ^3 ^5 ^6 + +assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 5]); +assert_eq!(m.indices_of("flag").unwrap().collect::<Vec<_>>(), &[3, 6]);
One final example, which is an odd case; if we don't use value delimiter as we did with
+the first example above instead of val1
, val2
and val3
all being distinc values, they
+would all be a single value of val1,val2,val3
, in which case case they'd only receive a
+single index.
+let m = App::new("myapp") + .arg(Arg::with_name("option") + .short("o") + .takes_value(true) + .multiple(true)) + .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); + // ARGV idices: ^0 ^1 + // clap idices: ^2 + // + // clap sees the above as 'myapp -o "val1,val2,val3"' + // ^0 ^1 ^2 +assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2]);
pub fn subcommand_matches<S: AsRef<str>>(
&self,
name: S
) -> Option<&ArgMatches<'a>>
[src]Because Subcommand
s are essentially "sub-App
s" they have their own ArgMatches
+as well. This method returns the ArgMatches
for a particular subcommand or None
if
+the subcommand wasn't present at runtime.
+let app_m = App::new("myprog") + .arg(Arg::with_name("debug") + .short("d")) + .subcommand(SubCommand::with_name("test") + .arg(Arg::with_name("opt") + .long("option") + .takes_value(true))) + .get_matches_from(vec![ + "myprog", "-d", "test", "--option", "val" + ]); + +// Both parent commands, and child subcommands can have arguments present at the same times +assert!(app_m.is_present("debug")); + +// Get the subcommand's ArgMatches instance +if let Some(sub_m) = app_m.subcommand_matches("test") { + // Use the struct like normal + assert_eq!(sub_m.value_of("opt"), Some("val")); +}
pub fn subcommand_name(&self) -> Option<&str>
[src]Because Subcommand
s are essentially "sub-App
s" they have their own ArgMatches
+as well.But simply getting the sub-ArgMatches
doesn't help much if we don't also know
+which subcommand was actually used. This method returns the name of the subcommand that was
+used at runtime, or None
if one wasn't.
NOTE: Subcommands form a hierarchy, where multiple subcommands can be used at runtime, +but only a single subcommand from any group of sibling commands may used at once.
+An ASCII art depiction may help explain this better...Using a fictional version of git
as
+the demo subject. Imagine the following are all subcommands of git
(note, the author is
+aware these aren't actually all subcommands in the real git
interface, but it makes
+explanation easier)
Top Level App (git) TOP
+ |
+ -----------------------------------------
+ / | \ \
+ clone push add commit LEVEL 1
+ | / \ / \ |
+ url origin remote ref name message LEVEL 2
+ / /\
+ path remote local LEVEL 3
+
+Given the above fictional subcommand hierarchy, valid runtime uses would be (not an all +inclusive list, and not including argument options per command for brevity and clarity):
+$ git clone url
+$ git push origin path
+$ git add ref local
+$ git commit message
+
+Notice only one command per "level" may be used. You could not, for example, do $ git clone url push origin path
+ let app_m = App::new("git") + .subcommand(SubCommand::with_name("clone")) + .subcommand(SubCommand::with_name("push")) + .subcommand(SubCommand::with_name("commit")) + .get_matches(); + +match app_m.subcommand_name() { + Some("clone") => {}, // clone was used + Some("push") => {}, // push was used + Some("commit") => {}, // commit was used + _ => {}, // Either no subcommand or one not tested for... +}
pub fn subcommand(&self) -> (&str, Option<&ArgMatches<'a>>)
[src]This brings together ArgMatches::subcommand_matches
and ArgMatches::subcommand_name
+by returning a tuple with both pieces of information.
+ let app_m = App::new("git") + .subcommand(SubCommand::with_name("clone")) + .subcommand(SubCommand::with_name("push")) + .subcommand(SubCommand::with_name("commit")) + .get_matches(); + +match app_m.subcommand() { + ("clone", Some(sub_m)) => {}, // clone was used + ("push", Some(sub_m)) => {}, // push was used + ("commit", Some(sub_m)) => {}, // commit was used + _ => {}, // Either no subcommand or one not tested for... +}
Another useful scenario is when you want to support third party, or external, subcommands. +In these cases you can't know the subcommand name ahead of time, so use a variable instead +with pattern matching!
+ ++// Assume there is an external subcommand named "subcmd" +let app_m = App::new("myprog") + .setting(AppSettings::AllowExternalSubcommands) + .get_matches_from(vec![ + "myprog", "subcmd", "--option", "value", "-fff", "--flag" + ]); + +// All trailing arguments will be stored under the subcommand's sub-matches using an empty +// string argument name +match app_m.subcommand() { + (external, Some(sub_m)) => { + let ext_args: Vec<&str> = sub_m.values_of("").unwrap().collect(); + assert_eq!(external, "subcmd"); + assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); + }, + _ => {}, +}
pub fn usage(&self) -> &str
[src]Returns a string slice of the usage statement for the App
or SubCommand
+let app_m = App::new("myprog") + .subcommand(SubCommand::with_name("test")) + .get_matches(); + +println!("{}", app_m.usage());
impl<'a> Clone for ArgMatches<'a>
[src]fn clone(&self) -> ArgMatches<'a>
[src]fn clone_from(&mut self, source: &Self)
1.0.0[src]impl<'a> Debug for ArgMatches<'a>
[src]impl<'a> Default for ArgMatches<'a>
[src]impl<'a> RefUnwindSafe for ArgMatches<'a>
impl<'a> Send for ArgMatches<'a>
impl<'a> Sync for ArgMatches<'a>
impl<'a> Unpin for ArgMatches<'a>
impl<'a> UnwindSafe for ArgMatches<'a>
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<T> ToOwned for T where
T: Clone,
[src]type Owned = T
The resulting type after obtaining ownership.
+fn to_owned(&self) -> T
[src]fn clone_into(&self, target: &mut T)
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]Command Line Argument Parser Error
+message: String
Formatted error message
+kind: ErrorKind
The type of error
+info: Option<Vec<String>>
Any additional information passed along, such as the argument name that caused the error
+impl Error
[src]pub fn use_stderr(&self) -> bool
[src]Should the message be written to stdout
or not
pub fn exit(&self) -> !
[src]Prints the error to stderr
and exits with a status of 1
pub fn with_description(description: &str, kind: ErrorKind) -> Self
[src]Create an error with a custom description.
+This can be used in combination with Error::exit
to exit your program
+with a custom error message.
impl Debug for Error
[src]impl Display for Error
[src]impl Error for Error
[src]fn description(&self) -> &str
[src]fn source(&self) -> Option<&(dyn Error + 'static)>
1.30.0[src]fn backtrace(&self) -> Option<&Backtrace>
[src]fn cause(&self) -> Option<&dyn Error>
1.0.0[src]impl From<Error> for Error
[src]impl From<Error> for Error
[src]impl RefUnwindSafe for Error
impl Send for Error
impl Sync for Error
impl Unpin for Error
impl UnwindSafe for Error
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<T> ToString for T where
T: Display + ?Sized,
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]An iterator for getting multiple values out of an argument via the ArgMatches::values_of_os
+method. Usage of this iterator allows values which contain invalid UTF-8 code points unlike
+Values
.
+use std::ffi::OsString; +use std::os::unix::ffi::{OsStrExt,OsStringExt}; + +let m = App::new("utf8") + .arg(Arg::from_usage("<arg> 'some arg'")) + .get_matches_from(vec![OsString::from("myprog"), + // "Hi {0xe9}!" + OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); +assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']);
impl<'a> Clone for OsValues<'a>
[src]impl<'a> Debug for OsValues<'a>
[src]impl<'a> Default for OsValues<'a>
[src]Creates an empty iterator.
+impl<'a> DoubleEndedIterator for OsValues<'a>
[src]fn next_back(&mut self) -> Option<&'a OsStr>
[src]fn nth_back(&mut self, n: usize) -> Option<Self::Item>
1.37.0[src]fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R where
F: FnMut(B, Self::Item) -> R,
R: Try<Ok = B>,
1.27.0[src]fn rfold<B, F>(self, init: B, f: F) -> B where
F: FnMut(B, Self::Item) -> B,
1.27.0[src]fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item> where
P: FnMut(&Self::Item) -> bool,
1.27.0[src]impl<'a> ExactSizeIterator for OsValues<'a>
[src]impl<'a> Iterator for OsValues<'a>
[src]type Item = &'a OsStr
The type of the elements being iterated over.
+fn next(&mut self) -> Option<&'a OsStr>
[src]fn size_hint(&self) -> (usize, Option<usize>)
[src]fn count(self) -> usize
1.0.0[src]fn last(self) -> Option<Self::Item>
1.0.0[src]fn nth(&mut self, n: usize) -> Option<Self::Item>
1.0.0[src]fn step_by(self, step: usize) -> StepBy<Self>
1.28.0[src]fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter> where
U: IntoIterator<Item = Self::Item>,
1.0.0[src]fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter> where
U: IntoIterator,
1.0.0[src]fn map<B, F>(self, f: F) -> Map<Self, F> where
F: FnMut(Self::Item) -> B,
1.0.0[src]fn for_each<F>(self, f: F) where
F: FnMut(Self::Item),
1.21.0[src]fn filter<P>(self, predicate: P) -> Filter<Self, P> where
P: FnMut(&Self::Item) -> bool,
1.0.0[src]fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
F: FnMut(Self::Item) -> Option<B>,
1.0.0[src]fn enumerate(self) -> Enumerate<Self>
1.0.0[src]fn peekable(self) -> Peekable<Self>
1.0.0[src]fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
P: FnMut(&Self::Item) -> bool,
1.0.0[src]fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
P: FnMut(&Self::Item) -> bool,
1.0.0[src]fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P> where
P: FnMut(Self::Item) -> Option<B>,
[src]fn skip(self, n: usize) -> Skip<Self>
1.0.0[src]fn take(self, n: usize) -> Take<Self>
1.0.0[src]fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F> where
F: FnMut(&mut St, Self::Item) -> Option<B>,
1.0.0[src]fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F> where
F: FnMut(Self::Item) -> U,
U: IntoIterator,
1.0.0[src]fn flatten(self) -> Flatten<Self> where
Self::Item: IntoIterator,
1.29.0[src]fn fuse(self) -> Fuse<Self>
1.0.0[src]fn inspect<F>(self, f: F) -> Inspect<Self, F> where
F: FnMut(&Self::Item),
1.0.0[src]fn by_ref(&mut self) -> &mut Self
1.0.0[src]#[must_use =
+ "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]fn collect<B>(self) -> B where
B: FromIterator<Self::Item>,
1.0.0[src]fn partition<B, F>(self, f: F) -> (B, B) where
B: Default + Extend<Self::Item>,
F: FnMut(&Self::Item) -> bool,
1.0.0[src]fn partition_in_place<'a, T, P>(self, predicate: P) -> usize where
P: FnMut(&T) -> bool,
Self: DoubleEndedIterator<Item = &'a mut T>,
T: 'a,
[src]fn is_partitioned<P>(self, predicate: P) -> bool where
P: FnMut(Self::Item) -> bool,
[src]fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R where
F: FnMut(B, Self::Item) -> R,
R: Try<Ok = B>,
1.27.0[src]fn try_for_each<F, R>(&mut self, f: F) -> R where
F: FnMut(Self::Item) -> R,
R: Try<Ok = ()>,
1.27.0[src]fn fold<B, F>(self, init: B, f: F) -> B where
F: FnMut(B, Self::Item) -> B,
1.0.0[src]fn fold_first<F>(self, f: F) -> Option<Self::Item> where
F: FnMut(Self::Item, Self::Item) -> Self::Item,
[src]fn all<F>(&mut self, f: F) -> bool where
F: FnMut(Self::Item) -> bool,
1.0.0[src]fn any<F>(&mut self, f: F) -> bool where
F: FnMut(Self::Item) -> bool,
1.0.0[src]fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where
P: FnMut(&Self::Item) -> bool,
1.0.0[src]fn find_map<B, F>(&mut self, f: F) -> Option<B> where
F: FnMut(Self::Item) -> Option<B>,
1.30.0[src]fn try_find<F, R>(
&mut self,
f: F
) -> Result<Option<Self::Item>, <R as Try>::Error> where
F: FnMut(&Self::Item) -> R,
R: Try<Ok = bool>,
[src]fn position<P>(&mut self, predicate: P) -> Option<usize> where
P: FnMut(Self::Item) -> bool,
1.0.0[src]fn rposition<P>(&mut self, predicate: P) -> Option<usize> where
P: FnMut(Self::Item) -> bool,
Self: ExactSizeIterator + DoubleEndedIterator,
1.0.0[src]fn max(self) -> Option<Self::Item> where
Self::Item: Ord,
1.0.0[src]fn min(self) -> Option<Self::Item> where
Self::Item: Ord,
1.0.0[src]fn max_by_key<B, F>(self, f: F) -> Option<Self::Item> where
B: Ord,
F: FnMut(&Self::Item) -> B,
1.6.0[src]fn max_by<F>(self, compare: F) -> Option<Self::Item> where
F: FnMut(&Self::Item, &Self::Item) -> Ordering,
1.15.0[src]fn min_by_key<B, F>(self, f: F) -> Option<Self::Item> where
B: Ord,
F: FnMut(&Self::Item) -> B,
1.6.0[src]fn min_by<F>(self, compare: F) -> Option<Self::Item> where
F: FnMut(&Self::Item, &Self::Item) -> Ordering,
1.15.0[src]fn rev(self) -> Rev<Self> where
Self: DoubleEndedIterator,
1.0.0[src]fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
FromA: Default + Extend<A>,
FromB: Default + Extend<B>,
Self: Iterator<Item = (A, B)>,
1.0.0[src]fn copied<'a, T>(self) -> Copied<Self> where
Self: Iterator<Item = &'a T>,
T: 'a + Copy,
1.36.0[src]fn cloned<'a, T>(self) -> Cloned<Self> where
Self: Iterator<Item = &'a T>,
T: 'a + Clone,
1.0.0[src]fn cycle(self) -> Cycle<Self> where
Self: Clone,
1.0.0[src]fn sum<S>(self) -> S where
S: Sum<Self::Item>,
1.11.0[src]fn product<P>(self) -> P where
P: Product<Self::Item>,
1.11.0[src]fn cmp<I>(self, other: I) -> Ordering where
I: IntoIterator<Item = Self::Item>,
Self::Item: Ord,
1.5.0[src]fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering where
F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering,
I: IntoIterator,
[src]fn partial_cmp<I>(self, other: I) -> Option<Ordering> where
I: IntoIterator,
Self::Item: PartialOrd<<I as IntoIterator>::Item>,
1.5.0[src]fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering> where
F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering>,
I: IntoIterator,
[src]fn eq<I>(self, other: I) -> bool where
I: IntoIterator,
Self::Item: PartialEq<<I as IntoIterator>::Item>,
1.5.0[src]fn eq_by<I, F>(self, other: I, eq: F) -> bool where
F: FnMut(Self::Item, <I as IntoIterator>::Item) -> bool,
I: IntoIterator,
[src]fn ne<I>(self, other: I) -> bool where
I: IntoIterator,
Self::Item: PartialEq<<I as IntoIterator>::Item>,
1.5.0[src]fn lt<I>(self, other: I) -> bool where
I: IntoIterator,
Self::Item: PartialOrd<<I as IntoIterator>::Item>,
1.5.0[src]fn le<I>(self, other: I) -> bool where
I: IntoIterator,
Self::Item: PartialOrd<<I as IntoIterator>::Item>,
1.5.0[src]fn gt<I>(self, other: I) -> bool where
I: IntoIterator,
Self::Item: PartialOrd<<I as IntoIterator>::Item>,
1.5.0[src]fn ge<I>(self, other: I) -> bool where
I: IntoIterator,
Self::Item: PartialOrd<<I as IntoIterator>::Item>,
1.5.0[src]fn is_sorted(self) -> bool where
Self::Item: PartialOrd<Self::Item>,
[src]fn is_sorted_by<F>(self, compare: F) -> bool where
F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
[src]fn is_sorted_by_key<F, K>(self, f: F) -> bool where
F: FnMut(Self::Item) -> K,
K: PartialOrd<K>,
[src]impl<'a> RefUnwindSafe for OsValues<'a>
impl<'a> Send for OsValues<'a>
impl<'a> Sync for OsValues<'a>
impl<'a> Unpin for OsValues<'a>
impl<'a> UnwindSafe for OsValues<'a>
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<I> IntoIterator for I where
I: Iterator,
[src]type Item = <I as Iterator>::Item
The type of the elements being iterated over.
+type IntoIter = I
Which kind of iterator are we turning this into?
+fn into_iter(self) -> I
[src]impl<T> ToOwned for T where
T: Clone,
[src]type Owned = T
The resulting type after obtaining ownership.
+fn to_owned(&self) -> T
[src]fn clone_into(&self, target: &mut T)
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]The abstract representation of a command line subcommand.
+This struct describes all the valid options of the subcommand for the program. Subcommands are
+essentially "sub-App
s" and contain all the same possibilities (such as their own
+arguments, subcommands, and settings).
+App::new("myprog") + .subcommand( + SubCommand::with_name("config") + .about("Used for configuration") + .arg(Arg::with_name("config_file") + .help("The configuration file to use") + .index(1)))
impl<'a> SubCommand<'a>
[src]pub fn with_name<'b>(name: &str) -> App<'a, 'b>
[src]Creates a new instance of a subcommand requiring a name. The name will be displayed +to the user when they print version or help and usage information.
++App::new("myprog") + .subcommand( + SubCommand::with_name("config"))
pub fn from_yaml(yaml: &Yaml) -> App
[src]Creates a new instance of a subcommand from a YAML (.yml) document
++let sc_yaml = load_yaml!("test_subcommand.yml"); +let sc = SubCommand::from_yaml(sc_yaml);
impl<'a> Clone for SubCommand<'a>
[src]fn clone(&self) -> SubCommand<'a>
[src]fn clone_from(&mut self, source: &Self)
1.0.0[src]impl<'a> Debug for SubCommand<'a>
[src]impl<'a> RefUnwindSafe for SubCommand<'a>
impl<'a> Send for SubCommand<'a>
impl<'a> Sync for SubCommand<'a>
impl<'a> Unpin for SubCommand<'a>
impl<'a> UnwindSafe for SubCommand<'a>
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<T> ToOwned for T where
T: Clone,
[src]type Owned = T
The resulting type after obtaining ownership.
+fn to_owned(&self) -> T
[src]fn clone_into(&self, target: &mut T)
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]An iterator for getting multiple values out of an argument via the ArgMatches::values_of
+method.
+let m = App::new("myapp") + .arg(Arg::with_name("output") + .short("o") + .multiple(true) + .takes_value(true)) + .get_matches_from(vec!["myapp", "-o", "val1", "val2"]); + +let mut values = m.values_of("output").unwrap(); + +assert_eq!(values.next(), Some("val1")); +assert_eq!(values.next(), Some("val2")); +assert_eq!(values.next(), None);
impl<'a> Clone for Values<'a>
[src]impl<'a> Debug for Values<'a>
[src]impl<'a> Default for Values<'a>
[src]Creates an empty iterator.
+impl<'a> DoubleEndedIterator for Values<'a>
[src]fn next_back(&mut self) -> Option<&'a str>
[src]fn nth_back(&mut self, n: usize) -> Option<Self::Item>
1.37.0[src]fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R where
F: FnMut(B, Self::Item) -> R,
R: Try<Ok = B>,
1.27.0[src]fn rfold<B, F>(self, init: B, f: F) -> B where
F: FnMut(B, Self::Item) -> B,
1.27.0[src]fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item> where
P: FnMut(&Self::Item) -> bool,
1.27.0[src]impl<'a> ExactSizeIterator for Values<'a>
[src]impl<'a> Iterator for Values<'a>
[src]type Item = &'a str
The type of the elements being iterated over.
+fn next(&mut self) -> Option<&'a str>
[src]fn size_hint(&self) -> (usize, Option<usize>)
[src]fn count(self) -> usize
1.0.0[src]fn last(self) -> Option<Self::Item>
1.0.0[src]fn nth(&mut self, n: usize) -> Option<Self::Item>
1.0.0[src]fn step_by(self, step: usize) -> StepBy<Self>
1.28.0[src]fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter> where
U: IntoIterator<Item = Self::Item>,
1.0.0[src]fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter> where
U: IntoIterator,
1.0.0[src]fn map<B, F>(self, f: F) -> Map<Self, F> where
F: FnMut(Self::Item) -> B,
1.0.0[src]fn for_each<F>(self, f: F) where
F: FnMut(Self::Item),
1.21.0[src]fn filter<P>(self, predicate: P) -> Filter<Self, P> where
P: FnMut(&Self::Item) -> bool,
1.0.0[src]fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
F: FnMut(Self::Item) -> Option<B>,
1.0.0[src]fn enumerate(self) -> Enumerate<Self>
1.0.0[src]fn peekable(self) -> Peekable<Self>
1.0.0[src]fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
P: FnMut(&Self::Item) -> bool,
1.0.0[src]fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
P: FnMut(&Self::Item) -> bool,
1.0.0[src]fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P> where
P: FnMut(Self::Item) -> Option<B>,
[src]fn skip(self, n: usize) -> Skip<Self>
1.0.0[src]fn take(self, n: usize) -> Take<Self>
1.0.0[src]fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F> where
F: FnMut(&mut St, Self::Item) -> Option<B>,
1.0.0[src]fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F> where
F: FnMut(Self::Item) -> U,
U: IntoIterator,
1.0.0[src]fn flatten(self) -> Flatten<Self> where
Self::Item: IntoIterator,
1.29.0[src]fn fuse(self) -> Fuse<Self>
1.0.0[src]fn inspect<F>(self, f: F) -> Inspect<Self, F> where
F: FnMut(&Self::Item),
1.0.0[src]fn by_ref(&mut self) -> &mut Self
1.0.0[src]#[must_use =
+ "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]fn collect<B>(self) -> B where
B: FromIterator<Self::Item>,
1.0.0[src]fn partition<B, F>(self, f: F) -> (B, B) where
B: Default + Extend<Self::Item>,
F: FnMut(&Self::Item) -> bool,
1.0.0[src]fn partition_in_place<'a, T, P>(self, predicate: P) -> usize where
P: FnMut(&T) -> bool,
Self: DoubleEndedIterator<Item = &'a mut T>,
T: 'a,
[src]fn is_partitioned<P>(self, predicate: P) -> bool where
P: FnMut(Self::Item) -> bool,
[src]fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R where
F: FnMut(B, Self::Item) -> R,
R: Try<Ok = B>,
1.27.0[src]fn try_for_each<F, R>(&mut self, f: F) -> R where
F: FnMut(Self::Item) -> R,
R: Try<Ok = ()>,
1.27.0[src]fn fold<B, F>(self, init: B, f: F) -> B where
F: FnMut(B, Self::Item) -> B,
1.0.0[src]fn fold_first<F>(self, f: F) -> Option<Self::Item> where
F: FnMut(Self::Item, Self::Item) -> Self::Item,
[src]fn all<F>(&mut self, f: F) -> bool where
F: FnMut(Self::Item) -> bool,
1.0.0[src]fn any<F>(&mut self, f: F) -> bool where
F: FnMut(Self::Item) -> bool,
1.0.0[src]fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where
P: FnMut(&Self::Item) -> bool,
1.0.0[src]fn find_map<B, F>(&mut self, f: F) -> Option<B> where
F: FnMut(Self::Item) -> Option<B>,
1.30.0[src]fn try_find<F, R>(
&mut self,
f: F
) -> Result<Option<Self::Item>, <R as Try>::Error> where
F: FnMut(&Self::Item) -> R,
R: Try<Ok = bool>,
[src]fn position<P>(&mut self, predicate: P) -> Option<usize> where
P: FnMut(Self::Item) -> bool,
1.0.0[src]fn rposition<P>(&mut self, predicate: P) -> Option<usize> where
P: FnMut(Self::Item) -> bool,
Self: ExactSizeIterator + DoubleEndedIterator,
1.0.0[src]fn max(self) -> Option<Self::Item> where
Self::Item: Ord,
1.0.0[src]fn min(self) -> Option<Self::Item> where
Self::Item: Ord,
1.0.0[src]fn max_by_key<B, F>(self, f: F) -> Option<Self::Item> where
B: Ord,
F: FnMut(&Self::Item) -> B,
1.6.0[src]fn max_by<F>(self, compare: F) -> Option<Self::Item> where
F: FnMut(&Self::Item, &Self::Item) -> Ordering,
1.15.0[src]fn min_by_key<B, F>(self, f: F) -> Option<Self::Item> where
B: Ord,
F: FnMut(&Self::Item) -> B,
1.6.0[src]fn min_by<F>(self, compare: F) -> Option<Self::Item> where
F: FnMut(&Self::Item, &Self::Item) -> Ordering,
1.15.0[src]fn rev(self) -> Rev<Self> where
Self: DoubleEndedIterator,
1.0.0[src]fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
FromA: Default + Extend<A>,
FromB: Default + Extend<B>,
Self: Iterator<Item = (A, B)>,
1.0.0[src]fn copied<'a, T>(self) -> Copied<Self> where
Self: Iterator<Item = &'a T>,
T: 'a + Copy,
1.36.0[src]fn cloned<'a, T>(self) -> Cloned<Self> where
Self: Iterator<Item = &'a T>,
T: 'a + Clone,
1.0.0[src]fn cycle(self) -> Cycle<Self> where
Self: Clone,
1.0.0[src]fn sum<S>(self) -> S where
S: Sum<Self::Item>,
1.11.0[src]fn product<P>(self) -> P where
P: Product<Self::Item>,
1.11.0[src]fn cmp<I>(self, other: I) -> Ordering where
I: IntoIterator<Item = Self::Item>,
Self::Item: Ord,
1.5.0[src]fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering where
F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering,
I: IntoIterator,
[src]fn partial_cmp<I>(self, other: I) -> Option<Ordering> where
I: IntoIterator,
Self::Item: PartialOrd<<I as IntoIterator>::Item>,
1.5.0[src]fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering> where
F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering>,
I: IntoIterator,
[src]fn eq<I>(self, other: I) -> bool where
I: IntoIterator,
Self::Item: PartialEq<<I as IntoIterator>::Item>,
1.5.0[src]fn eq_by<I, F>(self, other: I, eq: F) -> bool where
F: FnMut(Self::Item, <I as IntoIterator>::Item) -> bool,
I: IntoIterator,
[src]fn ne<I>(self, other: I) -> bool where
I: IntoIterator,
Self::Item: PartialEq<<I as IntoIterator>::Item>,
1.5.0[src]fn lt<I>(self, other: I) -> bool where
I: IntoIterator,
Self::Item: PartialOrd<<I as IntoIterator>::Item>,
1.5.0[src]fn le<I>(self, other: I) -> bool where
I: IntoIterator,
Self::Item: PartialOrd<<I as IntoIterator>::Item>,
1.5.0[src]fn gt<I>(self, other: I) -> bool where
I: IntoIterator,
Self::Item: PartialOrd<<I as IntoIterator>::Item>,
1.5.0[src]fn ge<I>(self, other: I) -> bool where
I: IntoIterator,
Self::Item: PartialOrd<<I as IntoIterator>::Item>,
1.5.0[src]fn is_sorted(self) -> bool where
Self::Item: PartialOrd<Self::Item>,
[src]fn is_sorted_by<F>(self, compare: F) -> bool where
F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
[src]fn is_sorted_by_key<F, K>(self, f: F) -> bool where
F: FnMut(Self::Item) -> K,
K: PartialOrd<K>,
[src]impl<'a> RefUnwindSafe for Values<'a>
impl<'a> Send for Values<'a>
impl<'a> Sync for Values<'a>
impl<'a> Unpin for Values<'a>
impl<'a> UnwindSafe for Values<'a>
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<I> IntoIterator for I where
I: Iterator,
[src]type Item = <I as Iterator>::Item
The type of the elements being iterated over.
+type IntoIter = I
Which kind of iterator are we turning this into?
+fn into_iter(self) -> I
[src]impl<T> ToOwned for T where
T: Clone,
[src]type Owned = T
The resulting type after obtaining ownership.
+fn to_owned(&self) -> T
[src]fn clone_into(&self, target: &mut T)
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]impl YamlLoader
[src]impl MarkedEventReceiver for YamlLoader
[src]impl RefUnwindSafe for YamlLoader
impl Send for YamlLoader
impl Sync for YamlLoader
impl Unpin for YamlLoader
impl UnwindSafe for YamlLoader
impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]fn borrow_mut(&mut self) -> &mut T
[src]impl<T> From<T> for T
[src]impl<T, U> Into<U> for T where
U: From<T>,
[src]impl<R> MarkedEventReceiver for R where
R: EventReceiver,
[src]impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]type Error = Infallible
The type returned in the event of a conversion error.
+fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]type Result<T> = StdResult<T, Error>;
Short hand for Result
type