Crates.io | hiopt |
lib.rs | hiopt |
version | 0.1.7 |
source | src |
created_at | 2023-10-13 09:20:34.738149 |
updated_at | 2023-11-17 08:55:53.250648 |
description | getopt/getopt_long for rust |
homepage | |
repository | https://gitee.com/1467792822/hiopt |
max_upload_size | |
id | 1002137 |
size | 35,078 |
getopt/getopt_long for rust
.
提供类似libc::getopt的功能.
-a -b
或者 -ab
, -c value
或者 -cvalue
--long=value
或者 --long value
--
-c value arg
或者 arg -c value
分别提供遍历选项和非选项的函数接口.
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获取应用程序的命令行输入进行分析处理
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元素生命周期更短.
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!(),
}
}
""
}