brew/Library/Homebrew/utils/puts_columns.rb

42 lines
1.1 KiB
Ruby
Raw Normal View History

2016-10-02 04:11:43 +02:00
require "utils/tty"
module Kernel
2016-10-02 04:11:43 +02:00
def puts_columns(*objects, gap_size: 2)
objects.flatten!
2016-10-02 08:32:25 +02:00
fallback = proc do
2016-10-02 04:11:43 +02:00
puts(*objects)
return
end
2016-10-02 08:32:25 +02:00
fallback.call if objects.empty?
fallback.call if respond_to?(:tty?) ? !tty? : !$stdout.tty?
2016-10-02 04:11:43 +02:00
2016-10-02 08:32:25 +02:00
console_width = Tty.width
2016-10-02 04:11:43 +02:00
object_lengths = objects.map { |obj| Tty.strip_ansi(obj.to_s).length }
cols = (console_width + gap_size) / (object_lengths.max + gap_size)
2016-10-02 08:32:25 +02:00
fallback.call if cols < 2
2016-10-02 04:11:43 +02:00
rows = (objects.count + cols - 1) / cols
cols = (objects.count + rows - 1) / rows # avoid empty trailing columns
col_width = (console_width + gap_size) / cols - gap_size
gap_string = "".rjust(gap_size)
rows.times do |row_index|
item_indices_for_row = row_index.step(objects.size - 1, rows).to_a
first_n = item_indices_for_row[0...-1].map { |index|
objects[index] + "".rjust(col_width - object_lengths[index])
}
# don't add trailing whitespace to last column
last = objects.values_at(item_indices_for_row.last)
puts (first_n + last).join(gap_string)
end
end
end