8 releases

0.1.7 Nov 17, 2023
0.1.6 Nov 8, 2023
0.1.5 Oct 16, 2023

#4 in #getopt


Used in hitotp

MIT/Apache

24KB
520 lines

hiopt

getopt/getopt_long for rust.

提供类似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:"]; // ':' means the option requires an argument. 表示选项需要输入参数
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:?}");
}

0.1.4版本区分了options!和args数组引用和数组元素的引用,这样可以将命令行输入参数('static)保存下来. 0.1.5版本区分了options!和args元素的引用,options!元素的生命周期可能比args元素生命周期更短.

Example

fn get_input() -> &'static str {
    let opts = hiopt::options!["i:", "input:"];
    let args = unsafe { hiopt::raw_args_from_i8(hictor::args()) };
    for opt in opts.opt_iter(args) {
        let (idx, arg) = opt.unwrap();
        match idx {
            0..=1 => return arg.unwrap(),
            _ => unreachable!(),
        }
    }
    ""
}

Dependencies

~13KB