如何配置optparse以接受两个参数选项作为命令?

Mau*_*res 0 ruby command-line optparse

我正在使用Ruby的optparse库来解析我的命令行应用程序的选项,但我无法弄清楚如何接受命令.

它会是这样的:

commit -f -d init
Run Code Online (Sandbox Code Playgroud)

init在这种情况下将是命令.它并不总是必需的,因为如果用户没有提供任何默认命令,则应该运行该命令.

这是我现在的代码:

OptionParser.new do |opts|
  opts.banner  = %Q!Usage:
  pivotal_commit                                          # to commit with a currently started issue
  pivotal_commit -f                                       # to commit with a currently started issue and finish it
  pivotal_commit -d                                       # to commit with a currently started issue and deliver it
  pivotal_commit init -e "me@gmail.com" -p my_password -l #to generate a config file at the current directory!

  opts.on("-e", "--email [EMAIL]", String, "The email to the PT account you want to access") do |v|
    options[:email] = v
  end

  opts.on("-p", "--password [PASSWORD]", String, "The password to the PT account you want to access") do |v|
    options[:password] = v
  end

  opts.on("-f", '--finish', 'Finish the story you were currently working on after commit') do |v|
    options[:finish] = v
  end

  opts.on('-d', '--deliver', 'Deliver the story you were currently working on after commit') do |v|
    options[:deliver] = v
  end

  opts.on_tail('-h', '--help', 'Show this message') do
    puts opts
    exit
  end

  opts.on_tail('-v', '--version', 'Show version') do
    puts "pivotal_committer version: #{PivotalCommitter::VERSION}"
    exit
  end

end.parse!
Run Code Online (Sandbox Code Playgroud)

KIT*_*oto 5

命令行参数(不是选项)在ARGV调用之后,OptionParser#parse!因为#parse!从中提取选项ARGV.所以,你可以得到这样的子命令:

options = {}

OptionParser.new do |opts|
# definitions of command-line options...
# ...
end.parse!

subcommand = ARGV.shift || "init"

print "options: "
p options
puts "subcommand: #{subcommand}"
Run Code Online (Sandbox Code Playgroud)

如果您有许多子命令,Thor gem可能会帮助您.

并且,虽然这不是您的问题的答案,但选项定义中的括号([])表示该选项的参数是可选的.例如,根据您的定义,即使传递选项,电子邮件和密码也可能为零:

$ pivotal_commit -e
options: {:email=>nil}
subcommand: init
Run Code Online (Sandbox Code Playgroud)

如果在传递选项时需要参数,请删除括号:

# ...
  opts.on("-e", "--email EMAIL", String, "The email to the PT account you want to access") do |v|
    options[:email] = v
  end
# ...
Run Code Online (Sandbox Code Playgroud)

现在需要电子邮件的参数:

$ pivotal_commit -e
pivotal_commit:6:in `<main>': missing argument: -e (OptionParser::MissingArgument)
Run Code Online (Sandbox Code Playgroud)