Parsnip

A small Rust Argparser

Setup

Add the lib to your Cargo.toml.

[dependencies] argparsnip = "0.1.3"

Features

Usage

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

Documentation

https://docs.rs/argparsnip/0.1.3/argparsnip/

Examples

Minimal Flag Example

// ./prog --arg fn main() { let args = args! { args: vec![arg! { name: "arg", short: Some("a"), }], }; let results = args.parse(std::env::args()); assert_eq!(1, results.flags("arg")); }

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, }], }; 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), }], }; 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") } } }], }; 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, }], subcommands: vec![args! { name: "sub", path: Some("main/sub"), args: vec![arg! { name: "arg", long: Some("arg"), num_values: NumValues::None, }], }], }; 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"]); }

Filters // only supports combinations (--arg && --arg2) or (--arg && --arg3) // will fail if --arg or --arg2 or --arg3 are passed on their own fn main() { let args = args! { args: vec![arg! { name: "arg", long: Some("arg"), num_values: NumValues::None, }, arg! { name: "arg2", long: Some("arg2"), num_values: NumValues::None, }, arg! { name: "arg3", long: Some("arg3"), num_values: NumValues::None, }], filters: Filters { filters: vec![Filter { filter_type: FilterType::All, inverse: false, args: vec!["arg", "arg2"], }, Filter { filter_type: FilterType::All, inverse: false, args: vec!["arg", "arg3"], }], ..Default::default() }, // this flag means we will fail if we see the same value multiple times disable_overrides: true, }; let results = args.parse(std::env::args()); }

Development

TODO