args 0.1.1

An argument parsing and validation library designed to take some of tediousness out of the general 'getopts' crate.
Documentation

A dead simple implementation of command line argument parsing and validation built on top of the getopts crate.

In order to use the args crate simply create an Args object and begin registering possible command line options via the flag(...) and option(...) methods. Once all options have been registered, parse arguments directly from the command line, or provide a vector of your own arguments.

If any errors are encountered during parsing the method will panic, otherwise, arguments can be retrieved from the args instance by calling value_of(...) or validated_value_of(...).

That's it!

Usage

This crate is on crates.io and can be used by adding args to the dependencies in your project's Cargo.toml.

[dependencies]
args = "0.1"

and this to your crate root:

extern crate args;

Example

The following example shows simple command line parsing for an application that requires a number of iterations between zero (0) and ten (10) to be specified, accepts an optional log file name and responds to the help flag.

extern crate args;
extern crate getopts;

use args::{Args,Order,OrderValidation};
use getopts::Occur;

const PROGRAM_NAME: &'static str = "program";

fn main() {
    let mut args = Args::new(PROGRAM_NAME);
    args.flag("h", "help", "Print the usage menu");
    args.option("i",
        "iter",
        "The number of times to run this program",
        "TIMES",
        Occur::Req,
        None);
    args.option("l",
        "log_file",
        "The name of the log file",
        "NAME",
        Occur::Optional,
        None);

    args.parse(vec!("-i", "15"));

    match args.value_of("help") {
        Ok(help) => {
            if help {
                args.full_usage(&format!("How to use {}", PROGRAM_NAME));
                return;
            }
        },
        Err(error) => {
            println!("{}", error);
            return;
        }
    }

    let gt_0 = Box::new(OrderValidation::new(Order::GreaterThan, 0u32));
    let lt_10 = Box::new(OrderValidation::new(Order::LessThanOrEqual, 10u32));
    match args.validated_value_of("iter", &[gt_0, lt_10]) {
        Ok(iterations) => {
            for _ in 0..iterations {
                println!("Doing work ...");
            }

            println!("All done.");
        },
        Err(error) => {
            println!("{}", error.to_string());
        }
    }
}