switches/src/lib.rs

47 lines
1.4 KiB
Rust

mod switches;
pub use switches::{Switches, SwitchesError as Error};
#[macro_export]
macro_rules! generate {
(
$structname:ident {
$($field:ident: $type:tt ($($opt:expr),+)),* $(,)?
}
) => {
macro_rules! build {
($f:ident, PathBuf) => {$f.as_path()};
($f:ident, Option<PathBuf>) => {$f.as_opt_path()};
($f:ident, String) => {$f.as_string()};
($f:ident, Option<String>) => {$f.as_opt_string()};
($f:ident, bool) => {$f.as_flag()};
($f:ident, u16) => {$f.as_u16()};
}
pub struct $structname {
$(pub $field: $type),*
}
impl $structname {
pub fn parse() -> Result<Self, switches::Error> {
let mut switches = switches::Switches::from_env();
$(
let mut $field = switches$(.or($opt))+;
let $field = build!($field, $type)?;
)*
Ok(Self {
$($field,)*
})
}
pub fn parse_and_raise() -> Self {
match Self::parse() {
Ok(parsed) => parsed,
Err(err) => {
eprintln!("[ERROR] {}", err);
std::process::exit(1);
}
}
}
}
};
}