[ruby/irb] Fix column overflow on ls output

https://github.com/ruby/irb/commit/6115754623
This commit is contained in:
Takashi Kokubun 2021-03-20 23:15:51 -07:00 коммит произвёл git
Родитель 21863470d9
Коммит d0b044a842
1 изменённых файлов: 40 добавлений и 5 удалений

Просмотреть файл

@ -1,5 +1,6 @@
# frozen_string_literal: true
require "reline"
require_relative "nop"
require_relative "../color"
@ -23,8 +24,11 @@ module IRB
end
class Output
MARGIN = " "
def initialize(grep: nil)
@grep = grep
@line_width = screen_width
end
def dump(name, strs)
@ -32,13 +36,44 @@ module IRB
strs = strs.sort
return if strs.empty?
# Attempt a single line
print "#{Color.colorize(name, [:BOLD, :BLUE])}: "
if strs.size > 7
len = [strs.map(&:length).max, 16].min
puts; strs.each_slice(7) { |ss| puts " #{ss.map { |s| "%-#{len}s" % s }.join(" ")}" }
else
puts strs.join(" ")
if fits_on_line?(strs, cols: strs.size, offset: "#{name}: ".length)
puts strs.join(MARGIN)
return
end
puts
# Dump with the largest # of columns that fits on a line
cols = strs.size
until fits_on_line?(strs, cols: cols, offset: MARGIN.length) || cols == 1
cols -= 1
end
widths = col_widths(strs, cols: cols)
strs.each_slice(cols) do |ss|
puts ss.map.with_index { |s, i| "#{MARGIN}%-#{widths[i]}s" % s }.join
end
end
private
def fits_on_line?(strs, cols:, offset: 0)
width = col_widths(strs, cols: cols).sum + MARGIN.length * (cols - 1)
width <= @line_width - offset
end
def col_widths(strs, cols:)
cols.times.map do |col|
(col...strs.size).step(cols.size - 1).map do |i|
strs[i].length
end.max
end
end
def screen_width
Reline.get_screen_size.last
rescue Errno::EINVAL # in `winsize': Invalid argument - <STDIN>
79
end
end
private_constant :Output