diff options
| author | Markus Reiter | 2016-10-15 18:51:11 +0200 |
|---|---|---|
| committer | GitHub | 2016-10-15 18:51:11 +0200 |
| commit | c233cacaf283a42940bdf3f607d82dab07d746a4 (patch) | |
| tree | 2c27248754a6c2b234adc7faae70e28c67ca0d17 /Library/Homebrew/utils | |
| parent | 527a62b64bd8c578af08540166a8b1fd5bce521f (diff) | |
| parent | 581a1245bf2c038a2f35fb10445592c7655108e3 (diff) | |
| download | brew-c233cacaf283a42940bdf3f607d82dab07d746a4.tar.bz2 | |
Merge pull request #1208 from reitermarkus/puts-columns
Refactor `puts_columns` to allow `$stderr.puts_columns`.
Diffstat (limited to 'Library/Homebrew/utils')
| -rw-r--r-- | Library/Homebrew/utils/formatter.rb | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/Library/Homebrew/utils/formatter.rb b/Library/Homebrew/utils/formatter.rb index cb4f041f4..a29a0d491 100644 --- a/Library/Homebrew/utils/formatter.rb +++ b/Library/Homebrew/utils/formatter.rb @@ -49,4 +49,45 @@ module Formatter end end private_class_method :prefix + + def columns(*objects, gap_size: 2) + objects = objects.flatten.map(&:to_s) + + fallback = proc do + return objects.join("\n").concat("\n") + end + + fallback.call if objects.empty? + fallback.call if respond_to?(:tty?) ? !tty? : !$stdout.tty? + + console_width = Tty.width + object_lengths = objects.map { |obj| Tty.strip_ansi(obj).length } + cols = (console_width + gap_size) / (object_lengths.max + gap_size) + + fallback.call if cols < 2 + + 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) + + output = "" + + 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) + + output.concat((first_n + last).join(gap_string)).concat("\n") + end + + output + end end |
