Crate argsyn

source ·
Expand description

Argument Syntax

This crate provides a complete implementation of the argument parsing algorithm described in
https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html

The easiest way to use this crate is with ArgsExt::opts and Opt::simplify. The extension trait is implemented for every Iterator which returns String. This includes std::env::Args. For example:

use argsyn::ArgsExt;

fn main() {
  for opt in std::env::args().opts("xy") {
    println!("{:?}", opt.simplify());
  }
}

Specific Example

Consider the following command:

$ program arg1 -abcx12 -y 3 --long --key=value - arg2 -- -kh --ignore

The following code simulates parsing of the command above:

use argsyn::ArgsExt;

let cmd = "
  program
  arg1
  -abcx12
  -y 3
  --long
  --key=value
  -
  arg2
  --
  -kh
  --ignore
";

let args = cmd
  .trim()
  .split_ascii_whitespace()
  .into_iter()
  .map(|s| s.to_string());

for opt in args.opts("xy") {
  println!("{:?}", opt.simplify());
}

Running the above code produces the following output:

Basic("program")
Basic("arg1")
Flag("a")
Flag("b")
Flag("c")
Pair("x", "12")
Pair("y", "3")
Flag("long")
Pair("key", "value")
Stdin
Basic("arg2")
Done
Basic("-kh")
Basic("--ignore")

See ArgsExt::opts for the same example but without simplification.

Structs

  • Flexible parser which converts arguments into Opts

Enums

  • All possible options/non-options which can be parsed from arguments
  • Alternative labeling of Opt which is easier to use in match statements.

Traits