Class: Aspera::Cli::Formatter

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

Overview

Take care of CLI output on terminal

Constant Summary collapse

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



177
178
179
180
# File 'lib/aspera/cli/formatter.rb', line 177

def initialize
  @options = {}
  @spinner = nil
end

Class Method Details

.add_elements(stack, prefix, enum) ⇒ Object

Add elements of enumerator to the stack, in reverse order



130
131
132
133
134
# File 'lib/aspera/cli/formatter.rb', line 130

def add_elements(stack, prefix, enum)
  enum.reverse_each do |key, value|
    stack.push([add_prefix(prefix, key), value])
  end
end

.add_prefix(prefix, key) ⇒ Object

Build new prefix



125
126
127
# File 'lib/aspera/cli/formatter.rb', line 125

def add_prefix(prefix, key)
  [prefix, key].compact.join('.')
end

.all_but(list) ⇒ Object



170
171
172
173
# File 'lib/aspera/cli/formatter.rb', line 170

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

.check_row(row) ⇒ Object

for transfer spec table, build line for display in terminal used by spec_doc



61
62
63
64
65
# File 'lib/aspera/cli/formatter.rb', line 61

def check_row(row)
  row.each_key do |k|
    row[k] = row[k].map{ |i| WordWrap.ww(i.to_s, 120).chomp}.join("\n") if row[k].is_a?(Array)
  end
end

.enhance_display_values_hash(input_hash) ⇒ Object

replace empty values with a readable version on terminal



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/aspera/cli/formatter.rb', line 88

def enhance_display_values_hash(input_hash)
  stack = [input_hash]
  until stack.empty?
    current = stack.pop
    current.each do |key, value|
      case value
      when NilClass
        current[key] = special_format('null')
      when String
        current[key] = special_format('empty string') if value.empty?
      when Proc
        current[key] = special_format('lambda')
      when Array
        if value.empty?
          current[key] = special_format('empty list')
        else
          value.each do |item|
            stack.push(item) if item.is_a?(Hash)
          end
        end
      when Hash
        if value.empty?
          current[key] = special_format('empty dict')
        else
          stack.push(value)
        end
      end
    end
  end
end

.flatten_hash(input) ⇒ Object

Flatten a Hash into single level hash



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

def flatten_hash(input)
  Aspera.assert_type(input, Hash)
  return input if input.empty?
  flat = {}
  # tail (pop,push) contains the next element to display
  stack = [[nil, input]]
  until stack.empty?
    prefix, current = stack.pop
    # empty things will be displayed as such
    if current.respond_to?(:empty?) && current.empty?
      flat[prefix] = current
      next
    end
    case current
    when Hash
      add_elements(stack, prefix, current)
    when Array
      if current.none?{ |i| i.is_a?(Array) || i.is_a?(Hash)}
        flat[prefix] = list_to_string(current.map(&:to_s))
      elsif current.all?{ |i| i.is_a?(Hash) && i.keys == ['name']}
        flat[prefix] = list_to_string(current.map{ |i| i['name']})
      elsif current.all?{ |i| i.is_a?(Hash) && i.keys.sort == %w[name value]}
        add_elements(stack, prefix, current.each_with_object({}){ |i, h| h[i['name']] = i['value']})
      else
        add_elements(stack, prefix, current.each_with_index.map{ |v, i| [i, v]})
      end
    else
      flat[prefix] = current
    end
  end
  flat
end

.list_to_string(list) ⇒ Object

Given a list of string, display that list in a single cell



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

def list_to_string(list)
  list.join(',')
end

.markdown(match) ⇒ Object

used by spec_doc

Parameters:



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/aspera/cli/formatter.rb', line 69

def markdown(match)
  if match.is_a?(String)
    match = Markdown::FORMATS.match(match)
    Aspera.assert(match)
  end
  Aspera.assert_type(match, MatchData)
  if match[:entity]
    Aspera.assert_values(match[:entity], 'bsol')
    '\\'
  elsif match[:bold]
    match[:bold].to_s.blue
  elsif match[:code]
    match[:code].to_s.bold
  else
    Aspera.error_unexpected_value(match.to_s)
  end
end

.special_format(what) ⇒ Object

Highlight special values on terminal empty values are dim used by spec_doc



54
55
56
57
# File 'lib/aspera/cli/formatter.rb', line 54

def special_format(what)
  result = "<#{what}>"
  return %w[null empty].any?{ |s| what.include?(s)} ? result.dim : result.reverse_color
end

.tick(yes) ⇒ Object

nicer display for boolean used by spec_doc



40
41
42
43
44
45
46
47
48
49
# File 'lib/aspera/cli/formatter.rb', line 40

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

Instance Method Details

#declare_options(options) ⇒ Object



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/aspera/cli/formatter.rb', line 198

def declare_options(options)
  default_table_style = if Environment.terminal_supports_unicode?
    {border: :unicode_round}
  else
    {}
  end
  options.declare(:format, 'Output format', allowed: DISPLAY_FORMATS, handler: {o: self, m: :option_handler}, default: :table)
  options.declare(:output, 'Destination for results', handler: {o: self, m: :option_handler})
  options.declare(:display, 'Output only some information', allowed: DISPLAY_LEVELS, handler: {o: self, m: :option_handler}, default: :info)
  options.declare(
    :fields, "Comma separated list of: fields, or #{SpecialValues::ALL}, or #{SpecialValues::DEF}", handler: {o: self, m: :option_handler},
    allowed: [String, Array, Regexp, Proc],
    default: SpecialValues::DEF
  )
  options.declare(:select, 'Select only some items in lists: column, value', allowed: [Hash, Proc], handler: {o: self, m: :option_handler})
  options.declare(:table_style, '(Table) Display style', allowed: [Hash], handler: {o: self, m: :option_handler}, default: default_table_style)
  options.declare(:flat_hash, '(Table) Display deep values as additional keys', allowed: Allowed::TYPES_BOOLEAN, handler: {o: self, m: :option_handler}, default: true)
  options.declare(
    :multi_single, '(Table) Control how object list is displayed as single table, or multiple objects', allowed: %i[no yes single],
    handler: {o: self, m: :option_handler}, default: :no
  )
  options.declare(:show_secrets, 'Show secrets on command output', allowed: Allowed::TYPES_BOOLEAN, handler: {o: self, m: :option_handler}, default: false)
  options.declare(:image, 'Options for image display', allowed: Hash, handler: {o: self, m: :option_handler}, default: {})
end

#display_item_count(number, total) ⇒ Object



269
270
271
272
273
274
275
276
# File 'lib/aspera/cli/formatter.rb', line 269

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, hide_secrets: true) ⇒ 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



255
256
257
258
259
260
261
262
263
# File 'lib/aspera/cli/formatter.rb', line 255

def display_message(message_level, message, hide_secrets: true)
  message = SecretHider.instance.hide_secrets_in_string(message) if hide_secrets && message.is_a?(String) && hide_secrets?
  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) # rubocop:disable Style/StderrPuts
  else Aspera.error_unexpected_value(message_level)
  end
end

#display_results(type:, data: nil, total: nil, fields: nil, name: nil) ⇒ Object

this method displays the results, especially the table format

Parameters:

  • type (Symbol)

    type of data

  • data (Object) (defaults to: nil)

    data to display

  • total (Integer) (defaults to: nil)

    total number of items

  • fields (Array<String>) (defaults to: nil)

    list of fields to display

  • name (String) (defaults to: nil)

    name of the column to display



293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'lib/aspera/cli/formatter.rb', line 293

def display_results(type:, data: nil, total: nil, fields: nil, name: nil)
  Log.log.debug{"display_results: type=#{type} class=#{data.class}"}
  Log.log.trace1{"display_results: data=#{data}"}
  Aspera.assert_type(type, Symbol){'result must have type'}
  Aspera.assert(!data.nil? || %i[empty nothing].include?(type)){'result must have data'}
  display_item_count(data.length, total) unless total.nil?
  hide_secrets(data)
  data = SecretHider.instance.hide_secrets_in_string(data) if data.is_a?(String) && hide_secrets?
  @options[:format] = :image if type.eql?(:image)
  case @options[:format]
  when :text
    display_message(:data, data.to_s)
  when :nagios
    Nagios.process(data)
  when :ruby
    display_message(:data, PP.pp(filter_list_on_fields(data), +''))
  when :json
    display_message(:data, JSON.generate(filter_list_on_fields(data)))
  when :jsonpp
    display_message(:data, JSON.pretty_generate(filter_list_on_fields(data)))
  when :yaml
    display_message(:data, YAML.dump(filter_list_on_fields(data)))
  when :image
    # if object or list, then must be a single
    case type
    when :single_object, :object_list
      data = [data] if type.eql?(:single_object)
      raise BadArgument, 'image display requires a single result' unless data.length == 1
      fields = compute_fields(data, fields)
      raise BadArgument, 'select a single field to display' unless fields.length == 1
      data = data.first
      raise BadArgument, 'no such field' unless data.key?(fields.first)
      data = data[fields.first]
    end
    Aspera.assert_type(data, String){'URL or blob for image'}
    # Check if URL
    data =
      begin
        # just validate
        URI.parse(data)
        if Environment.instance.url_method.eql?(:text)
          UriReader.read(data)
        else
          Environment.instance.open_uri(data)
          display_message(:info, "Opened URL in browser: #{data}")
          :done
        end
      rescue URI::InvalidURIError
        data
      end
    # try base64
    data = begin
      Base64.strict_decode64(data)
    rescue
      data
    end
    # here, data is the image blob
    display_message(:data, Preview::Terminal.build(data, **@options[:image].symbolize_keys)) unless data.eql?(:done)
  when :table, :csv
    case type
    when :single_object
      # :single_object is a Hash, where key=column name
      Aspera.assert_type(data, Hash)
      if data.empty?
        display_message(:data, self.class.special_format('empty dict'))
      else
        data = self.class.flatten_hash(data) if @options[:flat_hash]
        display_table([data], compute_fields([data], fields), single: true)
      end
    when :object_list
      # :object_list is an Array of Hash, where key=column name
      Aspera.assert_array_all(data, Hash){'result'}
      data = data.map{ |obj| self.class.flatten_hash(obj)} if @options[:flat_hash]
      display_table(data, compute_fields(data, fields), single: type.eql?(:single_object))
    when :value_list
      # :value_list is a simple array of values, name of column provided in `name`
      display_table(data.map{ |i| {name => i}}, [name])
    when :special # no table
      if data.eql?(:nothing)
        Log.log.debug('no result expected')
        return
      end
      display_message(:info, self.class.special_format(data.to_s))
      return
    when :status # no table
      # :status displays a simple message
      display_message(:info, data)
    when :text # no table
      # :status displays a simple message
      display_message(:data, data)
    else Aspera.error_unexpected_value(type){'data type'}
    end
  else Aspera.error_unexpected_value(@options[:format]){'format'}
  end
end

#display_status(status, **kwargs) ⇒ Object



265
266
267
# File 'lib/aspera/cli/formatter.rb', line 265

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

#hide_secrets(data) ⇒ Object

hides secrets in Hash or Array



283
284
285
# File 'lib/aspera/cli/formatter.rb', line 283

def hide_secrets(data)
  SecretHider.instance.deep_remove_secret(data) if hide_secrets?
end

#hide_secrets?Boolean

Returns:

  • (Boolean)


278
279
280
# File 'lib/aspera/cli/formatter.rb', line 278

def hide_secrets?
  !@options[:show_secrets] && !@options[:display].eql?(:data)
end

#long_operation_running(title = '') ⇒ Object

call this after REST calls if several api calls are expected



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

def long_operation_running(title = '')
  return unless Environment.terminal?
  if @spinner.nil?
    @spinner = TTY::Spinner.new('[:spinner] :title', format: :classic)
    @spinner.start
  end
  @spinner.update(title: title)
  @spinner.spin
end

#long_operation_terminatedObject



193
194
195
196
# File 'lib/aspera/cli/formatter.rb', line 193

def long_operation_terminated
  @spinner&.stop
  @spinner = nil
end

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

method accessed by option manager options are: format, output, display, fields, select, table_style, flat_hash, multi_single



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

def option_handler(option_symbol, operation, value = nil)
  Aspera.assert_values(operation, %i[set get])
  case operation
  when :set
    @options[option_symbol] = value
    # special handling of some options
    case option_symbol
    when :output
      $stdout = if value.eql?('-')
        STDOUT # rubocop:disable Style/GlobalStdStream
      else
        File.open(value, 'w')
      end
    when :image
      # get list if key arguments of method
      allowed_options = Preview::Terminal.method(:build).parameters.select{ |i| i[0].eql?(:key)}.map{ |i| i[1]}
      # check that only supported options are given
      unknown_options = value.keys.map(&:to_sym) - allowed_options
      raise "Invalid parameter(s) for option image: #{unknown_options.join(', ')}, use #{allowed_options.join(', ')}" unless unknown_options.empty?
    end
  when :get then return @options[option_symbol]
  else Aspera.error_unreachable_line
  end
  nil
end