[英]How to add --help, -h flag to Thor command?
我在 Ruby 可执行文件中创建了一个 Thor 类,它在使用./foo help bar
时正确显示了帮助。
为了使它更直观(为了我的用户的理智),我还想支持./foo bar --help
和./foo bar -h
。 当我这样做时,我得到:
ERROR: "foo bar" was called with arguments ["--help"]
Usage: "foo bar"
我可以手动执行method_option :help, ...
并在bar
方法中处理它,但我希望有一种更简单的方法来做到这一点(将该命令重定向到./foo help bar
)。
有谁知道一个简单易行的方法来做到这一点?
假设Foo
是继承自Thor
类,您可以在Foo.start
之前的某处调用以下Foo.start
:
help_commands = Thor::HELP_MAPPINGS + ["help"]
# => ["-h", "-?", "--help", "-D"]
if help_commands.any? { |cmd| ARGV.include? cmd }
help_commands.each do |cmd|
if match = ARGV.delete(cmd)
ARGV.unshift match
end
end
end
与其进入 Thor 并修补某些方法以具有不同的 ARGV 解析行为,不如将任何帮助命令移动到列表的前面来作弊。
您可以使用class_option
实现此class_option
。 如果您设置了类选项,则此选项可用于 cli 中的每个方法,您只需检查它是否已设置,然后调用帮助方法。
像这样的东西:
class CLI < Thor
class_option :help, type: :boolean
desc "foo PARAM", "foo"
def foo(param)
handle_help_option(:foo)
# your logic
end
def handle_help_option(method_name)
help(method_name) if options[:help]
end
end
以@max-pleaner 列出的内容为基础。 这也将支持子命令:
help_commands = Thor::HELP_MAPPINGS + ["help"]
(help_commands & ARGV).each do |cmd|
match = ARGV.delete(cmd)
ARGV.size > 1 ? ARGV.insert(-2, match) : ARGV.unshift(match)
end
为了补充 max plener 的答案,以下处理子命令,因为如果将技巧应用于它们,子命令帮助就会被破坏。
此外,我选择重载 Thor 启动命令。
def self.start(*args)
if (Thor::HELP_MAPPINGS & ARGV).any? and subcommands.grep(/^#{ARGV[0]}/).empty?
Thor::HELP_MAPPINGS.each do |cmd|
if match = ARGV.delete(cmd)
ARGV.unshift match
end
end
end
super
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.