2017-08-16 54 views
1

当打印其帮助输出时,gem似乎总是按照字母顺序排列定义的命令。例如:Thor CLI:在帮助输出中设置命令的自定义顺序

#!/usr/bin/env ruby 

require "thor" 

class MyCLI < Thor 
    desc "z", "this should go first" 
    def z; end 

    desc "a", "this should go second" 
    def a; end 
end 

MyCLI.start(ARGV) 

保存该脚本thor-test并调用它不带参数给出了这样的输出:

Commands: 
    thor-test a    # this should go second 
    thor-test help [COMMAND] # Describe available commands or one specific command 
    thor-test z    # this should go first 

问:我怎么能告诉托尔以不同的方式订购条目?

回答

2

仿佛雷神不提供这样的配置选项。所以我现在就定下一些猴子补丁。 aristotll's answer指出我在托尔的source code正确的地方。

但是,我决定改变help方法的实现,而不是黑客方法<=>。这仍然清洁在我看来,有我可以进一步影响帮助输出行为的优势:

#!/usr/bin/env ruby 

require "thor" 

class MyCLI < Thor 
    class << self 
    def help(shell, subcommand = false) 
     list = printable_commands(true, subcommand) 
     Thor::Util.thor_classes_in(self).each do |klass| 
     list += klass.printable_commands(false) 
     end 

     # Remove this line to disable alphabetical sorting 
     # list.sort! { |a, b| a[0] <=> b[0] } 

     # Add this line to remove the help-command itself from the output 
     list.reject! {|l| l[0].split[1] == 'help'} 

     if defined?(@package_name) && @package_name 
     shell.say "#{@package_name} commands:" 
     else 
     shell.say "Commands:" 
     end 

     shell.print_table(list, :indent => 2, :truncate => true) 
     shell.say 
     class_options_help(shell) 

     # Add this line if you want to print custom text at the end of your help output. 
     # (similar to how Rails does it) 
     shell.say 'All commands can be run with -h (or --help) for more information.' 
    end 
    end 

    desc "z", "this should go first" 
    def z; end 

    desc "a", "this should go second" 
    def a; end 
end 

MyCLI.start(ARGV) 
2

helpsource code

list.sort! { |a, b| a[0] <=> b[0] } 

预期它是按字母顺序排序。


当然恶猴补丁总是允许,MyCLI之前添加以下代码。

SCRIPT = File.basename $PROGRAM_NAME 
class String 
    alias old_compare <=> 
    # @param [String] other_string 
    # @return [Fixnum] 
    def <=>(other_string) 
    # currently the command name is like `script_name+space+usage` 
    # a monkey patch to make z goes first 
    if other_string.start_with?(SCRIPT) 
     index = SCRIPT.size + 1 
     if other_string[index] == 'z' 
     return 1 
     elsif self[index] =='z' 
     return -1 
     end 
    end 
    old_compare other_string 
    end 
end 

输出:

Commands: 
    thor-test z    # this should go first 
    thor-test a    # this should go second 
    thor-test help [COMMAND] # Describe available commands or one specific command 
+1

你的猴子补丁是有点太邪恶了我;)我张贴了自己的解决方案,并接受了现在。但是非常感谢您将我指向源代码中的正确位置。 – thutt