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=nowill 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. - reader
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::FromStrandcrate::FromArgfor type that implementsFromRead. - impl_
from_ str_ with_ read - Implements
std::str::FromStrfor type that implementsFromRead. - parsef
- This macro can be tought of as opposite of [
write!] or as something likefscanfin 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 likefscanfin C. - starts_
any - Checks if string starts with any of the given values.
Structs§
- ArgErr
Ctx - Information about error in command line arguments. Implements
Displaywith user friendly error messages. - ArgError
- Errors thrown when parsing arguments.
- Pareg
- Helper for parsing arguments.
- Pareg
Ref - Helper for parsing arguments.
- ReadFmt
- Format for read function with reader.
- Reader
- Struct that allows formated reading.
- Reader
Chars - Char iterator over reader.
Enums§
- ArgErr
Kind - Errors thrown when parsing arguments.
- Color
Mode - ParseF
Arg - Argument to
parsefdescribing expected operation.
Constants§
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 implementsFromStr, you can just implementFromArgStr. - From
ArgStr - Default implementation for
FromArgfor types that implementFromStr - From
Read - Trait similar to
crate::FromArg. Difference is that this may parse only part of the input. - SetFrom
Read - Simmilar to From read, but can be parsed into an existing instance. This
trait is required for parsef. Don’t implement this directly, rather
implement
FromReadand than use the traitAutoSetFromRead.
Functions§
- arg_
list - Parses multiple values in
argseparated bysep. - bool_
arg - Parse bool value in a specific way. If the value of lowercase
argis equal totreturns true, if it is equal tofreturns false and otherwise returns error. - key_arg
- If sep was
'=', parses"key=value"into"key"and discardsvalue. - key_
mval_ arg - If sep was
'=', parses"key=value"into"key"andvaluethat is also parsed to the given type. - key_
val_ arg - If sep was
'=', parses"key=value"into"key"andvaluethat is also parsed to the given type. - mval_
arg - If sep was
'=', parses"key=value"intovaluethat is parsed to the given type. - opt_
bool_ arg - Parse bool value in a specific way. If the value of lowercase
argis equal totreturns true, if it is equal tofreturns false and if it is equal tonreturnsNone. Otherwise returns error. - parse_
arg - Parses the given argument using the
FromArgtrait. - parsef
- Parsef implementation. Parse all data in
rbased onargs. - parsef_
part - Parsef part implementation. Parse part of data in
r, based onargs. - split_
arg - Splits
argby separatorsepand parses each word into a resulting vector. - try_
set_ arg - Tries to set the value of
resto some if it is none. Throws error if it is some. - try_
set_ arg_ with - Tries to set the value of
resto some if it is none. Throws error if it is some. - val_arg
- If sep was
'=', parses"key=value"intovaluethat 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.