简体   繁体   English

如何将 --help, -h 标志添加到 Thor 命令?

[英]How to add --help, -h flag to Thor command?

I created a Thor class inside a Ruby executable, and it correctly shows the help when using ./foo help bar .我在 Ruby 可执行文件中创建了一个 Thor 类,它在使用./foo help bar时正确显示了帮助。

To make it more intuitive (for the sanity of my users), I'd also like to support ./foo bar --help and ./foo bar -h .为了使它更直观(为了我的用户的理智),我还想支持./foo bar --help./foo bar -h When I do that, I get:当我这样做时,我得到:

ERROR: "foo bar" was called with arguments ["--help"]
Usage: "foo bar"

I could manually do method_option :help, ... and handle it inside the bar method, but I hope there would be an easier way to do that (redirecting that command to ./foo help bar ).我可以手动执行method_option :help, ...并在bar方法中处理它,但我希望有一种更简单的方法来做到这一点(将该命令重定向到./foo help bar )。

Does anyone know a simple and easy way to do this?有谁知道一个简单易行的方法来做到这一点?

Assuming Foo is your class that inherits from Thor , you can call the following somewhere before Foo.start :假设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

Rather than going into Thor and patching some method to have different ARGV-parsing behavior, this kind of cheats by moving any help commands to the front of the list.与其进入 Thor 并修补某些方法以具有不同的 ARGV 解析行为,不如将任何帮助命令移动到列表的前面来作弊。

You can achive this with class_option .您可以使用class_option实现此class_option If you set a class option this option is availiable for every method in your cli and you can just check if it is set and then call the help method.如果您设置了类选项,则此选项可用于 cli 中的每个方法,您只需检查它是否已设置,然后调用帮助方法。

Something like this:像这样的东西:

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

Building on what @max-pleaner listed.以@max-pleaner 列出的内容为基础。 This will support subcommands also:这也将支持子命令:

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

To complement the answer from max pleaner, the following handles subcommands, because subcommands help is broken if the trick is applied to them.为了补充 max plener 的答案,以下处理子命令,因为如果将技巧应用于它们,子命令帮助就会被破坏。

Also, I choose to overload Thor start command.此外,我选择重载 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM