Struct ValueParser

pub struct ValueParser(/* private field */);

Parse/validate argument values

Specified with [Arg::value_parser][crate::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

# use clap_builder as clap;
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

impl ValueParser

fn new<P>(other: P) -> Self
where
    P: TypedValueParser,

Custom parser for argument values

Pre-existing TypedValueParser implementations include:

Example

# use clap_builder as clap;
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())));
const fn bool() -> Self

bool parser for argument values

See also:

Example

# use clap_builder as clap;
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());
const fn string() -> Self

String parser for argument values

See also:

Example

# use clap_builder as clap;
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");
const fn os_string() -> Self

[OsString][std::ffi::OsString] parser for argument values

Example

# #[cfg(unix)] {
# use clap_builder as clap;
# use clap::{Command, Arg, builder::ValueParser};
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]);
# }
const fn path_buf() -> Self

[PathBuf][std::path::PathBuf] parser for argument values

Example

# use clap_builder as clap;
# use std::path::PathBuf;
# use std::path::Path;
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());

impl ValueParser

fn type_id(&self) -> AnyValueId

Describes the content of AnyValue

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

impl Clone for ValueParser

fn clone(&self) -> Self

impl Debug for ValueParser

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

impl From<Range<i64>> for ValueParser

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

impl From<RangeFrom<i64>> for ValueParser

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

impl From<RangeFull> for ValueParser

fn from(value: RangeFull) -> Self

impl From<RangeInclusive<i64>> for ValueParser

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

impl From<RangeTo<i64>> for ValueParser

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

impl From<RangeToInclusive<i64>> for ValueParser

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

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

fn from(p: P) -> Self

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

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

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

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

Auto Trait Implementations

impl !RefUnwindSafe for ValueParser

impl !UnwindSafe for ValueParser

impl Freeze for ValueParser

impl Send for ValueParser

impl Sync for ValueParser

impl Unpin for ValueParser

impl UnsafeUnpin for ValueParser

Blanket Implementations

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

fn into_resettable(self) -> Resettable<ValueParser>

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

fn type_id(&self) -> TypeId

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

fn borrow(&self) -> &T

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

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

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

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

impl<T> From<T> for ValueParser

fn from(t: T) -> T

Returns the argument unchanged.

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

type Owned = T;
fn to_owned(&self) -> T
fn clone_into(&self, target: &mut T)

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

fn into(self) -> U

Calls U::from(self).

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

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

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

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

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