Module: Formatter

Defined in:
utils/formatter.rb

Overview

This module is part of an internal API. This module may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this module if possible, as it may be removed or changed without warning.

Helper module for formatting output.

Constant Summary collapse

COMMAND_DESC_WIDTH =

This constant is part of an internal API. This constant may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

80
OPTION_DESC_WIDTH =

This constant is part of an internal API. This constant may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

45

Class Method Summary collapse

Class Method Details

.arrow(string, color: nil) ⇒ String

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



15
16
17
# File 'utils/formatter.rb', line 15

def self.arrow(string, color: nil)
  prefix("==>", string, color)
end

.bold(string) ⇒ String

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Keep in sync with bold in Library/Homebrew/utils/formatter.sh.

Parameters:

Returns:



35
36
37
# File 'utils/formatter.rb', line 35

def self.bold(string)
  "#{Tty.bold}#{string}#{Tty.reset}"
end

.columns(objects, gap_size: 2, min_width: 0) ⇒ String

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Layout objects in columns that fit the current terminal width.

Parameters:

Returns:



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'utils/formatter.rb', line 174

def self.columns(objects, gap_size: 2, min_width: 0)
  objects = objects.flatten.map(&:to_s)

  fallback = proc do
    return objects.join("\n").concat("\n")
  end

  fallback.call if objects.empty?
  fallback.call unless $stdout.tty?

  console_width = Tty.width
  object_lengths = objects.map { |obj| Tty.strip_ansi(obj).length }
  max_length = [*object_lengths, min_width].max || 0
  cols = (console_width + gap_size) / (max_length + gap_size)

  fallback.call if cols < 2

  rows = (objects.count + cols - 1) / cols
  cols = (objects.count + rows - 1) / rows if min_width.zero? # 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 = T.cast(row_index.step(objects.size - 1, rows).to_a, T::Array[Integer])

    first_n = item_indices_for_row.first(item_indices_for_row.size - 1).map do |index|
      objects.fetch(index) + "".rjust(col_width - object_lengths.fetch(index))
    end

    # don't add trailing whitespace to last column
    last = objects.values_at(item_indices_for_row.fetch(-1))

    output.concat((first_n + last)
          .join(gap_string))
          .concat("\n")
  end

  output.freeze
end

.disk_usage_readable(size_in_bytes) ⇒ String

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



236
237
238
239
240
241
242
243
244
245
# File 'utils/formatter.rb', line 236

def self.disk_usage_readable(size_in_bytes)
  size, unit = disk_usage_readable_size_unit(size_in_bytes, precision: 1)
  size = size.round(1)
  # avoid trailing zero after decimal point
  if (size % 1).zero?
    "#{size.to_i}#{unit}"
  else
    "#{format("%<size>.1f", size:)}#{unit}"
  end
end

.disk_usage_readable_size_unit(size_in_bytes, precision: nil) ⇒ Array<([Integer, Float], String)>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • size_in_bytes (Integer, Float)
  • precision (Integer, nil) (defaults to: nil)

Returns:



223
224
225
226
227
228
229
230
231
232
233
# File 'utils/formatter.rb', line 223

def self.disk_usage_readable_size_unit(size_in_bytes, precision: nil)
  size = size_in_bytes
  unit = "B"
  %w[KB MB GB].each do |next_unit|
    break if (precision ? size.abs.round(precision) : size.abs) < 1000

    size /= 1000.0
    unit = next_unit
  end
  [size, unit]
end

.error(string, label: nil) ⇒ String

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Format a string as error, with an optional label.

Parameters:

  • string (String, Exception)
  • label (String, nil) (defaults to: nil)

Returns:



64
65
66
# File 'utils/formatter.rb', line 64

def self.error(string, label: nil)
  label(label, string, :red)
end

.format_help_text(string, width: 172) ⇒ String

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Wraps text to fit within a given number of columns using regular expressions that:

  1. convert hard-wrapped paragraphs to a single line
  2. add line break and indent to subcommand descriptions
  3. find any option descriptions longer than a pre-set length and wrap between words with a hanging indent, without breaking any words that overflow
  4. wrap any remaining description lines that need wrapping with the same indent
  5. wrap all lines to the given width.

Note that an option (e.g. --foo) may not be at the beginning of a line, so we always wrap one word before an option.



95
96
97
98
99
100
101
102
103
# File 'utils/formatter.rb', line 95

def self.format_help_text(string, width: 172)
  desc = OPTION_DESC_WIDTH
  indent = width - desc
  string.gsub(/(?<=\S) *\n(?=\S)/, " ")
        .gsub(/([`>)\]]:) /, "\\1\n    ")
        .gsub(/^( +-.+  +(?=\S.{#{desc}}))(.{1,#{desc}})(?: +|$)(?!-)\n?/, "\\1\\2\n#{" " * indent}")
        .gsub(/^( {#{indent}}(?=\S.{#{desc}}))(.{1,#{desc}})(?: +|$)(?!-)\n?/, "\\1\\2\n#{" " * indent}")
        .gsub(/(.{1,#{width}})(?: +|$)(?!-)\n?/, "\\1\n")
end

.headline(string, color: nil) ⇒ String

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Format a string as headline.

Keep in sync with headline in Library/Homebrew/utils/formatter.sh.

Parameters:

Returns:



24
25
26
# File 'utils/formatter.rb', line 24

def self.headline(string, color: nil)
  arrow("#{Tty.bold}#{string}#{Tty.reset}", color:)
end

.identifier(string) ⇒ String

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



29
30
31
# File 'utils/formatter.rb', line 29

def self.identifier(string)
  "#{Tty.green}#{string}#{Tty.default}"
end

.number_readable(number) ⇒ String

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



248
249
250
# File 'utils/formatter.rb', line 248

def self.number_readable(number)
  number.to_i.to_s.gsub(/(\d)(?=(?:\d{3})+\z)/, "\\1,")
end

.option(string) ⇒ String

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



40
41
42
# File 'utils/formatter.rb', line 40

def self.option(string)
  bold(string)
end

.redact_secrets(input, secrets) ⇒ String

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



253
254
255
256
257
# File 'utils/formatter.rb', line 253

def self.redact_secrets(input, secrets)
  secrets.compact
         .reduce(input) { |str, secret| str.gsub secret, "******" }
         .freeze
end

.success(string, label: nil) ⇒ String

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Format a string as success, with an optional label.

Parameters:

Returns:



48
49
50
# File 'utils/formatter.rb', line 48

def self.success(string, label: nil)
  label(label, string, :green)
end

.truncate(string, max: 30, omission: "...") ⇒ String

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Truncate a string to a specific length.

Parameters:

Returns:



72
73
74
75
76
77
78
79
# File 'utils/formatter.rb', line 72

def self.truncate(string, max: 30, omission: "...")
  return string if string.length <= max

  length_with_room_for_omission = max - omission.length
  truncated = string[0, length_with_room_for_omission]

  "#{truncated}#{omission}"
end

.url(string) ⇒ String

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • string (String, URI::Generic, nil)

Returns:



106
107
108
# File 'utils/formatter.rb', line 106

def self.url(string)
  "#{Tty.underline}#{string}#{Tty.no_underline}"
end

.version_changes(changes) ⇒ Array<String>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Align version changes into columns: name old -> new or name version, followed by the download size like (2.4MB) in its own column.

Parameters:

Returns:



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'utils/formatter.rb', line 134

def self.version_changes(changes)
  name_width = changes.map { |change| change.name.length }.max || 0
  separator = (changes.one? ? " " : "  ")
  old_width = changes.map { |change| (change.old_version || change.new_version).length }.max || 0
  new_width = changes.filter_map { |change| change.new_version.length if change.old_version }.max || 0
  # Keep full versions in redirected output or when the terminal width is unknown.
  if $stdout.tty? && Tty.width.positive?
    # Reserve space for names, separators, size parentheses and the upgrade arrow.
    available_width = Tty.width - name_width - separator.length
    size_width = changes.filter_map { |change| change.size&.length }.max
    size_parentheses_width = 2
    available_width -= size_width + size_parentheses_width + separator.length if size_width
    upgrade_arrow_width = 4
    available_width -= upgrade_arrow_width if new_width.positive?

    # Keep room for XXX.YYY.ZZZ plus "...", even if a very narrow terminal must wrap.
    minimum_version_width = 14
    # Share space evenly, letting a long version use space left by a short one.
    old_width = [old_width, [available_width - new_width, available_width / 2, minimum_version_width].max].min
    new_width = [available_width - old_width, minimum_version_width].max
  end

  versions = changes.map do |change|
    old_version = change.old_version
    next truncate(change.new_version, max: old_width) unless old_version

    "#{truncate(old_version, max: old_width).ljust(old_width)} -> #{truncate(change.new_version, max: new_width)}"
  end
  versions_width = versions.map(&:length).max || 0

  changes.each_with_index.map do |change, index|
    size = "(#{change.size})" if change.size
    [change.name.ljust(name_width), versions.fetch(index).ljust(versions_width), size].join(separator).rstrip
  end
end

.warning(string, label: nil) ⇒ String

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Format a string as warning, with an optional label.

Parameters:

  • string (String, Exception)
  • label (String, nil) (defaults to: nil)

Returns:



56
57
58
# File 'utils/formatter.rb', line 56

def self.warning(string, label: nil)
  label(label, string, :yellow)
end