0

我正在使用 Ruby 的optparse库来解析我的命令行应用程序的选项,但我不知道如何也接受命令。

它会是这样的:

commit -f -d init

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!
4

1 回答 1

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}"

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

而且,虽然这不是您问题的答案,但选项定义中的方括号([])意味着选项的参数是可选的。例如,根据您的定义,即使通过了选项,电子邮件和密码也可能为零:

$ pivotal_commit -e
options: {:email=>nil}
subcommand: init

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

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

现在需要电子邮件参数:

$ pivotal_commit -e
pivotal_commit:6:in `<main>': missing argument: -e (OptionParser::MissingArgument)
于 2012-10-17T15:52:49.953 回答