diff --git a/lib/colorls/core.rb b/lib/colorls/core.rb index 5b385ac..bba18cc 100644 --- a/lib/colorls/core.rb +++ b/lib/colorls/core.rb @@ -92,6 +92,13 @@ module ColorLS def sort_contents case @sort + when :extension + @contents.sort_by! do |f| + name = f.name + ext = File.extname(name) + name = name.chomp(ext) unless ext.empty? + [ext, name].map { |s| CLocale.strxfrm(s) } + end when :time @contents.sort_by! { |a| -a.mtime.to_f } when :size diff --git a/lib/colorls/flags.rb b/lib/colorls/flags.rb index 4ba6663..03b49d2 100644 --- a/lib/colorls/flags.rb +++ b/lib/colorls/flags.rb @@ -76,15 +76,15 @@ module ColorLS options.on('-t', 'sort by modification time, newest first') { @opts[:sort] = :time } options.on('-U', 'do not sort; list entries in directory order') { @opts[:sort] = false } options.on('-S', 'sort by file size, largest first') { @opts[:sort] = :size } + options.on('-X', 'sort by file extension') { @opts[:sort] = :extension } options.on( '--sort=WORD', - %w[none time size], - 'sort by WORD instead of name: none, size (-S), time (-t)' + %w[none time size extension], + 'sort by WORD instead of name: none, size (-S), time (-t), extension (-X)' ) do |word| @opts[:sort] = case word when 'none' then false - when 'time' then :time - when 'size' then :size + else word.to_sym end end diff --git a/spec/color_ls/flags_spec.rb b/spec/color_ls/flags_spec.rb index 16cf19c..30b1e89 100644 --- a/spec/color_ls/flags_spec.rb +++ b/spec/color_ls/flags_spec.rb @@ -85,6 +85,12 @@ RSpec.describe ColorLS::Flags do it { is_expected.to match(/a-file.+z-file.+symlinks/) } # sorts results by size end + context 'with --sort=extension flag' do + let(:args) { ['--sort=extension', FIXTURES] } + + it { is_expected.to match(/a-file.+symlinks.+z-file.+a.md.+a.txt.+z.txt/) } # sorts results by extension + end + context 'with --dirs flag' do let(:args) { ['--dirs', FIXTURES] } diff --git a/spec/fixtures/a.md b/spec/fixtures/a.md new file mode 100644 index 0000000..e69de29 diff --git a/spec/fixtures/a.txt b/spec/fixtures/a.txt new file mode 100644 index 0000000..e69de29 diff --git a/spec/fixtures/z.txt b/spec/fixtures/z.txt new file mode 100644 index 0000000..e69de29 diff --git a/zsh/_colorls b/zsh/_colorls index 79b685f..3777b65 100644 --- a/zsh/_colorls +++ b/zsh/_colorls @@ -27,6 +27,7 @@ _arguments -s -S \ "-t[sort by modification time, newest first]" \ "-U[do not sort; list entries in directory order]" \ "-S[sort by file size, largest first]" \ + "-X[sort by file extension]" \ "--sort[sort by WORD instead of name: none, size (-S), time (-t)]" \ "-r[reverse order while sorting]" \ "--reverse[reverse order while sorting]" \