aboutsummaryrefslogtreecommitdiffstats
path: root/Library/Homebrew/utils
diff options
context:
space:
mode:
authorMarkus Reiter2016-10-02 04:11:43 +0200
committerMarkus Reiter2016-10-15 17:13:37 +0200
commit6e10f913714f195c2bbc77786f86342378243c1f (patch)
treeca7cf2531077efd2d1c6e67fd6eb96d43c46d76e /Library/Homebrew/utils
parent527a62b64bd8c578af08540166a8b1fd5bce521f (diff)
downloadbrew-6e10f913714f195c2bbc77786f86342378243c1f.tar.bz2
Refactor `puts_columns`.
Diffstat (limited to 'Library/Homebrew/utils')
-rw-r--r--Library/Homebrew/utils/puts_columns.rb49
1 files changed, 49 insertions, 0 deletions
diff --git a/Library/Homebrew/utils/puts_columns.rb b/Library/Homebrew/utils/puts_columns.rb
new file mode 100644
index 000000000..94a5354ad
--- /dev/null
+++ b/Library/Homebrew/utils/puts_columns.rb
@@ -0,0 +1,49 @@
+require "utils/tty"
+
+class IO
+ def puts_columns(*objects, gap_size: 2)
+ objects.flatten!
+
+ if objects.empty? || !tty?
+ puts(*objects)
+ return
+ end
+
+ console_width = Tty.width
+
+ object_lengths = objects.map { |obj| Tty.strip_ansi(obj.to_s).length }
+
+ cols = (console_width + gap_size) / (object_lengths.max + gap_size)
+
+ if cols < 2
+ puts(*objects)
+ return
+ end
+
+ 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
+
+module Kernel
+ def puts_columns(*objects)
+ $stdout.puts_columns(*objects)
+ end
+end