Parser

Struct Parser 

Source
pub struct Parser<'a> { /* private fields */ }

Implementations§

Source§

impl<'a, 'b> Parser<'a>

The Parser struct is the Heart of revparse. Here is a brief explanation.

§revparse

§Usage
// Import the Parser struct, and ArgState enum
use revparse::{ArgState, Parser};
// Create an instance of Parser
let mut parser: Parser = Parser::new("your_program_name"); // your_program_name is needed for the help message
// Add argument
parser.add_argument(
    "--argument",                  // Long Name, not optional
    Some("-a"),                    // Optional short name
    "Argument does this and that", // Help message for that specific argument
    // If this is Some(), then the argument will require a value to be passed to it
    Some("VALUE"),                 // like this: your_program_name -a "value"
);
 
// Call this function between adding the arguments and getting them
parser.run(); // Will take the arguments passed to the program
// Alternatively you can use run_custom_args() for testing
// parser.run_custom_args(Parser::args(&["your_program_name", "-a", "value"]));
 
let argument: ArgState = parser.get("--argument");
match argument {
    ArgState::False => println!("--argument wasn't called"),
    ArgState::Value(val) => println!("--argument was called with the value: {}", val),
    ArgState::True => panic!("Impossible, ArgState::True will only be returned, if the last argument to parser.add_argument() is None."),
}

§Positional Arguments

Positional Arguments are Values passed without flags.

§Usage
use revparse::Parser;
let mut parser: Parser = Parser::new("grep");
// This would store the first argument, that doesn't start with '-' AND isn't after a flag, that takes a value.
parser.add_pos_arg("PATTERN");
parser.run();
let pos_args: Vec<String> = parser.get_pos_args();
if pos_args.len() != 0 {
    // So in this case 'grep smth' would give you the String "smth" in pos_args[0]. The string can't start with '-'.
    // If you want your users to pass values with '-', use a flag.
    println!("The first positional argument was: {}", pos_args[0]);
}

§Examples

§Example Program with flag ‘-a’, that takes a value and flag ‘-b’, that doesn’t
use revparse::{ArgState, Parser};
let mut parser: Parser = Parser::new("your_program_name");
parser.add_argument("--arg-a", Some("-a"), "Takes a value", Some("VAL_NAME"));
parser.add_argument("--arg-b", Some("-b"), "Does not take a value", None);
// Normally you would call .run(), but in this example we will call .run_custom_args() instead, to test it.
parser.run_custom_args(Parser::args(&[
    "your_program_name", // Program name will be ignored
    "-avalue",           // "-a" "value" is valid too
    "-b",
]));
let value_passed_to_a: String = match parser.get("--arg-a") {
    ArgState::Value(s) => s,
    _ => panic!("Parsing Error!"),
};
assert_eq!(value_passed_to_a, "value");
if let ArgState::True = parser.get("--arg-b") {
    // true, as arg was called
} else {
    panic!("Parsing Error!")
}
§Help Message:
Usage: your_program_name [OPTION]...
 
Options:
  -a, --arg-a=VAL_NAME      Takes a value
  -b, --arg-b               Does not take a value
§Previous Example Program with 2 Positional Arguments
use revparse::{ArgState, Parser};
let mut parser: Parser = Parser::new("your_program_name");
parser.add_argument("--arg-a", Some("-a"), "Takes a value", Some("VAL_NAME"));
parser.add_argument("--arg-b", Some("-b"), "Does not take a value", None);
parser.add_pos_arg("EXAMPLE");
parser.add_pos_arg("[ANOTHER]...");
// You can see the help message format below
parser.pos_arg_help("Help Message Shown under 'Usage:', EXAMPLE can be used to ... etc\nCan contain new line chars.");
// Normally you would call .run(), but in this example we will call .run_custom_args() instead, to test it.
parser.run_custom_args(Parser::args(&[
    "your_program_name", // Program name will be ignored
    "--arg-a=value",     // "-a" "value" is valid too
    "pos_arg1",           // Valid, because it doesn't start with a '-'
    "-b",
    "This is a positional Argument, because -b does not take a value",
]));
// From previos code
let value_passed_to_a: String = match parser.get("--arg-a") {
    ArgState::Value(s) => s,
    _ => panic!("Parsing Error!"),
};
assert_eq!(value_passed_to_a, "value");
if let ArgState::True = parser.get("--arg-b") {
    // true, as arg was called
} else {
    panic!("Parsing Error!")
}
 
// Positional Arguments
let pos_args: Vec<String> = parser.get_pos_args();
assert_eq!(pos_args.len(), 2); // Length is 2, as two positional Arguments were provided.
assert_eq!(pos_args[0], "pos_arg1");
assert_eq!(pos_args[1], "This is a positional Argument, because -b does not take a value");
§Help Message:
Usage: your_program_name [OPTION]... EXAMPLE [ANOTHER]...
Help Message Shown under 'Usage:', EXAMPLE can be used to ... etc
Can contain new line chars.
 
Options:
  -a, --arg-a=VAL_NAME      Takes a value
  -b, --arg-b               Does not take a value
Source

pub fn run(&mut self)

Parses the arguments, and stores them in self or exits with the appropriate Error message. You have to run this function before using the .get() function.

Source

pub fn run_custom_args(&mut self, args: impl Iterator<Item = String>)

§Replaces the run() function, this function allows you to provide the program with custom Arguments other than std::env::args().
Source

pub fn get(&mut self, long_name: &'a str) -> ArgState

Function to get the results of the arguments. Returns an instance of ArgState. Example code:

use revparse::{ArgState, Parser};
let mut parser = Parser::new("your_program_name");
parser.add_argument("--start-process", Some("-s"), "Start some process, this is the help message", Some("PROCESS"));
parser.run();
let result: ArgState = parser.get("--start-process");
match result {
    ArgState::True => panic!("Impossible"), // True will only be the case, if you didn't allow a value
    ArgState::False => println!("Argument '--start-process' was not called"),
    ArgState::Value(value) => println!("Argument '--start-process' was called with the value: '{value}'"),
}
Source

pub fn new(program_name: &'a str) -> Parser<'a>

Function to create an instance of Parser, on which you call the .add_argument() function, as well as .get() and .run() Example code:

use revparse::Parser;
let mut parser = Parser::new("your_program_name");
Source

pub fn pos_arg_help(&mut self, help_msg: &'a str)

§Help Message for Positional Arguments
§Optional
§Example Usage:
use revparse::Parser;
let mut parser = Parser::new("grep");
parser.add_pos_arg("PATTERNS");
parser.add_pos_arg("[FILE]...");
// If you were to implement the help message of GNU grep:
parser.pos_arg_help("Search for PATTERNS in each FILE.\nExample: grep -i 'hello world' menu.h main.c\nPATTERNS can contain multiple patterns separated by newlines.");
parser.run(); // if the user now passes --help, the pos_arg_help message will be printed under "Usage: ..."

Which would look like this:

Usage: grep [OPTION]... PATTERNS [FILE]...
Search for PATTERNS in each FILE.
Example: grep -i 'hello world' menu.h main.c
PATTERNS can contain multiple patterns separated by newlines.
Source

pub fn add_argument( &mut self, long_name: &'a str, short_name: Option<&'a str>, help_msg: &'a str, take_value: Option<&'a str>, )

To add arguments, you can use the .add_argument() function on a Parser instance. The function takes 4 Parameters apart from self. The First is the long name, that has to start with “–” and is required, not optional. The Second is an optional short name, of type Option<&str>. If it is set to None, there will be no short name for that argument, if you want a short name, like “-e” you will have to wrap it in Some() like this Some(“-e”). Short names have to start with a ‘-’ and only contain one other character. The Third option is the help message, that will be shown behind the corresponding option, when –help is called. The Fourth options is about wheter the argument can take values, or arguments like this:

your_program_name --option-that-takes-a-value="This is the value"
your_program_name --option-that-takes-a-value "This is the value"
your_program_name -o"This is the value"
your_program_name -o "This is the value"

If you want this to be possible, you have to provide a name for the value to be shown in the help message wrapped in a Some(). For example to add an argument “–start-process” that takes a value “PROCESS” you have to write the following:

use revparse::Parser;
let mut parser = Parser::new("your_program_name");
parser.add_argument("--start-process", Some("-s"), "Start some process, this is the help message", Some("PROCESS"));

You don’t have to provide “PROCESS” in capital letters, since they will be capitalized automatically. This is what “PROCESS” is needed for:

Usage: your_program_name [OPTION]...

Options:
  -s, --start-process=PROCESS  Start some process, this is the help message
  ^-2 ^-1.parameter   ^-4.p.   ^-3.parameter
Source

pub fn add_pos_arg(&mut self, name: &'a str)

§Adds Positional Arguments

Usage:

use revparse::Parser;
let mut parser = Parser::new("your_program_name");
parser.add_pos_arg("DIRECTORY"); // can be any name, if not in capital letters, it will be capitalized.
parser.add_pos_arg("FILE"); // you can add as many positional arguments, as you want.
parser.add_pos_arg("[FILE2]..."); // The "[]..." can be used to tell the user, that the argument is optional.
parser.add_pos_arg("[MODE]..."); // The names are needed for the help message.
Source

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

§Returns a Vector with all Positional arguments: <Vec<String>
use revparse::Parser;
let mut parser = Parser::new("your_program_name");
parser.add_pos_arg("ARG");
parser.run();
let pos_args: Vec<String> = parser.get_pos_args();
match pos_args.len() {
    0 => println!("No positional argument was given"),
    1 => println!("Arg was: {}", pos_args[0]),
    _ => panic!("The Vectors length can't exceed the amount of times the add_pos_arg() function was called."),
}
Source

pub fn args(args: &[&str]) -> impl Iterator<Item = String>

Auto Trait Implementations§

§

impl<'a> Freeze for Parser<'a>

§

impl<'a> RefUnwindSafe for Parser<'a>

§

impl<'a> Send for Parser<'a>

§

impl<'a> Sync for Parser<'a>

§

impl<'a> Unpin for Parser<'a>

§

impl<'a> UnwindSafe for Parser<'a>

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.