Class: Aspera::Cli::Formatter

Inherits:
Object
  • Object
show all
Defined in:
lib/aspera/cli/formatter.rb

Overview

Take care of output

Constant Summary collapse

FIELDS_LESS =
'-'
RESULT_PARAMS =
%i[type data total fields name].freeze
ERROR_FLASH =

prefix to display error messages in user messages (terminal)

'ERROR:'.bg_red.gray.blink.freeze
WARNING_FLASH =
'WARNING:'.bg_brown.black.blink.freeze
HINT_FLASH =
'HINT:'.bg_green.gray.blink.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeFormatter

initialize the formatter



156
157
158
# File 'lib/aspera/cli/formatter.rb', line 156

def initialize
  @options = {}
end

Class Method Details

.all_but(list) ⇒ Object



121
122
123
124
# File 'lib/aspera/cli/formatter.rb', line 121

def all_but(list)
  list = [list] unless list.is_a?(Array)
  return list.map{|i|"#{FIELDS_LESS}#{i}"}.unshift(ExtendedValue::ALL)
end

.auto_type(data) ⇒ Object



143
144
145
146
147
148
149
150
151
152
# File 'lib/aspera/cli/formatter.rb', line 143

def auto_type(data)
  result = {type: :other_struct, data: data}
  result[:type] = :single_object if result[:data].is_a?(Hash)
  if result[:data].is_a?(Array)
    if result[:data].all?(Hash)
      result[:type] = :object_list
    end
  end
  return result
end

.special(what, use_colors: $stdout.isatty) ⇒ Object

Highlight special values



109
110
111
112
113
114
115
116
117
118
119
# File 'lib/aspera/cli/formatter.rb', line 109

def special(what, use_colors: $stdout.isatty)
  result = $stdout.isatty ? "<#{what}>" : "&lt;#{what}&gt;"
  if use_colors
    result = if %w[null empty].any?{|s|what.include?(s)}
      result.dim
    else
      result.reverse_color
    end
  end
  return result
end

.tick(yes) ⇒ Object



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/aspera/cli/formatter.rb', line 126

def tick(yes)
  result =
    if Environment.use_unicode?
      if yes
        "\u2713"
      else
        "\u2717"
      end
    elsif yes
      'Y'
    else
      ' '
    end
  return result.green if yes
  return result.red
end

Instance Method Details

#all_fields(data) ⇒ Object



219
220
221
# File 'lib/aspera/cli/formatter.rb', line 219

def all_fields(data)
  data.each_with_object({}){|v, m|v.each_key{|c|m[c] = true}}.keys
end

#compute_fields(data, default) ⇒ Object

this method computes the list of fields to display data: array of hash default: list of fields to display by default (may contain special values)



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
262
# File 'lib/aspera/cli/formatter.rb', line 226

def compute_fields(data, default)
  Log.log.debug{"compute_fields: data:#{data.class} default:#{default.class} #{default}"}
  request =
    case @options[:fields]
    when NilClass then [ExtendedValue::DEF]
    when String then @options[:fields].split(',')
    when Array then @options[:fields]
    when Regexp then return all_fields(data).select{|i|i.match(@options[:fields])}
    when Proc then return all_fields(data).select{|i|@options[:fields].call(i)}
    else Aspera.error_unexpected_value(@options[:fields])
    end
  result = []
  until request.empty?
    item = request.shift
    removal = false
    if item[0].eql?(FIELDS_LESS)
      removal = true
      item = item[1..-1]
    end
    case item
    when ExtendedValue::ALL
      # get the list of all column names used in all lines, not just first one, as all lines may have different columns
      request.unshift(*all_fields(data))
    when ExtendedValue::DEF
      default = all_fields(data).select{|i|default.call(i)} if default.is_a?(Proc)
      default = all_fields(data) if default.nil?
      request.unshift(*default)
    else
      if removal
        result = result.reject{|i|i.eql?(item)}
      else
        result.push(item)
      end
    end
  end
  return result
end

#declare_options(options) ⇒ Object



178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/aspera/cli/formatter.rb', line 178

def declare_options(options)
  options.declare(:format, 'Output format', values: DISPLAY_FORMATS, handler: {o: self, m: :option_handler}, default: :table)
  options.declare(:output, 'Destination for results', types: String, handler: {o: self, m: :option_handler})
  options.declare(:display, 'Output only some information', values: DISPLAY_LEVELS, handler: {o: self, m: :option_handler}, default: :info)
  options.declare(
    :fields, "Comma separated list of: fields, or #{ExtendedValue::ALL}, or #{ExtendedValue::DEF}", handler: {o: self, m: :option_handler},
    types: [String, Array, Regexp, Proc],
    default: ExtendedValue::DEF)
  options.declare(:select, 'Select only some items in lists: column, value', types: [Hash, Proc], handler: {o: self, m: :option_handler})
  options.declare(:table_style, 'Table display style', handler: {o: self, m: :option_handler}, default: ':.:')
  options.declare(:flat_hash, 'Display deep values as additional keys', values: :bool, handler: {o: self, m: :option_handler}, default: true)
  options.declare(:transpose_single, 'Single object fields output vertically', values: :bool, handler: {o: self, m: :option_handler}, default: true)
  options.declare(:show_secrets, 'Show secrets on command output', values: :bool, handler: {o: self, m: :option_handler}, default: false)
end

#display_item_count(number, total) ⇒ Object



210
211
212
213
214
215
216
217
# File 'lib/aspera/cli/formatter.rb', line 210

def display_item_count(number, total)
  number = number.to_i
  total = total.to_i
  return if total.eql?(0) && number.eql?(0)
  count_msg = "Items: #{number}/#{total}"
  count_msg = count_msg.bg_red unless number.eql?(total)
  display_status(count_msg)
end

#display_message(message_level, message) ⇒ Object

main output method data: for requested data, not displayed if level==error info: additional info, displayed if level==info error: always displayed on stderr



197
198
199
200
201
202
203
204
# File 'lib/aspera/cli/formatter.rb', line 197

def display_message(message_level, message)
  case message_level
  when :data then $stdout.puts(message) unless @options[:display].eql?(:error)
  when :info then $stdout.puts(message) if @options[:display].eql?(:info)
  when :error then $stderr.puts(message)
  else Aspera.error_unexpected_value(message_level)
  end
end

#display_results(results) ⇒ Object

this method displays the results, especially the table format



311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'lib/aspera/cli/formatter.rb', line 311

def display_results(results)
  Aspera.assert_type(results, Hash)
  Aspera.assert((results.keys - RESULT_PARAMS).empty?){"result unsupported key: #{results.keys - RESULT_PARAMS}"}
  Aspera.assert(results.key?(:type)){"result must have type (#{results})"}
  Aspera.assert(results.key?(:data) || %i[empty nothing].include?(results[:type])){'result must have data'}
  Log.log.debug{"display_results: #{results[:data].class} #{results[:type]}"}
  display_item_count(results[:data].length, results[:total]) if results.key?(:total)
  SecretHider.deep_remove_secret(results[:data]) unless @options[:show_secrets] || @options[:display].eql?(:data)
  case @options[:format]
  when :text
    display_message(:data, results[:data].to_s)
  when :nagios
    Nagios.process(results[:data])
  when :ruby
    display_message(:data, PP.pp(results[:data], +''))
  when :json
    display_message(:data, JSON.generate(results[:data]))
  when :jsonpp
    display_message(:data, JSON.pretty_generate(results[:data]))
  when :yaml
    display_message(:data, results[:data].to_yaml)
  when :table, :csv
    case results[:type]
    when :config_over
      display_table(Flattener.new.config_over(results[:data]), CONF_OVERVIEW_KEYS)
    when :object_list, :single_object
      obj_list = results[:data]
      obj_list = [obj_list] if results[:type].eql?(:single_object)
      Aspera.assert_type(obj_list, Array)
      Aspera.assert(obj_list.all?(Hash)){"expecting Array of Hash: #{obj_list.inspect}"}
      # :object_list is an array of hash tables, where key=colum name
      obj_list = obj_list.map{|obj|Flattener.new.flatten(obj)} if @options[:flat_hash]
      display_table(obj_list, compute_fields(obj_list, results[:fields]))
    when :value_list
      # :value_list is a simple array of values, name of column provided in the :name
      display_table(results[:data].map { |i| { results[:name] => i } }, [results[:name]])
    when :empty # no table
      display_message(:info, Formatter.special('empty'))
      return
    when :nothing # no result expected
      Log.log.debug('no result expected')
    when :status # no table
      # :status displays a simple message
      display_message(:info, results[:data])
    when :text # no table
      # :status displays a simple message
      display_message(:data, results[:data])
    when :other_struct # no table
      # :other_struct is any other type of structure
      display_message(:data, PP.pp(results[:data], +''))
    else
      raise "unknown data type: #{results[:type]}"
    end
  end
end

#display_status(status) ⇒ Object



206
207
208
# File 'lib/aspera/cli/formatter.rb', line 206

def display_status(status)
  display_message(:info, status)
end

#display_table(object_array, fields) ⇒ Object

this method displays a table object_array: array of hash fields: list of column names



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/aspera/cli/formatter.rb', line 267

def display_table(object_array, fields)
  Aspera.assert(!fields.nil?){'missing fields parameter'}
  case @options[:select]
  when Proc
    object_array.select!{|i|@options[:select].call(i)}
  when Hash
    @options[:select].each{|k, v|object_array.select!{|i|i[k].eql?(v)}}
  end
  if object_array.empty?
    # no  display for csv
    display_message(:info, Formatter.special('empty')) if @options[:format].eql?(:table)
    return
  end
  if object_array.length == 1 && fields.length == 1
    display_message(:data, object_array.first[fields.first])
    return
  end
  # Special case if only one row (it could be object_list or single_object)
  if @options[:transpose_single] && object_array.length == 1
    new_columns = %i[key value]
    single = object_array.first
    object_array = fields.map { |i| new_columns.zip([i, single[i]]).to_h }
    fields = new_columns
  end
  Log.log.debug{Log.dump(:object_array, object_array)}
  # convert data to string, and keep only display fields
  final_table_rows = object_array.map { |r| fields.map { |c| r[c].to_s } }
  # here : fields : list of column names
  case @options[:format]
  when :table
    style = @options[:table_style].chars
    # display the table !
    display_message(:data, Terminal::Table.new(
      headings:  fields,
      rows:      final_table_rows,
      border_x:  style[0],
      border_y:  style[1],
      border_i:  style[2]))
  when :csv
    display_message(:data, final_table_rows.map{|t| t.join(CSV_FIELD_SEPARATOR)}.join(CSV_RECORD_SEPARATOR))
  end
end

#option_handler(option_symbol, operation, value = nil) ⇒ Object



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/aspera/cli/formatter.rb', line 160

def option_handler(option_symbol, operation, value=nil)
  Aspera.assert_values(operation, %i[set get])
  case operation
  when :set
    @options[option_symbol] = value
    if option_symbol.eql?(:output)
      $stdout = if value.eql?('-')
        STDOUT # rubocop:disable Style/GlobalStdStream
      else
        File.open(value, 'w')
      end
    end
  when :get then return @options[option_symbol]
  else Aspera.error_unreachable_line
  end
  nil
end