2017-08-16 71 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