[][src]Macro argwerk::argwerk

macro_rules! argwerk {
    (
        $(#[$($usage_meta:tt)*])*
        $usage:literal $({
            $($field:ident : $ty:ty $(= $expr:expr)?),* $(,)?
        })? $(
            $(#[$($meta:tt)*])*
            $first:literal $(| $rest:literal)* $(, $arg:ident)* $(if $cond:expr)? => $block:block
        )*
    ) => { ... };
    (@doc #[doc = $doc:literal] $out:ident) => { ... };
    (@doc #[$meta:meta] $out:ident) => { ... };
    (@decl $field:ident, $ty:ty) => { ... };
    (@decl $field:ident, $ty:ty, $expr:expr) => { ... };
}

Parse commandline arguments.

This will generate an anonymous structure containing the arguments defined which is returned by the macro.

Each branch is executed when an incoming argument matches and must return a Result, like Ok(()). Error raised in the branch will cause a ErrorKind::Error error to be raised associated with that argument with the relevant error attached.

This also generated two helper functions available in the branches:

  • write_help - Which can write help to something implementing std::io::Write.
  • print_help - Which will write the help string to [io::stdout].

These are only available in the scope of the matching branches.

Examples

let args = argwerk::argwerk! {
    /// A simple test command.
    ///
    /// This is nice!
    "testcommand [-h]" {
        help: bool,
        file: Option<String>,
        limit: usize = 42,
    }
    /// Print the help.
    "-h" | "--help" => {
        help = true;
        print_help();
        Ok(())
    }
    /// Hello World.
    "--limit" | "-l", n => {
        limit = str::parse(&n)?;
        Ok(())
    }
}?;

if args.help {
    return Ok(());
}

Ok(())