繁体   English   中英

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

[英]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.

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