Crate pareg

Source
Expand description

§pareg

Helpful utilities for parsing command line arguments.

The aim of this crate is not to have some magic derive macro that will do all of the parsing for you. Instead pareg will let you choose exactly how to parse the arguments, but it will help as much as possible.

Pareg also comes with user friendly errors so that you don’t have to worry about writing the error messages while parsing the arguments. For example running the program below like this:

my-program --color=no

will output the following error message:

argument error: Unknown option `no`.
--> arg1:8..10
 |
 $ my-program --color=no
 |                    ^^ Unknown option.
hint: Valid options are: `auto`, `always`, `never`.

§Example usage

use std::process::ExitCode;

use pareg::{Result, Pareg, FromArg, starts_any};

// You can define enums, and have them automaticaly derive FromArg where each
// enum variant will be parsed from case insensitive strings of the same name
// (e.g. `"Auto"` will parse into `Auto`, `"always"` into `Always`, `"NEVER"`
// into `Never`)
#[derive(FromArg)]
enum ColorMode {
    Auto,
    Always,
    Never,
}

// create your struct that will hold the arguments
struct Args {
    name: String,
    count: usize,
    colors: ColorMode,
}

impl Args {
    // create function that takes the arguments as ArgIterator
    pub fn parse(mut args: Pareg) -> Result<Self>
    {
        // initialize with default values
        let mut res = Args {
            name: "pareg".to_string(),
            count: 1,
            colors: ColorMode::Auto,
        };

        while let Some(arg) = args.next() {
            match arg {
                // when there is the argument `count`, parse the next value
                "-c" | "--count" => res.count = args.next_arg()?,
                // if the argument starts with either `--color` or
                // `--colour`, parse its value.
                a if starts_any!(a, "--color=", "--colour=") => {
                    res.colors = args.cur_val('=')?;
                }
                // it seems that this is flag, but it is not recognized
                a if a.starts_with('-') => {
                    Err(args.err_unknown_argument())?
                },
                // if the argument is unknown, just set it as name
                _ => res.name = arg.to_string(),
            }
        }

        Ok(res)
    }
}

// Now you can call your parse method:
fn start() -> Result<()> {
    // just pass in any iterator of string reference that has lifetime
    let args = Args::parse(Pareg::args())?;

    // Now you can use your arguments:
    for _ in 0..args.count {
        println!("Hello {}!", args.name);
    }
    Ok(())
}

fn main() -> ExitCode {
    match start() {
        Ok(_) => ExitCode::SUCCESS,
        Err(e) => {
            eprint!("{e}");
            ExitCode::FAILURE
        }
    }
}

Modules§

check
This module provides types that allow checking for values even if the given type is parsed.
proc
This module contains raw implementation of proc macros with proc_macro2.

Macros§

has_any_key
Checks if string is key value with the given separator or just key with one of the keys.
impl_from_arg_str_with_read
Implements std::str::FromStr and crate::FromArg for type that implements FromRead.
impl_from_str_with_read
Implements std::str::FromStr for type that implements FromRead.
parsef
This macro can be tought of as opposite of [write!] or as something like fscanf in C.
parsef_part
Simmilar to parsef!, but doesn’t expect to parse the whole string, but only start of the string. It macro can be tought of as opposite of [write!] or as something like fscanf in C.
starts_any
Checks if string starts with any of the given values.

Structs§

ArgErrCtx
Information about error in command line arguments. Implements Display with user friendly error messages.
Pareg
Helper for parsing arguments.
ParegRef
Helper for parsing arguments.
Reader
Struct that allows formated reading.
ReaderChars
Char iterator over reader.

Enums§

ArgError
Errors thrown when parsing arguments.
ColorMode
ParseFArg
Argument to parsef describing expected operation.

Traits§

ArgInto
This trait represents a string reference object that can be parsed into a type.
ByRef
Similar to AsRef, but this also gives the option to specify the lifetime of the returned reference.
FromArg
Represents a trait similar to FromStr, in addition it may return type that references the original string slice. If your type already implements FromStr, you can just implement FromArgStr.
FromArgStr
Default implementation for FromArg for types that implement FromStr
FromRead
Trait similar to crate::FromArg. Difference is that this may parse only part of the input.
SetFromRead

Functions§

arg_list
Parses multiple values in arg separated by sep.
bool_arg
Parse bool value in a specific way. If the value of lowercase arg is equal to t returns true, if it is equal to f returns false and otherwise returns error.
key_arg
If sep was '=', parses "key=value" into "key" and discards value.
key_mval_arg
If sep was '=', parses "key=value" into "key" and value that is also parsed to the given type.
key_val_arg
If sep was '=', parses "key=value" into "key" and value that is also parsed to the given type.
mval_arg
If sep was '=', parses "key=value" into value that is parsed to the given type.
opt_bool_arg
Parse bool value in a specific way. If the value of lowercase arg is equal to t returns true, if it is equal to f returns false and if it is equal to n returns None. Otherwise returns error.
parse_arg
Parses the given argument using the FromArg trait.
parsef
Parsef implementation. Parse all data in r based on args.
parsef_part
Parsef part implementation. Parse part of data in r, based on args.
split_arg
Splits arg by separator sep and parses each word into a resulting vector.
try_set_arg
Tries to set the value of res to some if it is none. Throws error if it is some.
try_set_arg_with
Tries to set the value of res to some if it is none. Throws error if it is some.
val_arg
If sep was '=', parses "key=value" into value that is parsed to the given type.

Type Aliases§

Result
Pareg result type. It is [std::result::Result<T, ArgError<'a>>]

Derive Macros§

FromArg
Derives the [pareg_core::FromArg] macro for an enum. The enum must not be generic and the enum members cannot contain any fields.