Module: Morpheus::Cli::PrintHelper

Included in:
Credentials
Defined in:
lib/morpheus/cli/mixins/print_helper.rb

Constant Summary collapse

ALL_LABELS_UPCASE =
false

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



10
11
12
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 10

def self.included(klass)
  klass.send :include, Term::ANSIColor
end

.terminal_widthObject



14
15
16
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 14

def self.terminal_width
  @@terminal_width ||= 80
end

.terminal_width=(v) ⇒ Object



18
19
20
21
22
23
24
25
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 18

def self.terminal_width=(v)
  if v.nil? || v.to_i == 0
    @@terminal_width = nil
  else
    @@terminal_width = v.to_i
  end
  @@terminal_width
end

Instance Method Details

#anded_list(items) ⇒ Object



808
809
810
811
812
813
814
815
816
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 808

def anded_list(items)
  items = items ? items.clone : []
  last_item = items.pop
  if items.empty?
    return "#{last_item}"
  else
    return items.join(", ") + " and #{last_item}"
  end
end

#as_csv(data, columns, options = {}) ⇒ Object



696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 696

def as_csv(data, columns, options={})
  out = ""
  delim = options[:csv_delim] || options[:delim] || ","
  newline = options[:csv_newline] || options[:newline] || "\n"
  include_header = options[:csv_no_header] ? false : true
  do_quotes = options[:csv_quotes] || options[:quotes]

  column_defs = build_column_definitions(columns)
  #columns = columns.flatten.compact
  data_array = [data].flatten.compact

  if include_header
    headers = column_defs.collect {|column_def| column_def.label }
    if do_quotes
      headers = headers.collect {|it| quote_csv_value(it) }
    end
    out << headers.join(delim)
    out << newline
  end
  lines = []
  data_array.each do |obj|
    if obj
      cells = []
      column_defs.each do |column_def|
        label = column_def.label
        value = column_def.display_method.call(obj)
        # value = get_object_value(obj, column_def)
        if do_quotes
          cells << quote_csv_value(value)
        else
          cells << value.to_s
        end
      end
    end
    line = cells.join(delim)
    lines << line
  end
  out << lines.join(newline)
  #out << delim
  out

end

#as_description_list(obj, columns, opts = {}) ⇒ Object

as_description_list() prints a a two column table containing the name and value of a list of descriptions Usage: print_description_list([:id, :name, :status], my_instance, {})

Parameters:

  • columns
    • Hash or Array or Hashes

      list of column definitions, A column defintion can be a String, Symbol, Hash or Proc

  • obj (Object)

    an object to extract the data from, it is treated like a Hash.

  • opts (Map) (defaults to: {})

    rendering options for label :justify, :wrap



514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 514

def as_description_list(obj, columns, opts={})
  
  columns = build_column_definitions(columns)
  
  #label_width = opts[:label_width] || 10
  max_label_width = 0
  justify = opts.key?(:justify) ? opts[:justify] : "right"
  do_wrap = opts.key?(:wrap) ? !!opts[:wrap] : true
  color = opts.key?(:color) ? opts[:color] : cyan
  rows = []
  
  columns.flatten.each do |column_def|
    label = column_def.label
    label = label.upcase if ALL_LABELS_UPCASE
    # value = get_object_value(obj, column_def.display_method)
    value = column_def.display_method.call(obj)
    if label.size > max_label_width
      max_label_width = label.size
    end
    rows << {label: label, value: value}
  end
  label_width = max_label_width + 1 # for a leading space ' ' ..ew
  value_width = nil
  if Morpheus::Cli::PrintHelper.terminal_width
    value_width = Morpheus::Cli::PrintHelper.terminal_width - label_width
  end

  out = ""
  out << color if color
  rows.each do |row|
    value = row[:value].to_s
    if do_wrap
      if value_width && value_width < value.size
        wrap_indent = label_width + 1
        value = wrap(value, value_width, wrap_indent)
      end
    end
    out << format_dt_dd(row[:label], value, label_width, justify) + "\n"
  end
  out << reset if color
  return out
end

#as_json(data, options = {}, object_key = nil) ⇒ Object



762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 762

def as_json(data, options={}, object_key=nil)
  out = ""
  if !data
    return "null" # "No data"
  end

  if options[:include_fields]
    if object_key
      data[object_key] = filter_data(data[object_key], options[:include_fields])
    else
      data = filter_data(data, options[:include_fields])
    end
  end

  do_pretty = options.key?(:pretty_json) ? options[:pretty_json] : true
  if do_pretty
    out << JSON.pretty_generate(data)
  else
    out << JSON.fast_generate(data)
  end
  #out << "\n"
  out
end

#as_pretty_table(data, columns, options = {}) ⇒ String

as_pretty_table generates a table with aligned columns and truncated values. This can be used in place of TablePrint.tp() Usage: puts as_pretty_table(my_objects, [:id, :name])

puts as_pretty_table(my_objects, ["id", "name", {"plan" => "plan.name" }], {color: white})

Parameters:

  • data (Array)

    A list of objects to extract the data from.

  • columns
    • Array of Objects

      list of column definitions, A column definition can be a String, Symbol, or Hash

Returns:

  • (String)


409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 409

def as_pretty_table(data, columns, options={})
  data = [data].flatten
  columns = build_column_definitions(columns)

  table_color = options[:color] || cyan
  cell_delim = options[:delim] || " | "

  header_row = []
  
  columns.each do |column_def|
    header_row << column_def.label
  end

  # generate rows matrix data for the specified columns
  rows = []
  data.each do |row_data|
    row = []
    columns.each do |column_def|
      # r << column_def.display_method.respond_to?(:call) ? column_def.display_method.call(row_data) : get_object_value(row_data, column_def.display_method)
      value = column_def.display_method.call(row_data)        
      row << value
    end
    rows << row
  end

  # all rows (pre-formatted)
  data_matrix = [header_row] + rows

  # determine column meta info i.e. width    
  columns.each_with_index do |column_def, column_index|
    # column_def.meta = {
    #   max_value_size: (header_row + rows).max {|row| row[column_index] ? row[column_index].to_s.size : 0 }.size
    # }
    if column_def.fixed_width
      column_def.width = column_def.fixed_width.to_i
    else
      max_value_size = 0
      data_matrix.each do |row|
        v = row[column_index].to_s
        v_size = Term::ANSIColor.coloring? ? Term::ANSIColor.uncolored(v).size : v.size
        if v_size > max_value_size
          max_value_size = v_size
        end
      end

      max_width = (column_def.max_width.to_i > 0) ? column_def.max_width.to_i : nil
      min_width = (column_def.min_width.to_i > 0) ? column_def.min_width.to_i : nil
      if min_width && max_value_size < min_width
        column_def.width = min_width
      elsif max_width && max_value_size > max_width
        column_def.width = max_width
      else
        # expand / contract to size of the value by default
        column_def.width = max_value_size
      end
      #puts "DEBUG: #{column_index} column_def.width:  #{column_def.width}"
    end
  end

  # format header row
  header_cells = []
  columns.each_with_index do |column_def, column_index|
    value = header_row[column_index] # column_def.label
    header_cells << format_table_cell(value, column_def.width, column_def.justify)
  end
  
  # format header spacer row
  h_line = header_cells.collect {|cell| ("-" * cell.size) }.join(cell_delim.gsub(" ", "-"))
  
  # format data rows
  formatted_rows = []
  rows.each_with_index do |row, row_index|
    formatted_row = []
    row.each_with_index do |value, column_index|
      column_def = columns[column_index]
      formatted_row << format_table_cell(value, column_def.width, column_def.justify)
    end
    formatted_rows << formatted_row
  end
  
  

  table_str = ""
  table_str << header_cells.join(cell_delim) + "\n"
  table_str << h_line + "\n"
  formatted_rows.each do |row|
    table_str << row.join(cell_delim) + "\n"
  end

  out = ""
  out << table_color if table_color
  out << table_str
  out << reset if table_color
  out
end

#as_yaml(data, options = {}, object_key = nil) ⇒ Object



786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 786

def as_yaml(data, options={}, object_key=nil)
  out = ""
  if !data
    return "null" # "No data"
  end
  if options[:include_fields]
    if object_key
      data[object_key] = filter_data(data[object_key], options[:include_fields])
    else
      data = filter_data(data, options[:include_fields])
    end
  end
  begin
    out << data.to_yaml
  rescue => err
    puts "failed to render YAML from data: #{data.inspect}"
    puts err.message
  end
  #out << "\n"
  out
end

#build_column_definitions(*columns) ⇒ Array of OpenStruct

build_column_definitions constructs an Array of column definitions (OpenStruct) Each column is defined by a label (String), and a display_method (Proc)

Usage:

build_column_definitions(:id, :name)
build_column_definitions({"Object Id" => 'id'}, :name)
build_column_definitions({"ID" => 'id'}, "name", "plan.name", {status: lambda {|data| data['status'].upcase } })

Returns:

  • (Array of OpenStruct)

    list of column definitions (OpenStruct) like:

    “ID”, display_method: ‘id’, “Name”, display_method: Proc


574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 574

def build_column_definitions(*columns)
  # allow passing a single hash instead of an array of hashes
  if columns.size == 1 && columns[0].is_a?(Hash)
    columns = columns[0].collect {|k,v| {(k) => v} }
  else
    columns = columns.flatten.compact
  end
  results = []
  columns.each do |col|
    # determine label
    if col.is_a?(String)
      # supports "field as Label"
      field_key, field_label = col.split(/\s+as\s+/)
      if field_key && field_label
        k = field_label.strip
        v = field_key.strip
      else
        k = col.strip
        v = col.strip
      end
      build_column_definitions([{(k) => v}]).each do |r|
        results << r if r
      end
    elsif col.is_a?(Symbol)
      k = col.to_s.upcase #.capitalize
      v = col.to_s
      build_column_definitions([{(k) => v}]).each do |r|
        results << r if r
      end
    elsif col.is_a?(Hash)
      column_def = OpenStruct.new
      k, v = col.keys[0], col.values[0]
      if k.is_a?(String)
        column_def.label = k
      elsif k.is_a?(Symbol)
        column_def.label = k
      else
        column_def.label = k.to_s
        # raise "invalid column definition label (#{k.class}) #{k.inspect}. Should be a String or Symbol."
      end

      # determine display_method
      if v.is_a?(String)
        column_def.display_method = lambda {|data| get_object_value(data, v) }
      elsif v.is_a?(Symbol)
        column_def.display_method = lambda {|data| get_object_value(data, v) }
      elsif v.is_a?(Proc)
        column_def.display_method = v
      elsif v.is_a?(Hash) || v.is_a?(OStruct)
        if v[:display_name] || v[:label]
          column_def.label = v[:display_name] || v[:label]
        end
        if v[:display_method]
          if v[:display_method].is_a?(Proc)
            column_def.display_method = v[:display_method]
          else
            # assume v[:display_method] is a String, Symbol
            column_def.display_method = lambda {|data| get_object_value(data, v[:display_method]) }
          end
        else
          # the default behavior is to use the key (undoctored) to find the data
          # column_def.display_method = k
          column_def.display_method = lambda {|data| get_object_value(data, k) }
        end
        
        # other column rendering options
        column_def.justify = v[:justify]
        if v[:max_width]
          column_def.max_width = v[:max_width]
        end
        if v[:min_width]
          column_def.min_width = v[:min_width]
        end
        # tp uses width to behave like max_width
        if v[:width]
          column_def.width = v[:width]
          column_def.max_width = v[:width]
        end
        column_def.wrap = v[:wrap].nil? ? true :  v[:wrap] # only utlized in as_description_list() right now
        
      else
        raise "invalid column definition value (#{v.class}) #{v.inspect}. Should be a String, Symbol, Proc or Hash"
      end        

      # only upcase label for symbols, this is silly anyway, 
      # just pass the exact label (key) that you want printed..
      if column_def.label.is_a?(Symbol)
        column_def.label = column_def.label.to_s.upcase
      end

      results << column_def        

    else
      raise "invalid column definition (#{column_def.class}) #{column_def.inspect}. Should be a String, Symbol or Hash"
    end
    
  end

  return results
end

#current_terminal_widthObject



32
33
34
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 32

def current_terminal_width
  return IO.console.winsize[1] rescue 0
end

#format_available_options(option_types) ⇒ Object



309
310
311
312
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 309

def format_available_options(option_types)
  option_lines = option_types.collect {|it| "\t-O #{it['fieldContext'] ? it['fieldContext'] + '.' : ''}#{it['fieldName']}=\"value\"" }.join("\n")
  return "Available Options:\n#{option_lines}\n\n"
end

#format_boolean(v) ⇒ Object



688
689
690
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 688

def format_boolean(v)
  !!v ? 'Yes' : 'No'
end

#format_dt_dd(label, value, label_width = 10, justify = "right", do_wrap = true) ⇒ Object



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 314

def format_dt_dd(label, value, label_width=10, justify="right", do_wrap=true)
  # JD: uncomment next line to do away with justified labels
  # label_width, justify = 0, "none"
  out = ""
  value = value.to_s
  if do_wrap && value && Morpheus::Cli::PrintHelper.terminal_width
    value_width = Morpheus::Cli::PrintHelper.terminal_width - label_width
    if value_width > 0 && value.to_s.size > value_width
      wrap_indent = label_width + 1 # plus 1 needs to go away
      value = wrap(value, value_width, wrap_indent)
    end
  end
  if justify == "right"
    out << "#{label}:".rjust(label_width, ' ') + " #{value}" 
  elsif justify == "left"
    out << "#{label}:".ljust(label_width, ' ') + " #{value}" 
  else
    # default is none
    out << "#{label}:" + " #{value}" 
  end
  out
end

#format_results_pagination(json_response, options = {}) ⇒ Object



163
164
165
166
167
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 163

def format_results_pagination(json_response, options={})
  # no output for strange, empty data
  if json_response.nil? || json_response.empty?
    return ""
  end
  
  # options = OpenStruct.new(options) # laff, let's do this instead
  color = options.key?(:color) ? options[:color] : cyan
  label = options[:label]
  n_label = options[:n_label]
  # label = n_label if !label && n_label
  message = options[:message] || "Viewing %{start_index}-%{end_index} of %{total} %{label}"
  blank_message = options[:blank_message] || nil # "No %{label} found"

  # support lazy passing of common json_response {"meta": {"size": {25}, "total": 56} }
  # otherwise use the root values given
  meta = OpenStruct.new(json_response)
  if meta.meta
    meta = OpenStruct.new(meta.meta)
  end
  offset, size, total = meta.offset.to_i, meta.size.to_i, meta.total.to_i
  #objects = meta.objects || options[:objects_key] ? json_response[options[:objects_key]] : nil
  #objects ||= meta.instances || meta.servers || meta.users || meta.roles
  #size = objects.size if objects && size == 0
  if total == 0
    total = size
  end
  if total != 1
    label = n_label || label
  end
  out_str = ""
  string_key_values = {start_index: offset + 1, end_index: offset + size, total: total, size: size, offset: offset, label: label}
  if size > 0
    if message
      out_str << message % string_key_values
    end
  else
    if blank_message
      out_str << blank_message % string_key_values
    else
      #out << "No records"
    end
  end
  out = ""
  out << "\n"
  out << color if color
  out << out_str.strip
  out << reset if color
  out << "\n"
  out
end

#format_table_cell(value, width, justify = "left", pad_char = " ", suffix = "...") ⇒ Object



393
394
395
396
397
398
399
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 393

def format_table_cell(value, width, justify="left", pad_char=" ", suffix="...")
  #puts "format_table_cell(#{value}, #{width}, #{justify}, #{pad_char.inspect})"
  cell = value.to_s
  cell = truncate_string(cell, width, suffix)
  cell = justify_string(cell, width, justify, pad_char)
  cell
end

#generate_usage_bar(used_value, max_value, opts = {}) ⇒ Object

shows cyan, yellow, red progress bar where 50% looks like [||||| ] todo: render units used / available here too maybe



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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 222

def generate_usage_bar(used_value, max_value, opts={})
  opts[:bar_color] ||= :rainbow # :rainbow, :solid, or a color eg. cyan
  max_bars = opts[:max_bars] || 50
  out = ""
  bars = []
  percent = 0
  if max_value.to_i == 0
    percent = 0
  else
    percent = ((used_value.to_f / max_value.to_f) * 100)
  end
  percent_label = ((used_value.nil? || max_value.to_f == 0.0) ? "n/a" : "#{percent.round(2)}%").rjust(6, ' ')
  bar_display = ""
  if percent > 100
    max_bars.times { bars << "|" }
    # percent = 100
  else
    n_bars = ((percent / 100.0) * max_bars).ceil
    n_bars.times { bars << "|" }
  end

  if opts[:bar_color] == :rainbow
    rainbow_bar = ""
    cur_rainbow_color = white
    bars.each_with_index {|bar, i|
      reached_percent = (i / max_bars.to_f) * 100
      new_bar_color = cur_rainbow_color
      if reached_percent > 80
        new_bar_color = red
      elsif reached_percent > 50
        new_bar_color = yellow
      elsif reached_percent > 10
        new_bar_color = cyan
      end
      if cur_rainbow_color != new_bar_color
        cur_rainbow_color = new_bar_color
        rainbow_bar << cur_rainbow_color
      end
      rainbow_bar << bar
    }
    padding = max_bars - bars.size
    if padding > 0
      padding.times { rainbow_bar << " " }
      #rainbow_bar <<  " " * padding
    end
    rainbow_bar << reset
    bar_display = white + "[" + rainbow_bar + white + "]" + " #{cur_rainbow_color}#{percent_label}#{reset}"
    out << bar_display
  elsif opts[:bar_color] == :solid
    bar_color = cyan
    if percent > 80
      bar_color = red
    elsif percent > 50
      bar_color = yellow
    end
    bar_display = white + "[" + bar_color + bars.join.ljust(max_bars, ' ') + white + "]" + " #{percent_label}" + reset
    out << bar_display
  else
    bar_color = opts[:bar_color] || cyan
    bar_display = white + "[" + bar_color + bars.join.ljust(max_bars, ' ') + white + "]" + " #{percent_label}" + reset
    out << bar_display
  end
  return out
end

#justify_string(value, width, justify = "left", pad_char = " ") ⇒ String

justified returns a left, center, or right aligned string.

Parameters:

  • value (String)

    the string to pad

  • width (Integer)

    the length to truncate to

  • pad_char (String) (defaults to: " ")

    the character to pad with. Default is ‘ ’

Returns:

  • (String)


377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 377

def justify_string(value, width, justify="left", pad_char=" ")
  # JD: hack alert! this sux, but it's a best effort to preserve values containing ascii coloring codes
  value = value.to_s
  uncolored_value = Term::ANSIColor.coloring? ? Term::ANSIColor.uncolored(value.to_s) : value.to_s
  if value.size != uncolored_value.size
    width = width + (value.size - uncolored_value.size)
  end
  if justify == "right"
    return "#{value}".rjust(width, pad_char)
  elsif justify == "center"
    return "#{value}".center(width, pad_char)
  else
    return "#{value}".ljust(width, pad_char)
  end
end

print_description_list() is an alias for ‘print generate_description_list()`



558
559
560
561
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 558

def print_description_list(columns, obj, opts={})
  # raise "oh no.. replace with as_description_list()"
  print as_description_list(obj, columns, opts)
end


102
103
104
105
106
107
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
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 102

def print_dry_run(opts, command_string=nil)
  http_method = opts[:method]
  url = opts[:url]
  params = opts[:params]
  params = opts[:headers][:params] if opts[:headers] && opts[:headers][:params]
  query_string = params.respond_to?(:map) ? URI.encode_www_form(params) : query_string
  if query_string && !query_string.empty?
    url = "#{url}?#{query_string}"
  end
  request_string = "#{http_method.to_s.upcase} #{url}".strip
  payload = opts[:payload] || opts[:body]
  if command_string != false
    if command_string
      print_h1 "DRY RUN > #{command_string}"
    else
      print_h1 "DRY RUN"
    end
  end
  print cyan
  print "Request: ", "\n"
  print reset
  print request_string, "\n"
  print cyan
  if payload
    if payload.is_a?(String)
      begin
        payload = JSON.parse(payload)
      rescue => e
        #payload = "(unparsable) #{payload}"
      end
    end
    print "\n"
    if opts[:headers] && opts[:headers]['Content-Type'] == 'application/json'
      print "JSON: ", "\n"
      print reset
      print JSON.pretty_generate(payload)
    else
      print "Content-Type: #{opts[:headers]['Content-Type']}", "\n"
      #print "BODY: ", "\n"
      print reset
      if payload.is_a?(File)
        # pretty_size = Filesize.from("#{payload.size} B").pretty.strip
        pretty_size = "#{payload.size} B"
        # print "File: #{payload.path} (#{payload.size} bytes)"
        print "File: #{payload.path} (#{pretty_size})"
      elsif payload.is_a?(String)
        print payload
      else
        print payload.inspect
      end
    end
  end
  print "\n"
  print reset
end

puts green message to stdout



44
45
46
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 44

def print_green_success(msg)
  print "#{green}#{msg}#{reset}\n"
end

print_h1 prints a header title and optional subtitles Output:

title - subtitle1, subtitle2



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 54

def print_h1(title, subtitles=[], color=cyan)
  #print "\n" ,color, bold, title, (subtitles.empty? ? "" : " - #{subtitles.join(', ')}"), "\n", "==================", reset, "\n\n"
  subtitles = subtitles.flatten
  out = ""
  out << "\n"
  out << "#{color}#{bold}#{title}#{reset}"
  if !subtitles.empty?
    out << "#{color} | #{subtitles.join(', ')}#{reset}"
  end
  out << "\n"
  out << "#{color}#{bold}==================#{reset}"
  out << "\n\n"
  out << reset
  print out
end


70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 70

def print_h2(title, subtitles=[], color=cyan)
  #print "\n" ,color, bold, title, (subtitles.empty? ? "" : " - #{subtitles.join(', ')}"), "\n", "---------------------", reset, "\n\n"
  subtitles = subtitles.flatten
  out = ""
  out << "\n"
  out << "#{color}#{bold}#{title}#{reset}"
  if !subtitles.empty?
    out << "#{color} - #{subtitles.join(', ')}#{reset}"
  end
  out << "\n"
  out << "#{color}---------------------#{reset}"
  out << "\n\n"
  out << reset
  print out
end

puts red message to stderr



37
38
39
40
41
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 37

def print_red_alert(msg)
  #$stderr.print "#{red}#{msg}#{reset}\n"
  print "#{red}#{msg}#{reset}\n"
  #puts_error "#{red}#{msg}#{reset}"
end


94
95
96
97
98
99
100
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 94

def print_rest_errors(errors, options={})
  if respond_to?(:my_terminal)
    Morpheus::Cli::ErrorHandler.new(my_terminal.stderr).print_rest_errors(errors, options)
  else
    Morpheus::Cli::ErrorHandler.new.print_rest_errors(errors, options)
  end
end


86
87
88
89
90
91
92
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 86

def print_rest_exception(e, options={})
  if respond_to?(:my_terminal)
    Morpheus::Cli::ErrorHandler.new(my_terminal.stderr).print_rest_exception(e, options)
  else
    Morpheus::Cli::ErrorHandler.new.print_rest_exception(e, options)
  end
end


158
159
160
161
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 158

def print_results_pagination(json_response, options={})
  # print cyan,"\nViewing #{json_response['meta']['offset'].to_i + 1}-#{json_response['meta']['offset'].to_i + json_response['meta']['size'].to_i} of #{json_response['meta']['total']}\n", reset
  print format_results_pagination(json_response, options)
end


287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 287

def print_stats_usage(stats, opts={})
  label_width = opts[:label_width] || 10
  out = ""
  if stats.nil? || stats.empty?
    out << cyan + "No data." +  "\n" + reset
    print out
    return
  end
  opts[:include] ||= [:memory, :storage, :cpu]
  if opts[:include].include?(:cpu)
    cpu_usage = (stats['usedCpu'] || stats['cpuUsage'])
    out << cyan + "CPU".rjust(label_width, ' ') + ": " + generate_usage_bar(cpu_usage.to_f, 100)  + "\n"
  end
  if opts[:include].include?(:memory)
    out << cyan + "Memory".rjust(label_width, ' ') + ": " + generate_usage_bar(stats['usedMemory'], stats['maxMemory']) + cyan + Filesize.from("#{stats['usedMemory']} B").pretty.strip.rjust(15, ' ')           + " / " + Filesize.from("#{stats['maxMemory']} B").pretty.strip.ljust(15, ' ')  + "\n"
  end
  if opts[:include].include?(:storage)
    out << cyan + "Storage".rjust(label_width, ' ') + ": " + generate_usage_bar(stats['usedStorage'], stats['maxStorage']) + cyan + Filesize.from("#{stats['usedStorage']} B").pretty.strip.rjust(15, ' ') + " / " + Filesize.from("#{stats['maxStorage']} B").pretty.strip.ljust(15, ' ') + "\n"
  end
  print out
end

#quote_csv_value(v) ⇒ Object



692
693
694
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 692

def quote_csv_value(v)
  '"' + v.to_s.gsub('"', '""') + '"'
end

#records_as_csv(records, options = {}, default_columns = nil) ⇒ Object



739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 739

def records_as_csv(records, options={}, default_columns=nil)
  out = ""
  if !records
    #raise "records_as_csv expects records as an Array of objects to render"
    return out
  end
  cols = []
  all_fields = records.first ? records.first.keys : []
  if options[:include_fields]
    if options[:include_fields] == 'all' || options[:include_fields].include?('all')
      cols = all_fields
    else
      cols = options[:include_fields]
    end
  elsif default_columns
    cols = default_columns
  else
    cols = all_fields
  end
  out << as_csv(records, cols, options)
  out
end

#required_blue_promptObject



215
216
217
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 215

def required_blue_prompt
  "#{cyan}|#{reset}"
end

#sleep_with_dots(sleep_seconds, dots = 3, dot_chr = ".") ⇒ Object



818
819
820
821
822
823
824
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 818

def sleep_with_dots(sleep_seconds, dots=3, dot_chr=".")
  dot_interval = (sleep_seconds.to_f / dots.to_i)
  dots.to_i.times do |dot_index|
    sleep dot_interval
    print dot_chr
  end
end

#truncate_string(value, width, suffix = "...") ⇒ Object

truncate_string truncates a string and appends the suffix “…”

Parameters:

  • value (String)

    the string to pad

  • width (Integer)

    the length to truncate to

  • pad_char (String)

    the character to pad with. Default is ‘ ’



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
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 341

def truncate_string(value, width, suffix="...")
  value = value.to_s
  # JD: hack alerty.. this sux, but it's a best effort to preserve values containing ascii coloring codes
  #     it stops working when there are words separated by ascii codes, eg. two diff colors
  #     plus this is probably pretty slow...
  uncolored_value = Term::ANSIColor.coloring? ? Term::ANSIColor.uncolored(value.to_s) : value.to_s
  if uncolored_value != value
    trimmed_value = nil
    if uncolored_value.size > width
      if suffix
        trimmed_value = uncolored_value[0..width-(suffix.size+1)] + suffix
      else
        trimmed_value = uncolored_value[0..width-1]
      end
      return value.gsub(uncolored_value, trimmed_value)
    else
      return value
    end
  else
    if value.size > width
      if suffix
        return value[0..width-(suffix.size+1)] + suffix
      else
        return value[0..width-1]
      end
    else
      return value
    end
  end
end

#wrap(s, width, indent = 0) ⇒ Object



675
676
677
678
679
680
681
682
683
684
685
686
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 675

def wrap(s, width, indent=0)
  out = s
  if s.size > width
    if indent > 0
      out = s.gsub(/(.{1,#{width}})(\s+|\Z)/, "#{' ' * indent}\\1\n").strip
    else
      out = s.gsub(/(.{1,#{width}})(\s+|\Z)/, "\\1\n")
    end
  else
    return s
  end
end