Class: WavefrontDisplay::Base

Inherits:
Object
  • Object
show all
Includes:
WavefrontCli::Constants
Defined in:
lib/wavefront-cli/display/base.rb

Overview

Print human-friendly output. If a command requires a dedicated handler to format its output, define a method with the same name as that which fetches the data, in a WavefrontDisplay class, extending this one.

We provide #long_output() and #multicolumn() methods to solve standard formatting problems. To use them, define a do_() method but rather than printing the output, have it call the method.

Constant Summary

Constants included from WavefrontCli::Constants

WavefrontCli::Constants::ALL_PAGE_SIZE, WavefrontCli::Constants::DEFAULT_OPTS, WavefrontCli::Constants::HUMAN_TIME_FORMAT, WavefrontCli::Constants::HUMAN_TIME_FORMAT_MS

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw_response, options = {}) ⇒ Base

Returns a new instance of Base.

Parameters:

  • raw_response (Map, Hash, Array)

    the data returned by the SDK response.

  • options (Hash) (defaults to: {})

    options from docopt



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/wavefront-cli/display/base.rb', line 23

def initialize(raw_response, options = {})
  @raw = raw_response

  data = if raw_response.respond_to?(:items)
           raw_response.items
         else
           raw_response
         end

  @data = data.is_a?(Map) ? Map(put_id_first(data)) : data
  @options = options
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



17
18
19
# File 'lib/wavefront-cli/display/base.rb', line 17

def data
  @data
end

#optionsObject (readonly)

Returns the value of attribute options.



17
18
19
# File 'lib/wavefront-cli/display/base.rb', line 17

def options
  @options
end

#rawObject (readonly)

Returns the value of attribute raw.



17
18
19
# File 'lib/wavefront-cli/display/base.rb', line 17

def raw
  @raw
end

Instance Method Details

#do_deleteObject



171
172
173
# File 'lib/wavefront-cli/display/base.rb', line 171

def do_delete
  puts "Deleted #{friendly_name} '#{options[:'<id>']}'."
end

#do_importObject



166
167
168
169
# File 'lib/wavefront-cli/display/base.rb', line 166

def do_import
  puts "Imported #{friendly_name}."
  long_output
end

#do_listObject

The following do_ methods are default handlers called following their namesake operation in the corresponding WavefrontCli class. They can be overriden in the inheriting class.



158
159
160
# File 'lib/wavefront-cli/display/base.rb', line 158

def do_list
  long_output
end

#do_list_briefObject



162
163
164
# File 'lib/wavefront-cli/display/base.rb', line 162

def do_list_brief
  multicolumn(:id, :name)
end

#do_queriesObject



223
224
225
226
227
228
229
# File 'lib/wavefront-cli/display/base.rb', line 223

def do_queries
  if options[:brief]
    multicolumn(:condition)
  else
    multicolumn(:id, :condition)
  end
end

#do_searchObject



191
192
193
194
195
196
197
# File 'lib/wavefront-cli/display/base.rb', line 191

def do_search
  if data.empty?
    puts 'No matches.'
  else
    long_output
  end
end

#do_search_briefObject



179
180
181
182
183
184
185
186
187
188
189
# File 'lib/wavefront-cli/display/base.rb', line 179

def do_search_brief
  display_keys = ([:id] + options[:'<condition>'].map do |c|
    c.split(/\W/, 2).first.to_sym
  end).uniq

  if data.empty?
    puts 'No matches.'
  else
    multicolumn(*display_keys)
  end
end

#do_tag_addObject



199
200
201
# File 'lib/wavefront-cli/display/base.rb', line 199

def do_tag_add
  puts "Tagged #{friendly_name} '#{options[:'<id>']}'."
end

#do_tag_clearObject



207
208
209
# File 'lib/wavefront-cli/display/base.rb', line 207

def do_tag_clear
  puts "Cleared tags on #{friendly_name} '#{options[:'<id>']}'."
end

#do_tag_deleteObject



203
204
205
# File 'lib/wavefront-cli/display/base.rb', line 203

def do_tag_delete
  puts "Deleted tag from #{friendly_name} '#{options[:'<id>']}'."
end

#do_tag_setObject



211
212
213
# File 'lib/wavefront-cli/display/base.rb', line 211

def do_tag_set
  puts "Set tags on #{friendly_name} '#{options[:'<id>']}'."
end

#do_tagsObject



215
216
217
218
219
220
221
# File 'lib/wavefront-cli/display/base.rb', line 215

def do_tags
  if data.empty?
    puts "No tags set on #{friendly_name} '#{options[:'<id>']}'."
  else
    data.sort.each { |t| puts t }
  end
end

#do_undeleteObject



175
176
177
# File 'lib/wavefront-cli/display/base.rb', line 175

def do_undelete
  puts "Undeleted #{friendly_name} '#{options[:'<id>']}'."
end

#drop_fields(*keys) ⇒ Nil

Modify, in-place, the data structure to remove fields which we deem not of interest to the user.

Parameters:

  • keys (Symbol)

    keys you do not wish to be shown.

Returns:

  • (Nil)


237
238
239
240
241
242
243
# File 'lib/wavefront-cli/display/base.rb', line 237

def drop_fields(*keys)
  if data.is_a?(Array)
    data.each { |i| i.delete_if { |k, _v| keys.include?(k.to_sym) } }
  else
    data.delete_if { |k, _v| keys.include?(k.to_sym) }
  end
end

#friendly_nameObject

return [String] the name of the thing we’re operating on, like

'alert' or 'dashboard'.


148
149
150
151
# File 'lib/wavefront-cli/display/base.rb', line 148

def friendly_name
  self.class.name.split('::').last.gsub(/([a-z])([A-Z])/, '\\1 \\2')
      .downcase
end

#human_time(time, force_utc = false) ⇒ Object

Make a time human-readable. Automatically deals with epoch seconds and epoch milliseconds

param t [Integer, String] a timestamp. If it’s a string, it is

converted to an int.

param force_utc [Boolean] force output in UTC. Currently only

used for unit tests.

return [String] a human-readable timestamp

Raises:

  • (ArgumentError)


275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/wavefront-cli/display/base.rb', line 275

def human_time(time, force_utc = false)
  raise ArgumentError unless time.is_a?(Numeric) || time.is_a?(String)

  return 'FOREVER' if time == -1

  str = time.to_s
  fmt, out_fmt = time_formats(str)
  # rubocop:disable Style/DateTime
  ret = DateTime.strptime(str, fmt).to_time
  # rubocop:enable Style/DateTime
  ret = force_utc ? ret.utc : ret.localtime
  ret.strftime(out_fmt)
end

#key_width(hash = {}, pad = 2) ⇒ Integer

Give it a key-value hash, and it will return the size of the first column to use when formatting that data.

Parameters:

  • hash (Hash) (defaults to: {})

    the data for which you need a column width

  • pad (Integer) (defaults to: 2)

    the number of spaces you want between columns

Returns:

  • (Integer)

    length of longest key + pad



140
141
142
143
# File 'lib/wavefront-cli/display/base.rb', line 140

def key_width(hash = {}, pad = 2)
  return 0 if hash.keys.empty?
  hash.keys.map(&:size).max + pad
end

#long_output(fields = nil, modified_data = nil) ⇒ Object

Default display method for ‘describe’ and long-list methods. Wraps around #_two_columns() giving you the chance to modify

Parameters:

  • fields (Array[Symbol]) (defaults to: nil)

    a list of fields you wish to display. If this is nil, all fields are displayed.

  • modified_data (Hash, Array) (defaults to: nil)

    lets you modify @data in-line. If this is truthy, it is used. Passing modified_data means that any fields parameter is ignored.



103
104
105
106
107
108
109
110
111
# File 'lib/wavefront-cli/display/base.rb', line 103

def long_output(fields = nil, modified_data = nil)
  if data.empty? || (modified_data && modified_data.empty?)
    puts 'No data.'
  else
    require_relative 'printer/long'
    puts WavefrontDisplayPrinter::Long.new(data, fields, modified_data)
    pagination_line
  end
end

#multicolumn(*columns) ⇒ Object



113
114
115
116
117
# File 'lib/wavefront-cli/display/base.rb', line 113

def multicolumn(*columns)
  require_relative 'printer/terse'
  puts WavefrontDisplayPrinter::Terse.new(data, *columns)
  pagination_line
end

#pagination_lineObject

if this is a section of a larger dataset, say so

rubocop:disable Metrics/AbcSize



122
123
124
125
126
127
128
129
130
# File 'lib/wavefront-cli/display/base.rb', line 122

def pagination_line
  return unless raw.respond_to?(:moreItems) && raw.moreItems == true

  enditem = raw.limit > 0 ? raw.offset + raw.limit - 1 : 0
  puts format('List shows items %d to %d. Use -o and -L for more.',
              raw.offset, enditem)
rescue StandardError
  puts 'List shows paginated output. Use -o and -L for more.'
end

#put_id_first(data) ⇒ Object

If the data contains an ‘id’ key, move it to the start.



89
90
91
# File 'lib/wavefront-cli/display/base.rb', line 89

def put_id_first(data)
  data.key?(:id) ? { id: data[:id] }.merge(data) : data
end

#readable_time(*keys) ⇒ Object

Modify, in-place, the @data structure to make times human-readable. Automatically handles second and millisecond epoch times. Currently only operates on top-level keys.

param keys [Symbol, Array] the keys you wish to be

turned into readable times.

return [Nil]



253
254
255
# File 'lib/wavefront-cli/display/base.rb', line 253

def readable_time(*keys)
  keys.each { |k| data[k] = human_time(data[k]) if data.key?(k) }
end

#readable_time_arr(*keys) ⇒ Object

As for #readable_time, but when @data is an array. For instance in “firing” alerts



260
261
262
263
264
# File 'lib/wavefront-cli/display/base.rb', line 260

def readable_time_arr(*keys)
  data.map do |row|
    keys.each { |k| row[k] = human_time(row[k]) if row.key?(k) }
  end
end

#run(method) ⇒ Object

find the correct method to deal with the output of the user’s command.



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/wavefront-cli/display/base.rb', line 39

def run(method)
  if method == 'do_list'
    run_list
  elsif method == 'do_search'
    run_search
  elsif respond_to?("#{method}_brief")
    send("#{method}_brief")
  elsif respond_to?(method)
    send(method)
  else
    long_output
  end
end

#run_error(method) ⇒ Object

Display classes can provide a do_method_code() method, which handles <code> errors when running do_method(). (Code is 404 etc.)

Parameters:

  • method (Symbol)

    the error method we wish to call



81
82
83
84
85
# File 'lib/wavefront-cli/display/base.rb', line 81

def run_error(method)
  return unless respond_to?(method)
  send(method)
  exit 1
end

#run_listObject

Choose the correct list handler. The user can specifiy a long listing with the –long options.



56
57
58
59
60
61
62
# File 'lib/wavefront-cli/display/base.rb', line 56

def run_list
  if options[:long]
    do_list
  else
    do_list_brief
  end
end

#run_searchObject

Choose the correct search handler. The user can specifiy a long listing with the –long options.



67
68
69
70
71
72
73
# File 'lib/wavefront-cli/display/base.rb', line 67

def run_search
  if options[:long]
    do_search
  else
    do_search_brief
  end
end

#time_formats(str) ⇒ String

How do we format a timestamp?

Parameters:

  • str (String)

    an epoch timestamp, as a string

Returns:

  • (String, String)

    DateTime formatter, strptime formatter



293
294
295
296
297
298
299
300
301
# File 'lib/wavefront-cli/display/base.rb', line 293

def time_formats(str)
  if str =~ /^\d{13}$/
    ['%Q', HUMAN_TIME_FORMAT_MS]
  elsif str =~ /^\d{10}$/
    ['%s', HUMAN_TIME_FORMAT]
  else
    raise ArgumentError
  end
end