clap::builder

Struct ValueParser

Source
pub struct ValueParser(/* private fields */);
Expand description

Parse/validate argument values

Specified with Arg::value_parser.

ValueParser defines how to convert a raw argument value into a validated and typed value for use within an application.

See

§Example

let mut cmd = clap::Command::new("raw")
    .arg(
        clap::Arg::new("color")
            .long("color")
            .value_parser(["always", "auto", "never"])
            .default_value("auto")
    )
    .arg(
        clap::Arg::new("hostname")
            .long("hostname")
            .value_parser(clap::builder::NonEmptyStringValueParser::new())
            .action(clap::ArgAction::Set)
            .required(true)
    )
    .arg(
        clap::Arg::new("port")
            .long("port")
            .value_parser(clap::value_parser!(u16).range(3000..))
            .action(clap::ArgAction::Set)
            .required(true)
    );

let m = cmd.try_get_matches_from_mut(
    ["cmd", "--hostname", "rust-lang.org", "--port", "3001"]
).unwrap();

let color: &String = m.get_one("color")
    .expect("default");
assert_eq!(color, "auto");

let hostname: &String = m.get_one("hostname")
    .expect("required");
assert_eq!(hostname, "rust-lang.org");

let port: u16 = *m.get_one("port")
    .expect("required");
assert_eq!(port, 3001);

Implementations§

Source§

impl ValueParser

Source

pub fn new<P>(other: P) -> ValueParser

Custom parser for argument values

Pre-existing TypedValueParser implementations include:

§Example
type EnvVar = (String, Option<String>);
fn parse_env_var(env: &str) -> Result<EnvVar, std::io::Error> {
    if let Some((var, value)) = env.split_once('=') {
        Ok((var.to_owned(), Some(value.to_owned())))
    } else {
        Ok((env.to_owned(), None))
    }
}

let mut cmd = clap::Command::new("raw")
    .arg(
        clap::Arg::new("env")
            .value_parser(clap::builder::ValueParser::new(parse_env_var))
            .required(true)
    );

let m = cmd.try_get_matches_from_mut(["cmd", "key=value"]).unwrap();
let port: &EnvVar = m.get_one("env")
    .expect("required");
assert_eq!(*port, ("key".into(), Some("value".into())));
Source

pub const fn bool() -> ValueParser

bool parser for argument values

See also:

§Example
let mut cmd = clap::Command::new("raw")
    .arg(
        clap::Arg::new("download")
            .value_parser(clap::value_parser!(bool))
            .required(true)
    );

let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap();
let port: bool = *m.get_one("download")
    .expect("required");
assert_eq!(port, true);

assert!(cmd.try_get_matches_from_mut(["cmd", "forever"]).is_err());
Source

pub const fn string() -> ValueParser

String parser for argument values

See also:

§Example
let mut cmd = clap::Command::new("raw")
    .arg(
        clap::Arg::new("port")
            .value_parser(clap::value_parser!(String))
            .required(true)
    );

let m = cmd.try_get_matches_from_mut(["cmd", "80"]).unwrap();
let port: &String = m.get_one("port")
    .expect("required");
assert_eq!(port, "80");
Source

pub const fn os_string() -> ValueParser

OsString parser for argument values

§Example
use std::ffi::OsString;
use std::os::unix::ffi::{OsStrExt,OsStringExt};
let r = Command::new("myprog")
    .arg(
        Arg::new("arg")
        .required(true)
        .value_parser(ValueParser::os_string())
    )
    .try_get_matches_from(vec![
        OsString::from("myprog"),
        OsString::from_vec(vec![0xe9])
    ]);

assert!(r.is_ok());
let m = r.unwrap();
let arg: &OsString = m.get_one("arg")
    .expect("required");
assert_eq!(arg.as_bytes(), &[0xe9]);
Source

pub const fn path_buf() -> ValueParser

PathBuf parser for argument values

§Example
let mut cmd = clap::Command::new("raw")
    .arg(
        clap::Arg::new("output")
            .value_parser(clap::value_parser!(PathBuf))
            .required(true)
    );

let m = cmd.try_get_matches_from_mut(["cmd", "hello.txt"]).unwrap();
let port: &PathBuf = m.get_one("output")
    .expect("required");
assert_eq!(port, Path::new("hello.txt"));

assert!(cmd.try_get_matches_from_mut(["cmd", ""]).is_err());
Source§

impl ValueParser

Source

pub fn type_id(&self) -> AnyValueId

Describes the content of AnyValue

Source

pub fn possible_values( &self, ) -> Option<Box<dyn Iterator<Item = PossibleValue> + '_>>

Reflect on enumerated value properties

Error checking should not be done with this; it is mostly targeted at user-facing applications like errors and completion.

Trait Implementations§

Source§

impl Clone for ValueParser

Source§

fn clone(&self) -> ValueParser

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ValueParser

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<P, const C: usize> From<[P; C]> for ValueParser
where P: Into<PossibleValue>,

Create a ValueParser with PossibleValuesParser

See PossibleValuesParser for more flexibility in creating the PossibleValues.

§Examples

let mut cmd = clap::Command::new("raw")
    .arg(
        clap::Arg::new("color")
            .long("color")
            .value_parser(["always", "auto", "never"])
            .default_value("auto")
    );

let m = cmd.try_get_matches_from_mut(
    ["cmd", "--color", "never"]
).unwrap();

let color: &String = m.get_one("color")
    .expect("default");
assert_eq!(color, "never");
Source§

fn from(values: [P; C]) -> ValueParser

Converts to this type from the input type.
Source§

impl<P> From<P> for ValueParser
where P: TypedValueParser + Send + Sync + 'static,

Convert a TypedValueParser to ValueParser

§Example

let mut cmd = clap::Command::new("raw")
    .arg(
        clap::Arg::new("hostname")
            .long("hostname")
            .value_parser(clap::builder::NonEmptyStringValueParser::new())
            .action(clap::ArgAction::Set)
            .required(true)
    );

let m = cmd.try_get_matches_from_mut(
    ["cmd", "--hostname", "rust-lang.org"]
).unwrap();

let hostname: &String = m.get_one("hostname")
    .expect("required");
assert_eq!(hostname, "rust-lang.org");
Source§

fn from(p: P) -> ValueParser

Converts to this type from the input type.
Source§

impl From<Range<i64>> for ValueParser

Create an i64 ValueParser from a N..M range

See RangedI64ValueParser for more control over the output type.

See also RangedU64ValueParser

§Examples

let mut cmd = clap::Command::new("raw")
    .arg(
        clap::Arg::new("port")
            .long("port")
            .value_parser(3000..4000)
            .action(clap::ArgAction::Set)
            .required(true)
    );

let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
let port: i64 = *m.get_one("port")
    .expect("required");
assert_eq!(port, 3001);
Source§

fn from(value: Range<i64>) -> ValueParser

Converts to this type from the input type.
Source§

impl From<RangeFrom<i64>> for ValueParser

Create an i64 ValueParser from a N.. range

See RangedI64ValueParser for more control over the output type.

See also RangedU64ValueParser

§Examples

let mut cmd = clap::Command::new("raw")
    .arg(
        clap::Arg::new("port")
            .long("port")
            .value_parser(3000..)
            .action(clap::ArgAction::Set)
            .required(true)
    );

let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
let port: i64 = *m.get_one("port")
    .expect("required");
assert_eq!(port, 3001);
Source§

fn from(value: RangeFrom<i64>) -> ValueParser

Converts to this type from the input type.
Source§

impl From<RangeFull> for ValueParser

Create an i64 ValueParser from a .. range

See RangedI64ValueParser for more control over the output type.

See also RangedU64ValueParser

§Examples

let mut cmd = clap::Command::new("raw")
    .arg(
        clap::Arg::new("port")
            .long("port")
            .value_parser(..)
            .action(clap::ArgAction::Set)
            .required(true)
    );

let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
let port: i64 = *m.get_one("port")
    .expect("required");
assert_eq!(port, 3001);
Source§

fn from(value: RangeFull) -> ValueParser

Converts to this type from the input type.
Source§

impl From<RangeInclusive<i64>> for ValueParser

Create an i64 ValueParser from a N..=M range

See RangedI64ValueParser for more control over the output type.

See also RangedU64ValueParser

§Examples

let mut cmd = clap::Command::new("raw")
    .arg(
        clap::Arg::new("port")
            .long("port")
            .value_parser(3000..=4000)
            .action(clap::ArgAction::Set)
            .required(true)
    );

let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
let port: i64 = *m.get_one("port")
    .expect("required");
assert_eq!(port, 3001);
Source§

fn from(value: RangeInclusive<i64>) -> ValueParser

Converts to this type from the input type.
Source§

impl From<RangeTo<i64>> for ValueParser

Create an i64 ValueParser from a ..M range

See RangedI64ValueParser for more control over the output type.

See also RangedU64ValueParser

§Examples

let mut cmd = clap::Command::new("raw")
    .arg(
        clap::Arg::new("port")
            .long("port")
            .value_parser(..3000)
            .action(clap::ArgAction::Set)
            .required(true)
    );

let m = cmd.try_get_matches_from_mut(["cmd", "--port", "80"]).unwrap();
let port: i64 = *m.get_one("port")
    .expect("required");
assert_eq!(port, 80);
Source§

fn from(value: RangeTo<i64>) -> ValueParser

Converts to this type from the input type.
Source§

impl From<RangeToInclusive<i64>> for ValueParser

Create an i64 ValueParser from a ..=M range

See RangedI64ValueParser for more control over the output type.

See also RangedU64ValueParser

§Examples

let mut cmd = clap::Command::new("raw")
    .arg(
        clap::Arg::new("port")
            .long("port")
            .value_parser(..=3000)
            .action(clap::ArgAction::Set)
            .required(true)
    );

let m = cmd.try_get_matches_from_mut(["cmd", "--port", "80"]).unwrap();
let port: i64 = *m.get_one("port")
    .expect("required");
assert_eq!(port, 80);
Source§

fn from(value: RangeToInclusive<i64>) -> ValueParser

Converts to this type from the input type.
Source§

impl<P> From<Vec<P>> for ValueParser
where P: Into<PossibleValue>,

Create a ValueParser with PossibleValuesParser

See PossibleValuesParser for more flexibility in creating the PossibleValues.

§Examples

let possible = vec!["always", "auto", "never"];
let mut cmd = clap::Command::new("raw")
    .arg(
        clap::Arg::new("color")
            .long("color")
            .value_parser(possible)
            .default_value("auto")
    );

let m = cmd.try_get_matches_from_mut(
    ["cmd", "--color", "never"]
).unwrap();

let color: &String = m.get_one("color")
    .expect("default");
assert_eq!(color, "never");
Source§

fn from(values: Vec<P>) -> ValueParser

Converts to this type from the input type.
Source§

impl IntoResettable<ValueParser> for Option<ValueParser>

Source§

fn into_resettable(self) -> Resettable<ValueParser>

Convert to the intended resettable type

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<I> IntoResettable<ValueParser> for I
where I: Into<ValueParser>,

Source§

fn into_resettable(self) -> Resettable<ValueParser>

Convert to the intended resettable type
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.

Layout§

Note: Most layout information is completely unstable and may even differ between compilations. The only exception is types with certain repr(...) attributes. Please see the Rust Reference's “Type Layout” chapter for details on type layout guarantees.

Size: 24 bytes