Crate hiopt

source ·
Expand description

提供类似libc::getopt的功能.

  1. 单ascii字符的选项: -a -b 或者 -ab, -c value 或者 -cvalue
  2. 长字符串选项: --long=value 或者 --long value
  3. 选项结束标志: --
  4. 不限制非选项的输入顺序: -c value arg 或者 arg -c value

分别提供遍历选项和非选项的函数接口.

Example

use hiopt::{options, OptErr};
let opts = options!["a", "b:", "long:"];
let args = ["program", "-acbb-arg", "--long=long-arg", "--abc", "arg", "-b", "--", "-abc", "--long"];
let mut iter = opts.opt_iter(&args);
assert_eq!(iter.next(), Some(Ok((0, None)))); // opts[0].name = "a"
assert_eq!(iter.next(), Some(Err(OptErr::NoShortOpt(b'c'))));
assert_eq!(iter.next(), Some(Ok((1, Some("b-arg"))))); // opts[1].name = "b"
assert_eq!(iter.next(), Some(Ok((2, Some("long-arg"))))); // opts[2].name = "long"
assert_eq!(iter.next(), Some(Err(OptErr::NoLongOpt("abc"))));
assert_eq!(iter.next(), Some(Err(OptErr::NoArg(1)))); // opts[1].name = "b"
assert_eq!(iter.next(), None);

let mut iter = opts.noopt_iter(&args);
assert_eq!(iter.next(), Some("program"));
assert_eq!(iter.next(), Some("arg"));
assert_eq!(iter.next(), Some("--"));
assert_eq!(iter.next(), Some("-abc"));
assert_eq!(iter.next(), Some("--long"));
assert_eq!(iter.next(), None);

可以通过hictor crate获取应用程序的命令行输入进行分析处理

Example

let opts = hiopt::options!["a", "b:"];
let args = unsafe { hiopt::raw_args_from_i8(hictor::args()) };
for opt in opts.opt_iter(args) {
    println!("opt = {:?}", opt);
}

for arg in opts.noopt_iter(args) {
    println!("arg = {:?}", arg);
}

可以定义为静态变量或者常量.

Example

static OPTS: hiopt::Options<'static> = hiopt::options!["i", "input"];
 
fn parse_opts(opts: &hiopt::Options<'_>) {
    let args = unsafe { hiopt::raw_args_from_i8(hictor::args()) };
    for opt in opts.opt_iter(args) {
        println!("opt = {:?}", opt);
    }
}

parse_opts(&OPTS);

Macros

  • 定义支持的所有选项数组

Structs

Enums

Traits

  • 基于Arguments同时支持[*const u8]和&str两种类型, 前者对应获取的应用程序的输入
  • 统一按照[u8]进行选项匹配

Functions