我正在使用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!
答案 0 :(得分: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)