我有一个ruby cli解析脚本,似乎有一些解析选项的正则表达式行为:
op = OptionParser.new do |x|
x.on("--output-config PATH", "The filesystem location for the output config file") do |output_config|
options[:output_config] = output_config
end
x.on("-j", "--json", "If this is set, then json is output instead of tabular form") do
options[:disp_json] = true
end
x.on("-h", "--help", "Show this message") do
puts op
exit 0
end
x.on("-v", "--version", "Show version") do
puts "version #{VERSION_NUMBER}"
exit 0
end
end
# do input validation and check leftovers for proper commands
begin
# parse options, parse! removes elements from ARGV so leftovers are positional arg(s)
op.parse!(ARGV)
options[:config_file] = ARGV[0] if ARGV[0]
rescue OptionParser::InvalidOption, OptionParser::MissingArgument
puts "############### #{$!.to_s} ###############"
puts ""
puts op
exit 1
end
然后,如果我这样称呼它:
script -a
它输出以下(预期行为)
############### invalid option: -a ###############
或者
script --output-config
它输出以下(预期行为)
############### missing argument: --output-config ###############
所以这就是奇怪的地方:
script --output
它输出以下内容(不预期行为)
############### missing argument: --output ###############
或者
script --ou
它输出以下内容(不预期行为)
############### missing argument: --ou ###############
基本上你传递的正则表达式匹配" output-config"传递给
块x.on("--output-config PATH"....
我看到MissingArgument与InvalidOption行为的原因是什么。
我是否使用了optparse错误或者这是库中的错误?
#######编辑如果我添加另一个x.on:
x.on("--out PATH", "The filesystem location for the output config file") do |output_config|
options[:output_config2] = output_config
end
并且传递-o(一个破折号,即一个简短形式)或--o(两个破折号),它不会抛出异常(我特别是在处理时没有执行OptionParser :: AmbiguousOption)。而是执行最短的匹配,即--out。如果我传递--outp,那么执行的时间越长。这对我来说似乎很不稳定。
#######编辑2> ./my_app --output-c
############### missing argument: --output-c
MissingArgument异常仅显示传递的标志,而不是“预期的”标记。它清楚地知道它匹配' - output-config'所以我希望能够知道这一点,以便我对用户的错误信息清晰明了。有没有办法可以确定在引发MissingArgument异常时optparser匹配的是什么?
答案 0 :(得分:1)
这是长选项的标准行为。我很难找到任何支持文档但我一直在使用长选项的这个功能,只要我一直在使用长选项(即很久很久以前)。
您可以使用 ls(1)的GNU版本轻松查看:
$ ls --h
ls: option '--h' is ambiguous
Try `ls --help' for more information.
$ ls --he
Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort.
...
$ ls --help
Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort.
...
有多个选项以--h
开头,因此--h
是一个选项错误,只有一个选项以--he
开头,因此--he
与{相同} {1}}。
如果您添加了--help
选项,那么如果您说--output-pancakes
但--output
和--output-c
可以正常工作,则会收到有关含糊不清的投诉。
您没有错误地使用该库。这也不是一个错误。这是一个功能。