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
andcrate::FromArg
for type that implementsFromRead
. - impl_
from_ str_ with_ read - Implements
std::str::FromStr
for type that implementsFromRead
. - parsef
- This macro can be tought of as opposite of [
write!
] or as something likefscanf
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 likefscanf
in C. - starts_
any - Checks if string starts with any of the given values.
Structs§
- ArgErr
Ctx - Information about error in command line arguments. Implements
Display
with user friendly error messages. - Pareg
- Helper for parsing arguments.
- Pareg
Ref - Helper for parsing arguments.
- Reader
- Struct that allows formated reading.
- Reader
Chars - Char iterator over reader.
Enums§
- ArgError
- Errors thrown when parsing arguments.
- Color
Mode - ParseF
Arg - 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 implementsFromStr
, you can just implementFromArgStr
. - From
ArgStr - Default implementation for
FromArg
for types that implementFromStr
- From
Read - Trait similar to
crate::FromArg
. Difference is that this may parse only part of the input. - SetFrom
Read
Functions§
- arg_
list - Parses multiple values in
arg
separated bysep
. - bool_
arg - Parse bool value in a specific way. If the value of lowercase
arg
is equal tot
returns true, if it is equal tof
returns 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"
andvalue
that is also parsed to the given type. - key_
val_ arg - If sep was
'='
, parses"key=value"
into"key"
andvalue
that is also parsed to the given type. - mval_
arg - If sep was
'='
, parses"key=value"
intovalue
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 tot
returns true, if it is equal tof
returns false and if it is equal ton
returnsNone
. Otherwise returns error. - parse_
arg - Parses the given argument using the
FromArg
trait. - parsef
- Parsef implementation. Parse all data in
r
based onargs
. - parsef_
part - Parsef part implementation. Parse part of data in
r
, based onargs
. - split_
arg - Splits
arg
by separatorsep
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"
intovalue
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.