Parsnip

A small Rust Argparser

Setup

Add the lib to your Cargo.toml.

[dependencies] argparsnip = "0.1.0"

Setup

Add the lib to your Cargo.toml.

[dependencies] parsnip = "0.1.0"

Features

Usage

Here are some quick common cases. For more examples please look at the tests in lib.rs

Examples

Check if a flag was given once

// ./prog --arg fn main() { let args = Args { args: vec![Arg { name: "arg", short: Some("a"), about: "a flag", long: Some("arg"), required: true, ..Default::default() }], ..Default::default() }; let results = args.parse(std::env::args()); assert_eq!(1, results.flags("arg")); }

Get the value of an arg

// ./prog -a 1 fn main() { let args = Args { args: vec![Arg { name: "arg", short: Some("a"), default: Some(|| { Value::From(2) }), value_type: Type::Int, num_values: NumValues::Fixed(1), ..Default::default() }], ..Default::default() }; let results = args.parse(std::env::args()); assert_eq!(1, results.params.get("arg")?.try_into()); }

Validate an argument

// ./prog -a 1 2 fn main() { let args = Args { args: vec![Arg { name: "arg", short: Some("a"), value_type: Type::Int, num_values: NumValues::AtLeast(1), validation: |val| { let val: &i32 = v.try_into().unwrap(); if 2 >= *val { Ok(()) } else { Err("failed validation") } } ..Default::default() }], ..Default::default() }; let results = args.parse(std::env::args()); assert_eq!(vec![1, 2], results.params.get("arg")?.try_into()); }

Using Subcommand

// ./prog sub --arg fn main() { let args = Args { args: vec![Arg { name: "arg", long: Some("arg"), num_values: NumValues::None, ..Default::default() }], subcommands: vec![Args { name: "sub", path: Some("main/sub"), args: vec![Arg { name: "arg", long: Some("arg"), num_values: NumValues::None, ..Default::default() }], ..Default::default() }], ..Default::default() }; let results = args.parse(std::env::args()); // this is the unique identifier for the subcommand assert_eq!("main/sub", results.path); assert_eq!(1, results.flags["arg"]); }

Documentation

Development

TODO