Class: OsCtl::Cli::OutputFormatter

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of OutputFormatter



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/osctl/cli/output_formatter.rb', line 15

def initialize(objects, cols = nil, header: true, sort: nil, layout: nil, empty: '-', color: false)
  @objects = objects
  @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) ⇒ Object



5
6
7
8
# File 'lib/osctl/cli/output_formatter.rb', line 5

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


10
11
12
13
# File 'lib/osctl/cli/output_formatter.rb', line 10

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

Instance Method Details

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



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/osctl/cli/output_formatter.rb', line 243

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.



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
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
# File 'lib/osctl/cli/output_formatter.rb', line 108

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)



271
272
273
274
275
276
277
278
# File 'lib/osctl/cli/output_formatter.rb', line 271

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

  else
    yield(@objects)
  end
end

#formatObject



52
53
54
55
56
# File 'lib/osctl/cli/output_formatter.rb', line 52

def format
  @out = ''
  generate
  @out
end

#generateObject (protected)



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/osctl/cli/output_formatter.rb', line 91

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)



259
260
261
262
263
264
265
266
267
268
269
# File 'lib/osctl/cli/output_formatter.rb', line 259

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)



195
196
197
198
199
200
201
202
# File 'lib/osctl/cli/output_formatter.rb', line 195

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

  else
    puts str
  end
end

#many?Boolean (protected)

Returns:

  • (Boolean)


280
281
282
# File 'lib/osctl/cli/output_formatter.rb', line 280

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

#parse_cols(cols) ⇒ Object (protected)



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/osctl/cli/output_formatter.rb', line 64

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,
      })
      ret << base

    elsif c.is_a?(::Hash)
      base.update(c)
      ret << base

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

  ret
end

#prepareObject (protected)



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/osctl/cli/output_formatter.rb', line 204

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


58
59
60
61
# File 'lib/osctl/cli/output_formatter.rb', line 58

def print
  @out = nil
  generate
end

#rowsObject (protected)

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



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/osctl/cli/output_formatter.rb', line 168

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