Skip to content

Commit

Permalink
Merge pull request #642 from alessio-signorini/allow-to-override-comm…
Browse files Browse the repository at this point in the history
…ands-sorting

Allow to Override Order of Commands in Help
  • Loading branch information
rafaelfranca authored May 11, 2023
2 parents 8d85e2d + b2590c1 commit 91aa66f
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/thor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def help(shell, subcommand = false)
Thor::Util.thor_classes_in(self).each do |klass|
list += klass.printable_commands(false)
end
list.sort! { |a, b| a[0] <=> b[0] }
sort_commands!(list)

if defined?(@package_name) && @package_name
shell.say "#{@package_name} commands:"
Expand Down Expand Up @@ -495,6 +495,14 @@ def help(command = nil, subcommand = true); super; end
"
end
alias_method :subtask_help, :subcommand_help

# Sort the commands, lexicographically by default.
#
# Can be overridden in the subclass to change the display order of the
# commands.
def sort_commands!(list)
list.sort! { |a, b| a[0] <=> b[0] }
end
end

include Thor::Base
Expand Down
75 changes: 75 additions & 0 deletions spec/sort_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
require "helper"

describe Thor do
def shell
@shell ||= Thor::Base.shell.new
end

describe "#sort - default" do
my_script = Class.new(Thor) do
desc "a", "First Command"
def a; end

desc "z", "Last Command"
def z; end
end

before do
@content = capture(:stdout) { my_script.help(shell) }
end

it "sorts them lexicographillay" do
expect(@content).to match(/:a.+:help.+:z/m)
end
end


describe "#sort - simple override" do
my_script = Class.new(Thor) do
desc "a", "First Command"
def a; end

desc "z", "Last Command"
def z; end

def self.sort_commands!(list)
list.sort!
list.reverse!
end

end

before do
@content = capture(:stdout) { my_script.help(shell) }
end

it "sorts them in reverse" do
expect(@content).to match(/:z.+:help.+:a/m)
end
end


describe "#sort - simple override" do
my_script = Class.new(Thor) do
desc "a", "First Command"
def a; end

desc "z", "Last Command"
def z; end

def self.sort_commands!(list)
list.sort_by! do |a,b|
a[0] == :help ? -1 : a[0] <=> b[0]
end
end
end

before do
@content = capture(:stdout) { my_script.help(shell) }
end

it "puts help first then sorts them lexicographillay" do
expect(@content).to match(/:help.+:a.+:z/m)
end
end
end

0 comments on commit 91aa66f

Please sign in to comment.