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
62
63
# 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?
    if many?
      @layout = :columns

    else
      @layout = :rows
    end
  end

  if cols
    @cols = parse_cols(cols)

  else
    if @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
      fail "unsupported type #{@objects.class}"
    end
  end
end

Class Method Details

.format(*args, **kwargs) ⇒ String

Format data and return as string

Returns:

  • (String)


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

def self.format(*args, **kwargs)
  f = new(*args, **kwargs)
  f.format
end

Format data and print to standard output



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

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

Instance Method Details

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



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/libosctl/cli/output_formatter.rb', line 259

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

  @str_objects.each do |o|
    if @color
      len = Rainbow::StringUtils.uncolor(o[i].to_s).length
    else
      len = 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

      sprintf(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)

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

        else
          w = 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

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

#each_objectObject (protected)



287
288
289
290
291
292
293
294
# File 'lib/libosctl/cli/output_formatter.rb', line 287

def each_object
  if @objects.is_a?(::Array)
    @objects.each { |v| yield(v) }

  else
    yield(@objects)
  end
end

#formatString

Returns:

  • (String)


66
67
68
69
70
# File 'lib/libosctl/cli/output_formatter.rb', line 66

def format
  @out = ''
  generate
  @out
end

#generateObject (protected)



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

def generate
  return if @cols.empty?
  prepare

  case @layout
  when :columns
    columns

  when :rows
    rows

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

#heading_widthObject (protected)



275
276
277
278
279
280
281
282
283
284
285
# File 'lib/libosctl/cli/output_formatter.rb', line 275

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)



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

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

  else
    puts str
  end
end

#many?Boolean (protected)

Returns:

  • (Boolean)


296
297
298
# File 'lib/libosctl/cli/output_formatter.rb', line 296

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

#parse_cols(cols) ⇒ Object (protected)



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

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
      fail "unsupported column type #{c.class}"
    end
  end

  ret
end

#prepareObject (protected)



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

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 }
      fail "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


72
73
74
75
# File 'lib/libosctl/cli/output_formatter.rb', line 72

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
# 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..-1].map { |l| (' ' * (w+3)) + l }).join("\n")

      else
        v = o[i]
      end

      line sprintf("%#{w}s:  %s", c[:label], v)
    end

    line
  end
end