Derive-based argument parsing optimized for code size and conformance to the Fuchsia commandline tools specification. 基于 derive 宏的参数解析工具,针对代码大小进行了优化,并且遵循 Fuchsia 命令行工具规范。
repo:https://github.com/google/argh
由 Google 开发者编写,但并非 Google 官方支持。
官方给的基本例子:
use argh::FromArgs;
#[derive(FromArgs)]
/// Reach new heights.
struct GoUp {
/// whether or not to jump
#[argh(switch, short = 'j')]
jump: bool,
/// how high to go
#[argh(option)]
height: usize,
/// an optional nickname for the pilot
#[argh(option)]
pilot_nickname: Option<String>,
}
fn main() {
let up: GoUp = argh::from_env();
}
Usage: cmdname [-j] --height <height> [--pilot-nickname <pilot-nickname>]
Reach new heights.
Options:
-j, --jump whether or not to jump
--height how high to go
--pilot-nickname an optional nickname for the pilot
--help display usage information
过程宏-参数类型:
switch
:用在 bool 类型的字段上,表明命令行参数是可选的,而且一旦提供该命令行参数,则给该字段的值赋给 true 。option
:Option
类型上,表明命令行参数是可选的。Vec
类型上,表明命令行参数可选,而且可以重复出现,即这个参数及其值可以在命令行中出现 0 次或更多次。Option
、非 Vec
类型上,则表示命令行参数必选。positional
:位置参数,表明按照结构体声明的字段顺序解析命令行参数,无需 --xx value
的 --xx
。最后一个位置参数可以包含默认值,也可以包装在 Option 或 Vec 中来接收可选(指 0 或 1 个)或重复(指 0 或多个)的位置参数。subcommand
:需定义一个顶层结构体、一个表示子命令的枚举体(这个枚举体列举所有子命令,子命令以结构体形式呈现,子命令结构体还需要 name 设置名称)过程宏-其他设置:
short = 'a'
:解析 -a
形式的简短参数,只支持 ascii 的 Char
类型,比如大小写、数字。long = "xx-xx"
:重新命名这个字段的参数名称,由此可允许参数名称带连字符 --xx-xx
。这个设置的默认值为字段名称,只支持 ascii 小写形式的名称,不支持大写和数字。default = "default_height()")
、default = "String::from(\"only up\")")
:默认值,引号内可以是函数名(带括号)、表达式from_str_fn(always_five)
:针对某个解析的参数进行自定义处理,always_five
的函数签名方式为 fn(&str) -> Result<T, String>
description = "xxxxx"
:给参数添加帮助信息。///
文档注释也可以提供用帮助信息,而 description
的内容在命令行帮助信息里会覆盖掉 ///
提供的信息。注意:换行和空换行会在 --help 信息里变成一个空格;描述信息不能过长,否则会出现 error: invalid reference to positional arguments 4 and 5 (there is 1 argument
(这个报错信息不准确,我也是排查了很久才发现)。trait:
FromArgs
trait:用于 argh 命令行解析的所有结构体和枚举体,都必须 derive 这个 trait 。FromArgValue
trait:用于 argh 命令行解析的结构体字段的类型必须实现这个 trait ,argh 已经给所有实现 FromStr
trait 的类型实现了这个 trait 。std 的基础类型都实现了 FromStr
trait ,所以可以直接使用 std 的基础类型;自定义类型需要实现 FromStr
trait 和 FromArgValue
trait 。优点:
缺点:
--help
不支持 -h
--option value
和 -o value
,不支持 --option=value
和 -ovalue
其他 args-parser:
clap
/structopt
: very fully-featured. The only other argument parser for Rust I know of that truly handles invalid unicode properly, if used right. Large.argh
and gumdrop
: much leaner, yet still convenient and powerful enough for most purposes. Panic on invalid unicode.argh
adheres to the Fuchsia specification and therefore does not support --option=value
and -ovalue
, only --option value
and -o value
.pico-args
: slightly smaller than lexopt and easier to use (but less rigorous).ap
: I have not used this, but it seems to support iterative parsing while being less bare-bones than lexopt.getopt
.src: https://github.com/blyxxyz/lexopt#see-also
P.S. 不得不说,Rust 利用抽象的类型系统和宏,在 args-parser 方面太棒了。写 Rust 是一种享受。