Class: OsCtl::Lib::Cli::OutputFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/libosctl/cli/output_formatter.rb

Overview

Format and print data in column or row view

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(objects, cols: nil, opts: {}, header: true, sort: nil, layout: nil, empty: '-', color: false) ⇒ OutputFormatter

Returns a new instance of OutputFormatter.

Parameters:

  • objects (Hash, Array)
  • cols (Array<Symbol, Hash>, nil) (defaults to: nil)

    a list of parameter names to show

  • opts (Hash<Symbol, Hash>) (defaults to: {})

    column options

  • header (Boolean) (defaults to: true)

    whether to show header

  • sort (Array<Symbol>, nil) (defaults to: nil)

    array of parameter names to sort by

  • layout (:columns, :rows) (defaults to: nil)
  • empty (String) (defaults to: '-')

    string used for nil values

  • color (Boolean) (defaults to: false)

    handle color escape sequences in formatted strings



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/libosctl/cli/output_formatter.rb', line 27

def initialize(objects, cols: nil, opts: {}, header: true, sort: nil, layout: nil, empty: '-', color: false)
  @objects = objects
  @opts = opts
  @header = header
  @sort = sort
  @layout = layout
  @empty = empty
  @color = color

  if @layout.nil?
    @layout = if many?
                :columns

              else
                :rows
              end
  end

  if cols
    @cols = parse_cols(cols)

  elsif @objects.is_a?(::Array) # A list of items
    if @objects.count == 0
      @cols = []
    else
      @cols ||= parse_cols(@objects.first.keys)
    end

  elsif @objects.is_a?(::Hash) # Single item
    @cols ||= parse_cols(@objects.keys)

  else
    raise "unsupported type #{@objects.class}"
  end
end

Class Method Details

Format data and print to standard output



14
15
16
17
# File 'lib/libosctl/cli/output_formatter.rb', line 14

def self.print(*, **)
  f = new(*, **)
  f.print
end

.to_sString

Format data and return as string

Returns:

  • (String)


8
9
10
11
# File 'lib/libosctl/cli/output_formatter.rb', line 8

def self.to_s(*, **)
  f = new(*, **)
  f.to_s
end

Instance Method Details

#col_width(i, c) ⇒ Object (protected)



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/libosctl/cli/output_formatter.rb', line 263

def col_width(i, c)
  w = c[:label].to_s.length

  @str_objects.each do |o|
    len = if @color
            Rainbow::StringUtils.uncolor(o[i].to_s).length
          else
            o[i].to_s.length
          end

    w = len if len > w
  end

  w + 1
end

#columnsObject (protected)

Each object is printed on one line, it’s parameters aligned into columns.



124
125
126
127
128
129
130
131
132
133
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
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/libosctl/cli/output_formatter.rb', line 124

def columns
  # Calculate column widths
  @cols.each_with_index do |c, i|
    c[:width] = col_width(i, c)
  end

  # Print header
  if @header
    line(@cols.map.with_index do |c, i|
      fmt =
        if i == (@cols.count - 1)
          '%s'
        elsif c[:align].to_sym == :right
          "%#{c[:width]}s"
        else
          "%-#{c[:width]}s"
        end

      format(fmt, c[:label])
    end.join('  '))
  end

  # Print data
  @str_objects.each do |o|
    line(@cols.map.with_index do |c, i|
      s = o[i].to_s

      if @color
        # If there are colors in the string, they affect the string size
        # and thus sprintf formatting. sprintf is working with characters
        # that the terminal will consume and not display (escape sequences).
        # The format string needs to be changed to accomodate for those
        # unprintable characters.
        s_nocolor = Rainbow::StringUtils.uncolor(s)

        w = if s_nocolor.length == s.length
              c[:width]

            else
              c[:width] + (s.length - s_nocolor.length)
            end
      else
        w = c[:width]
      end

      fmt =
        if i == (@cols.count - 1)
          '%s'
        elsif c[:align].to_sym == :right
          "%#{w}s"
        else
          "%-#{w}s"
        end

      format(fmt, s)
    end.join('  '))
  end
end

#each_objectObject (protected)



291
292
293
294
295
296
297
298
# File 'lib/libosctl/cli/output_formatter.rb', line 291

def each_object(&)
  if @objects.is_a?(::Array)
    @objects.each(&)

  else
    yield(@objects)
  end
end

#generateObject (protected)



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/libosctl/cli/output_formatter.rb', line 106

def generate
  return if @cols.empty?

  prepare

  case @layout
  when :columns
    columns

  when :rows
    rows

  else
    raise "unsupported layout '#{@layout}'"
  end
end

#heading_widthObject (protected)



279
280
281
282
283
284
285
286
287
288
289
# File 'lib/libosctl/cli/output_formatter.rb', line 279

def heading_width
  w = @cols.first[:label].to_s.length

  @cols.each do |c|
    len = c[:label].to_s.length

    w = len if len > w
  end

  w + 1
end

#line(str = '') ⇒ Object (protected)



213
214
215
216
217
218
219
220
# File 'lib/libosctl/cli/output_formatter.rb', line 213

def line(str = '')
  if @out
    @out += "#{str}\n"

  else
    puts str
  end
end

#many?Boolean (protected)

Returns:

  • (Boolean)


300
301
302
# File 'lib/libosctl/cli/output_formatter.rb', line 300

def many?
  @objects.is_a?(::Array) && @objects.size > 1
end

#parse_cols(cols) ⇒ Object (protected)



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/libosctl/cli/output_formatter.rb', line 77

def parse_cols(cols)
  ret = []

  cols.each do |c|
    base = {
      align: 'left'
    }

    if c.is_a?(::String) || c.is_a?(::Symbol)
      base.update({
        name: c,
        label: c.to_s.upcase
      })
      base.update(@opts.fetch(c, {}))
      ret << base

    elsif c.is_a?(::Hash)
      base.update(c)
      base.update(@opts.fetch(c[:name], {}))
      ret << base

    else
      raise "unsupported column type #{c.class}"
    end
  end

  ret
end

#prepareObject (protected)



222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/libosctl/cli/output_formatter.rb', line 222

def prepare
  @str_objects = []

  each_object do |o|
    arr = []

    @cols.each do |c|
      v = o[c[:name]]
      str = (c[:display] ? c[:display].call(v, o) : v)
      str = @empty if !str || (str.is_a?(::String) && str.empty?)

      arr << str
    end

    @str_objects << arr
  end

  if @sort
    col_indexes = @sort.map do |s|
      i = @cols.index { |c| c[:name] == s }
      raise "unknown sort column '#{s}'" unless i

      i
    end

    @str_objects.sort! do |a, b|
      a_vals = col_indexes.map { |i| a[i] }
      b_vals = col_indexes.map { |i| b[i] }
      cmp = a_vals <=> b_vals
      next(cmp) if cmp

      next(-1) if [nil, @empty].detect { |v| a_vals.include?(v) }
      next(1) if [nil, @empty].detect { |v| b_vals.include?(v) }

      0
    end
  end

  @str_objects
end


70
71
72
73
# File 'lib/libosctl/cli/output_formatter.rb', line 70

def print
  @out = nil
  generate
end

#rowsObject (protected)

Each object is printed on multiple lines, one parameter per line.



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
# File 'lib/libosctl/cli/output_formatter.rb', line 184

def rows
  w = heading_width if @header

  @str_objects.each do |o|
    @cols.each_index do |i|
      c = @cols[i]

      unless @header
        line o[i]
        next
      end

      if o[i].is_a?(::String) && o[i].index("\n")
        lines = o[i].split("\n")
        v = ([lines.first] + lines[1..].map { |l| (' ' * (w + 3)) + l }).join("\n")

      else
        v = o[i]
      end

      # rubocop:disable Lint/FormatParameterMismatch
      line format("%#{w}s:  %s", c[:label], v)
      # rubocop:enable Lint/FormatParameterMismatch
    end

    line
  end
end

#to_sString

Returns:

  • (String)


64
65
66
67
68
# File 'lib/libosctl/cli/output_formatter.rb', line 64

def to_s
  @out = ''
  generate
  @out
end