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