Struct Parser

Source
pub struct Parser {
    pub command: String,
    /* private fields */
}
Expand description

The arguments parser.

Fields§

§command: String

The name of the command used in the help string.

Implementations§

Source§

impl Parser

Source

pub fn from_env() -> Self

Initializes a Parser using std::env::args as input.

Source

pub fn from_vec(args: Vec<String>) -> Self

Initializes a Parser using a given vector of strings as input.

Source

pub fn bool_flag(&mut self, flag: &str, usage: &str)

Defines a boolean flag.

§Examples
§Boolean Flag Set
use yafp::Parser;
use yafp::errors::Error;

let cmd_args: Vec<String> =
    vec!["head", "-verbose", "file.txt"]
        .iter()
        .map(|x| x.to_string())
        .collect();

let mut parser = Parser::from_vec(cmd_args);
parser.bool_flag("verbose", "this is used to get verbose output");

/// This must be called before fetching flags and returns any remaining args.
parser.finalize()?;

/// Since the verbose flag is set this returns true.
let verbose: Option<bool> = parser.get_value("verbose");
assert_eq!(Some(true), verbose);
§Boolean Flag Unset
use yafp::Parser;
use yafp::errors::Error;

let cmd_args: Vec<String> =
    vec!["head", "file.txt"]
        .iter()
        .map(|x| x.to_string())
        .collect();

let mut parser = Parser::from_vec(cmd_args);
parser.bool_flag("verbose", "this is used to get verbose output");

/// This must be called before fetching flags and returns any remaining args.
parser.finalize()?;

/// Since the verbose flag is not set this returns false.
let verbose: Option<bool> = parser.get_value("verbose");
assert_eq!(Some(false), verbose);
Source

pub fn required_flag(&mut self, flag: &str, usage: &str)

Defines a required flag that accepts a value.

If the flag is not set then crate::Parser::finalize returns an error result of type crate::errors::Error::MissingArgument.

If the flag is set but no value is given then crate::Parser::finalize returns an error result of type crate::errors::Error::MissingValue.

§Examples
§Required Flag Set
use yafp::Parser;
use yafp::errors::Error;

let cmd_args: Vec<String> =
    vec!["head", "-file", "file.txt"]
        .iter()
        .map(|x| x.to_string())
        .collect();

let mut parser = Parser::from_vec(cmd_args);
parser.required_flag("file", "this is used to set the path for a file");

/// This must be called before fetching flags and returns any remaining args.
parser.finalize()?;

/// Since the flag is set this returns the given file path.
let file: Option<String> = parser.get_value("file");
assert_eq!(Some(String::from("file.txt")), file);
Source

pub fn optional_flag(&mut self, flag: &str, usage: &str)

Defines an optional flag that accepts a value.

Similar to crate::Parser::required_flag but crate::Parser::finalize will not return an error result if the flag is missing.

Source

pub fn get_value<T>(&self, flag: &str) -> Option<T>
where T: FromStr, <T as FromStr>::Err: Display,

Returns the value of a flag.

Source

pub fn help_flags(&self) -> String

Returns a string with the generated flag information.

Source

pub fn help(&self) -> String

Returns a string with the usage string.

If you use positional arguments it might be useful to define a custom function which prints the usage line and then prints the string returned by crate::Parser::help_flags.

§Examples
§Default Help
use yafp::Parser;
use yafp::errors::Error;

let cmd_args: Vec<String> =
    vec!["head", "-verbose", "file.txt"]
        .iter()
        .map(|x| x.to_string())
        .collect();

let mut parser = Parser::from_vec(cmd_args);
parser.bool_flag("verbose", "this is used to get verbose output");

/// This must be called before fetching flags and returns any remaining args.
parser.finalize()?;

/// Using the default help function does not allow you to specify the positional args but let's you get
/// the basic help working.
let help: String = parser.help();
assert_eq!(String::from("Usage: head [options...]\n  -verbose\n\tthis is used to get verbose output\n"), help);
§Custom Help
use yafp::Parser;
use yafp::errors::Error;

let cmd_args: Vec<String> =
    vec!["head", "-verbose", "file.txt"]
        .iter()
        .map(|x| x.to_string())
        .collect();

let mut parser = Parser::from_vec(cmd_args);
parser.bool_flag("verbose", "this is used to get verbose output");

let command = parser.command.to_string();
let help_flags = parser.help_flags();
parser.set_help_fn(move || {
  let help_string = format!("Usage: {} [options...] <file>", command);
  format!("{}\n{}", help_string, help_flags)
});

/// This must be called before fetching flags and returns any remaining args.
parser.finalize()?;

/// Using the default help function does not allow you to specify the positional args but let's you get
/// the basic help working.
let help: String = parser.help();
assert_eq!(String::from("Usage: head [options...] <file>\n  -verbose\n\tthis is used to get verbose output\n"), help);
Source

pub fn set_help_fn(&mut self, f: impl Fn() -> String + 'static)

Accepts a closure that defines a custom help function, for an example usage check the custom help example.

Source

pub fn finalize(&mut self) -> Result<Vec<String>>

Parses the arguments taking into account all defined flags and returns any remaining non-flag arguments.

§Errors

Depending on the flags set, it returns a variant of crate::errors::Error.

Auto Trait Implementations§

§

impl Freeze for Parser

§

impl !RefUnwindSafe for Parser

§

impl !Send for Parser

§

impl !Sync for Parser

§

impl Unpin for Parser

§

impl !UnwindSafe for Parser

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> 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, 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.