Struct Argument

Source
pub struct Argument { /* private fields */ }
Expand description

Represents the arguments of an option or command.

Implementations§

Source§

impl Argument

Source

pub fn new() -> Self

Constructs a new Argument that takes 1 value.

Source

pub fn with_name<S: Into<String>>(name: S) -> Self

Constructs a new Argument with the given name that takes 1 value.

§Panics:

Panics if the argument name is empty or contains whitespaces.

§Example
use clapi::Argument;

let arg = Argument::with_name("number");
assert_eq!(arg.get_name(), "number");
Source

pub fn zero_or_one<S: Into<String>>(name: S) -> Self

Constructs a new Argument that takes 0 or 1 values.

§Panics:

Panics if the argument name is blank or empty.

Source

pub fn zero_or_more<S: Into<String>>(name: S) -> Self

Constructs a new Argument that takes 0 or more values.

§Panics:

Panics if the argument name is blank or empty.

Source

pub fn one_or_more<S: Into<String>>(name: S) -> Self

Constructs a new Argument that takes 1 or more values.

§Panics:

Panics if the argument name is blank or empty.

Source

pub fn get_name(&self) -> &str

Returns the name of this argument.

Source

pub fn get_description(&self) -> Option<&str>

Returns the description of this argument.

Source

pub fn get_values_count(&self) -> ArgCount

Returns the number of values this argument takes.

Source

pub fn get_validator(&self) -> Option<&dyn Validator>

Returns the value Validator used by this argument.

Source

pub fn get_validation_error(&self) -> Option<&str>

Returns the validation error message.

Source

pub fn get_default_values(&self) -> &[String]

Returns the default values of this argument or a 0-length slice if none.

Source

pub fn get_valid_values(&self) -> &[String]

Returns the valid values of this argument or a 0-length slice if none.

Source

pub fn get_values(&self) -> &[String]

Returns the values of this argument or a 0-length slice if none.

Source

pub fn contains<S: AsRef<str>>(&self, value: S) -> bool

Returns true if this argument contains the specified value, false otherwise.

§Example
use clapi::{Command, Argument};

let result = Command::new("MyApp")
    .arg(Argument::with_name("data"))
    .parse_from(vec!["Hello World"])
    .unwrap();

assert!(result.args().get("data").unwrap().contains("Hello World"));
Source

pub fn has_default_values(&self) -> bool

Returns true if this argument have default values.

Source

pub fn is_valid<S: AsRef<str>>(&self, value: S) -> bool

Returns true if the given value is valid for this argument.

§Example
use clapi::{Command, Argument};
use clapi::validator::validate_type;

let arg = Argument::with_name("number")
    .validator(validate_type::<i64>());

assert!(arg.is_valid("25"));        // Valid `i64` value
assert!(arg.is_valid("-20"));       // Valid `i64` value
assert!(!arg.is_valid("true"));     // Invalid `i64` value
assert!(!arg.is_valid("Hello"));    // Invalid `i64` value
Source

pub fn is_set(&self) -> bool

Returns true if this Argument contains values, or false if don’t contains values or only contains default values.

§Example
use clapi::{Command, Argument};

let result = Command::new("MyApp")
    .arg(Argument::zero_or_more("data")
        .default("Hello World"))
        .parse_from(Vec::<String>::new())
        .unwrap();

assert!(!result.arg().unwrap().is_set());
Source

pub fn values_count<A: Into<ArgCount>>(self, value_count: A) -> Self

Sets the number of values this argument takes.

§Panics

If the value is exactly 0, an argument must take from 0 to 1 values.

§Example
use clapi::{Command, Argument};

let command = Command::new("MyApp")
    .arg(Argument::with_name("numbers")
        .values_count(1..=2));

assert!(command.clone().parse_from(vec!["10"]).is_ok());
assert!(command.clone().parse_from(vec!["10", "20", "30"]).is_err());
Source

pub fn min_values(self, min: usize) -> Self

Sets the min number of values this argument takes.

§Example
use clapi::{Command, Argument};

let command = Command::new("MyApp")
    .arg(Argument::with_name("numbers")
        .min_values(1));

assert!(command.clone().parse_from(vec!["10"]).is_ok());
assert!(command.clone().parse_from(Vec::<String>::new()).is_err());
Source

pub fn max_values(self, max: usize) -> Self

Sets the max number of values this argument takes.

§Example
use clapi::{Command, Argument};

let command = Command::new("MyApp")
    .arg(Argument::with_name("numbers")
        .max_values(2));

assert!(command.clone().parse_from(vec!["10"]).is_ok());
assert!(command.clone().parse_from(vec!["10", "20", "30"]).is_err());
Source

pub fn description<S: Into<String>>(self, description: S) -> Self

Sets the description of this argument.

Source

pub fn validator<V: Validator + 'static>(self, validator: V) -> Self

Sets the value Validator of this argument.

§Panics
  • If there is already a validator.
  • If there is default values; a validator must be set before the default values.
  • If there is values.
§Examples

Using the parse_validator to ensure the value is an i64.

use clapi::{Command, Argument};
use clapi::validator::validate_type;

let command = Command::new("MyApp")
    .arg(Argument::with_name("numbers")
        .validator(validate_type::<i64>()));

assert!(command.clone().parse_from(vec!["10"]).is_ok());
assert!(command.clone().parse_from(vec!["10", "true"]).is_err());

Also you can use a closure as a validator in the form: fn(&str) -> Result<(), String>.

use clapi::{Command, Argument};
use std::str::FromStr;

let command = Command::new("MyApp")
    .arg(Argument::with_name("numbers")
        .validator(|s: &str| match i64::from_str(s) {
            Ok(v) => Ok(()),
            Err(_) => Err("expected an integer".into())
        }
    ));

assert!(command.clone().parse_from(vec!["10"]).is_ok());
assert!(command.clone().parse_from(vec!["10", "true"]).is_err());
Source

pub fn validation_error<S: Into<String>>(self, error: S) -> Self

Sets the error message returned when a value is no valid.

§Example
use clapi::{Command, Argument, Error, ErrorKind};
use clapi::validator::validate_type;
use std::num::NonZeroUsize;

let error = Command::new("MyApp")
    .arg(Argument::with_name("number")
        .validator(validate_type::<NonZeroUsize>())
        .validation_error("expected a number greater than 0"))
        .parse_from(vec!["0"])
        .err()
        .unwrap();

assert!(error.to_string().contains("invalid value for argument 'number': expected a number greater than 0"));
Source

pub fn valid_values<S, I>(self, values: I) -> Self
where S: ToString, I: IntoIterator<Item = S>,

Sets the valid values of this argument.

§Panics

If the argument contains default values. Default values must be set before the valid values.

§Example
use clapi::{Command, Argument};

let command = Command::new("MyApp")
    .arg(Argument::with_name("color")
        .valid_values(&["red", "green", "blue"]));

let result = command.clone().parse_from(vec!["green"]).unwrap();
assert!(result.arg().unwrap().contains("green"));

// Yellow is an invalid value
assert!(command.clone().parse_from(vec!["yellow"]).is_err());
Source

pub fn default<S: ToString>(self, value: S) -> Self

Sets the default value of this argument.

§Panics
  • If argument already contains values.
  • If already contains default values.
  • If the number of arguments is invalid.
§Example
use clapi::{Command, Argument};

let command = Command::new("MyApp")
    .arg(Argument::with_name("number")
        .default(0));

let result_with_value = command.clone().parse_from(vec!["10"]).unwrap();
assert!(result_with_value.arg().unwrap().contains("10"));

let result = command.clone().parse_from(Vec::<String>::new()).unwrap();
assert!(result.arg().unwrap().contains("0"));
Source

pub fn defaults<S, I>(self, values: I) -> Self
where S: ToString, I: IntoIterator<Item = S>,

Sets the default values of this argument.

§Panics
  • If argument already contains values.
  • If already contains default values.
  • If the number of arguments is invalid.
§Example
use clapi::{Command, Argument};

let command = Command::new("MyApp")
    .arg(Argument::one_or_more("numbers")
        .defaults(vec![1, 2, 3]));

let without_values = command.clone().parse_from(Vec::<String>::new()).unwrap();
assert!(without_values.arg().unwrap().contains("1"));
assert!(without_values.arg().unwrap().contains("2"));
assert!(without_values.arg().unwrap().contains("3"));

let with_values = command.clone().parse_from(vec!["10", "true"]).unwrap();
assert!(with_values.arg().unwrap().contains("10"));
assert!(with_values.arg().unwrap().contains("true"));
Source

pub fn set_values<S, I>(&mut self, values: I) -> Result<()>
where S: ToString, I: IntoIterator<Item = S>,

Sets the values of this argument.

§Example
use clapi::Argument;
use clapi::validator::validate_type;

let mut arg = Argument::with_name("number")
    .validator(validate_type::<i64>())
    .default(0);

assert!(arg.set_values(vec![2]).is_ok());
assert!(arg.set_values(vec!["hello"]).is_err());
Source

pub fn convert<T>(&self) -> Result<T>
where T: FromStr + 'static, <T as FromStr>::Err: Display,

Converts the value of this argument to a concrete type.

§Returns
  • Ok(T) : If the String value can be parse to T.
  • Err(error):
    • If the value cannot be parse.
    • if there no value to parse.
    • if there is more than 1 value.
§Example
use clapi::{Command, Argument};
use clapi::validator::validate_type;

let result = Command::new("MyApp")
    .arg(Argument::one_or_more("numbers")
        .validator(validate_type::<i64>()))
    .parse_from(vec!["10"])
    .unwrap();

assert_eq!(result.args().get("numbers").unwrap().convert::<i64>().ok(), Some(10));

// This only fails if feature `typing` is enable, otherwise the value will be converted
#[cfg(feature = "typing")]
assert!(result.args().get("numbers").unwrap().convert::<f32>().is_err());
Source

pub fn convert_all<T>(&self) -> Result<Vec<T>>
where T: FromStr + 'static, <T as FromStr>::Err: Display,

Converts the values of this argument to a concrete type.

§Returns
  • Ok(Vec<T>) : If all the values are parsed.
  • Err(error):
    • If one of the values cannot be parse.
    • if there no values to parse.
§Example
use clapi::{Command, Argument};
use clapi::validator::validate_type;

let result = Command::new("MyApp")
    .arg(Argument::one_or_more("numbers")
        .validator(validate_type::<i64>()))
    .parse_from(vec!["1", "2", "3"])
    .unwrap();

assert_eq!(result.args().get("numbers").unwrap().convert_all::<i64>().ok(), Some(vec![1, 2, 3]));

// This only fails if feature `typing` is enable, otherwise the values will be converted
#[cfg(feature = "typing")]
assert!(result.args().get("numbers").unwrap().convert_all::<f32>().is_err());

Trait Implementations§

Source§

impl Clone for Argument

Source§

fn clone(&self) -> Argument

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 Argument

Source§

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

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

impl Default for Argument

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Argument

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Hash for Argument

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<I: SliceIndex<[String]>> Index<I> for Argument

Source§

type Output = <I as SliceIndex<[String]>>::Output

The returned type after indexing.
Source§

fn index(&self, index: I) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl PartialEq for Argument

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Argument

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for Argument

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, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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<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.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,