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
- #anded_list(items) ⇒ Object
- #as_csv(data, columns, options = {}) ⇒ Object
-
#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, {}).
- #as_json(data, options = {}, object_key = nil) ⇒ Object
-
#as_pretty_table(data, columns, options = {}) ⇒ String
as_pretty_table generates a table with aligned columns and truncated values.
- #as_yaml(data, options = {}, object_key = nil) ⇒ Object
-
#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).
- #current_terminal_width ⇒ Object
- #format_available_options(option_types) ⇒ Object
- #format_boolean(v) ⇒ Object
-
#format_curl_command(http_method, url, headers, payload = nil, options = {}) ⇒ Object
format_curl_command generates a valid curl command for the given api request formats command like:.
- #format_dt_dd(label, value, label_width = 10, justify = "right", do_wrap = true) ⇒ Object
- #format_results_pagination(json_response, options = {}) ⇒ Object
- #format_table_cell(value, width, justify = "left", pad_char = " ", suffix = "...") ⇒ Object
-
#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.
-
#justify_string(value, width, justify = "left", pad_char = " ") ⇒ String
justified returns a left, center, or right aligned string.
-
#print_description_list(columns, obj, opts = {}) ⇒ Object
print_description_list() is an alias for ‘print generate_description_list()`.
- #print_dry_run(api_request, options = {}) ⇒ Object
-
#print_green_success(msg) ⇒ Object
puts green message to stdout.
-
#print_h1(title, subtitles = nil, options = nil) ⇒ Object
print_h1 prints a header title and optional subtitles Output:.
- #print_h2(title, subtitles = nil, options = nil) ⇒ Object
-
#print_red_alert(msg) ⇒ Object
puts red message to stderr why this not stderr yet? use print_error or if respond_to?(:my_terminal).
- #print_rest_errors(errors, options = {}) ⇒ Object
- #print_rest_exception(e, options = {}) ⇒ Object
- #print_results_pagination(json_response, options = {}) ⇒ Object
- #print_stats_usage(stats, opts = {}) ⇒ Object
- #quote_csv_value(v) ⇒ Object
- #records_as_csv(records, options = {}, default_columns = nil) ⇒ Object
- #required_blue_prompt ⇒ Object
- #sleep_with_dots(sleep_seconds, dots = 3, dot_chr = ".") ⇒ Object
-
#truncate_string(value, width, suffix = "...") ⇒ Object
truncate_string truncates a string and appends the suffix “…”.
- #wrap(s, width, indent = 0) ⇒ Object
Class Method Details
.included(klass) ⇒ Object
11 12 13 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 11 def self.included(klass) klass.send :include, Term::ANSIColor end |
.terminal_width ⇒ Object
15 16 17 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 15 def self.terminal_width @@terminal_width ||= 80 end |
.terminal_width=(v) ⇒ Object
19 20 21 22 23 24 25 26 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 19 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
1024 1025 1026 1027 1028 1029 1030 1031 1032 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 1024 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
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 912 def as_csv(data, columns, ={}) out = "" delim = [:csv_delim] || [:delim] || "," newline = [:csv_newline] || [:newline] || "\n" include_header = [:csv_no_header] ? false : true do_quotes = [:csv_quotes] || [: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, {})
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 730 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
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 978 def as_json(data, ={}, object_key=nil) out = "" if !data return "null" # "No data" end if [:include_fields] if object_key data[object_key] = filter_data(data[object_key], [:include_fields]) else data = filter_data(data, [:include_fields]) end end do_pretty = .key?(:pretty_json) ? [: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})
567 568 569 570 571 572 573 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 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 567 def as_pretty_table(data, columns, ={}) data = [data].flatten columns = build_column_definitions(columns) table_color = [:color] || cyan cell_delim = [: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 # responsive tables # pops columns off end until they all fit on the terminal # could use some options[:preferred_columns] logic here to throw away in some specified order # --all fields disables this trimmed_columns = [] if [:responsive_table] != false && [:include_fields].nil? && [:all_fields] != true begin term_width = current_terminal_width() table_width = columns.inject(0) {|acc, column_def| acc + (column_def.width || 0) } table_width += ((columns.size-0) * (3)) # col border width if term_width && table_width # leave 1 column always... while table_width > term_width && columns.size > 1 column_index = columns.size - 1 removed_column = columns.pop trimmed_columns << removed_column if removed_column.width table_width -= removed_column.width table_width -= 3 # col border width end # clear from data_matrix # wel, nvm it just gets regenerated end end rescue => ex Morpheus::Logging::DarkPrinter.puts "Encountered error while applying responsive table sizing: (#{ex.class}) #{ex}" end if trimmed_columns.size > 0 # data_matrix = generate_table_data(data, columns, options) header_row = [] columns.each do |column_def| header_row << column_def.label end 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 data_matrix = [header_row] + rows 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 if [:border_style] == :thin # a simpler looking table cell_delim = " " h_line = header_cells.collect {|cell| ("-" * cell.strip.size).ljust(cell.size, ' ') }.join(cell_delim) else # default border style h_line = header_cells.collect {|cell| ("-" * cell.size) }.join(cell_delim.gsub(" ", "-")) end # 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
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 1002 def as_yaml(data, ={}, object_key=nil) out = "" if !data return "null" # "No data" end if [:include_fields] if object_key data[object_key] = filter_data(data[object_key], [:include_fields]) else data = filter_data(data, [:include_fields]) end end begin out << data.to_yaml rescue => err puts "failed to render YAML from data: #{data.inspect}" puts err. 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 } })
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 790 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, but tp() is gone, remove this? 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_width ⇒ Object
33 34 35 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 33 def current_terminal_width return IO.console.winsize[1] rescue 0 end |
#format_available_options(option_types) ⇒ Object
467 468 469 470 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 467 def (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
904 905 906 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 904 def format_boolean(v) !!v ? 'Yes' : 'No' end |
#format_curl_command(http_method, url, headers, payload = nil, options = {}) ⇒ Object
format_curl_command generates a valid curl command for the given api request formats command like:
curl -XPOST “api.gomorpheus.com/api/cypher” \
-H "Authorization: BEARER ******************" \
-H "Content-Type: application/json" \
-d '{
"value": "mysecret"
}'
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 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 251 def format_curl_command(http_method, url, headers, payload=nil, ={}) ||= {} # build curl [options] out = "" out << "curl -X#{http_method.to_s.upcase} '#{url}'" if headers headers.each do |k,v| # avoid weird [:headers][:params] unless k == :params header_value = v out << ' \\' + "\n" header_line = " -H \"#{k.is_a?(Symbol) ? k.to_s.capitalize : k.to_s}: #{v}\"" out << header_line end end end if payload && !payload.empty? out << + ' \\' + "\n" if headers && headers['Content-Type'] == 'application/json' if payload.is_a?(String) begin payload = JSON.parse(payload) rescue => e #payload = "(unparsable) #{payload}" end end if payload.is_a?(Hash) out << " -d '#{as_json(payload, options)}'" else out << " -d '#{payload}'" end else content_type = headers['Content-Type'] || 'application/x-www-form-urlencoded' 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)" out << " -d @#{payload.path}" elsif payload.is_a?(String) out << " -d '#{payload}'" else if content_type == 'application/x-www-form-urlencoded' body_str = payload.to_s begin body_str = URI.encode_www_form(payload) rescue => ex # raise ex end out << " -d '#{body_str}'" else out << " -d '#{payload}'" end end end out << "\n" else out << "\n" end if [:scrub] out = Morpheus::Logging.(out) end return out end |
#format_dt_dd(label, value, label_width = 10, justify = "right", do_wrap = true) ⇒ Object
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 472 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
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 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 321 def format_results_pagination(json_response, ={}) # 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 = .key?(:color) ? [:color] : cyan label = [:label] n_label = [:n_label] # label = n_label if !label && n_label = [:message] || "Viewing %{start_index}-%{end_index} of %{total} %{label}" = [:blank_message] || nil # "No %{label} found" # support lazy passing of common json_response {"meta": {"size": {25}, "total": 56} } # otherwise use the root values given = OpenStruct.new(json_response) if . = OpenStruct.new(.) end offset, size, total = .offset.to_i, .size.to_i, .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: format_number(offset + 1), end_index: format_number(offset + size), total: format_number(total), size: format_number(size), offset: format_number(offset), label: label} if size > 0 if out_str << % string_key_values end else if out_str << % 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
551 552 553 554 555 556 557 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 551 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
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 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 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 380 def (used_value, max_value, opts={}) opts[:bar_color] ||= :rainbow # :rainbow, :solid, or a color eg. cyan = opts[:max_bars] || 50 out = "" = [] 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, ' ') = "" if percent > 100 .times { << "|" } # percent = 100 else = ((percent / 100.0) * ).ceil .times { << "|" } end if opts[:bar_color] == :rainbow = "" cur_rainbow_color = white .each_with_index {|, i| reached_percent = (i / .to_f) * 100 = cur_rainbow_color if reached_percent > 80 = red elsif reached_percent > 50 = yellow elsif reached_percent > 10 = cyan end if cur_rainbow_color != cur_rainbow_color = << cur_rainbow_color end << } padding = - .size if padding > 0 padding.times { << " " } #rainbow_bar << " " * padding end << reset = white + "[" + + white + "]" + " #{cur_rainbow_color}#{percent_label}#{reset}" out << elsif opts[:bar_color] == :solid = cyan if percent > 80 = red elsif percent > 50 = yellow end = white + "[" + + .join.ljust(, ' ') + white + "]" + " #{percent_label}" + reset out << else = opts[:bar_color] || cyan = white + "[" + + .join.ljust(, ' ') + white + "]" + " #{percent_label}" + reset out << end return out end |
#justify_string(value, width, justify = "left", pad_char = " ") ⇒ String
justified returns a left, center, or right aligned string.
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 535 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(columns, obj, opts = {}) ⇒ Object
print_description_list() is an alias for ‘print generate_description_list()`
774 775 776 777 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 774 def print_description_list(columns, obj, opts={}) # raise "oh no.. replace with as_description_list()" print as_description_list(obj, columns, opts) end |
#print_dry_run(api_request, options = {}) ⇒ Object
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 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 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 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 127 def print_dry_run(api_request, ={}) # 2nd argument used to be command_string (String) command_string = nil if .is_a?(String) command_string = = {} end ||= {} # api client injects common command options here if api_request[:command_options] = .merge(api_request[:command_options]) end ||= {} # parse params request arguments http_method = api_request[:method] url = api_request[:url] headers = api_request[:headers] params = nil if api_request[:params] && !api_request[:params].empty? params = api_request[:params] elsif api_request[:headers] && api_request[:headers][:params] # params inside headers for restclient reasons.. params = api_request[:headers][:params] elsif api_request[:query] && !api_request[:query].empty? params = api_request[:query] end query_string = params if query_string.respond_to?(:map) query_string = URI.encode_www_form(query_string) end if query_string && !query_string.empty? url = "#{url}?#{query_string}" end request_string = "#{http_method.to_s.upcase} #{url}".strip payload = api_request[:payload] || api_request[:body] #Morpheus::Logging::DarkPrinter.puts "API payload is: (#{payload.class}) #{payload.inspect}" # curl output? if api_request[:curl] || [:curl] print "\n" puts "#{cyan}#{bold}#{dark}CURL COMMAND#{reset}\n" print format_curl_command(http_method, url, headers, payload, ) print "\n" return end # print this thing: # REQUEST: # POST http://morpheusdata.com/api/whoami # f it..removing this, just DRY RUN printed at the start of command print "\n" # if command_string != false # if command_string # print_h1 "DRY RUN > #{command_string}" # else # #print "\n" # #print_h1 "DRY RUN" # end # end puts "#{cyan}#{bold}#{dark}REQUEST#{reset}\n" # print cyan # print "Request: ", "\n" # print reset request_string = "#{http_method.to_s.upcase} #{url}".strip print request_string, "\n" print cyan if payload print "\n" if api_request[:headers] && api_request[:headers]['Content-Type'] == 'application/json' if payload.is_a?(String) begin payload = JSON.parse(payload) rescue => e #payload = "(unparsable) #{payload}" end end puts "#{cyan}#{bold}#{dark}JSON#{reset}\n" # print "JSON: ", "\n" # print reset print JSON.pretty_generate(payload) else content_type = api_request[:headers]['Content-Type'] || 'application/x-www-form-urlencoded' print "Content-Type: #{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 if content_type == 'application/x-www-form-urlencoded' body_str = payload.to_s begin body_str = URI.encode_www_form(payload) rescue => ex # raise ex end print body_str else print payload end end end end print "\n" print reset end |
#print_green_success(msg) ⇒ Object
puts green message to stdout
46 47 48 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 46 def print_green_success(msg) print "#{green}#{msg}#{reset}\n" end |
#print_h1(title, subtitles = nil, options = nil) ⇒ Object
print_h1 prints a header title and optional subtitles Output:
title - subtitle1, subtitle2
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 56 def print_h1(title, subtitles=nil, =nil) # ok, support all these formats for now: # print_h1(title, options={}) # print_h1(title, subtitles, options={}) # this can go away when we have a dirty @current_options if subtitles.is_a?(Hash) = subtitles subtitles = ([:subtitles] || []).flatten end subtitles = (subtitles || []).flatten ||= {} color = [:color] || cyan out = "" out << "\n" out << "#{color}#{bold}#{title}#{reset}" if !subtitles.empty? out << "#{color} | #{subtitles.join(', ')}#{reset}" end out << "\n" if [:border_style] == :thin out << "\n" else out << "#{color}#{bold}==================#{reset}\n\n" end print out end |
#print_h2(title, subtitles = nil, options = nil) ⇒ Object
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 83 def print_h2(title, subtitles=nil, =nil) # ok, support all these formats for now: # print_h2(title={}) # print_h2(title, options={}) # print_h2(title, subtitles, options={}) # this can go away when we have a dirty @current_options if subtitles.is_a?(Hash) = subtitles subtitles = ([:subtitles] || []).flatten end subtitles = (subtitles || []).flatten ||= {} color = [:color] || cyan out = "" out << "\n" out << "#{color}#{bold}#{title}#{reset}" if !subtitles.empty? out << "#{color} - #{subtitles.join(', ')}#{reset}" end out << "\n" if [:border_style] == :thin out << "\n" else out << "#{color}---------------------#{reset}\n\n" end print out end |
#print_red_alert(msg) ⇒ Object
puts red message to stderr why this not stderr yet? use print_error or if respond_to?(:my_terminal)
39 40 41 42 43 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 39 def print_red_alert(msg) #$stderr.print "#{red}#{msg}#{reset}\n" print "#{red}#{msg}#{reset}\n" #puts_error "#{red}#{msg}#{reset}" end |
#print_rest_errors(errors, options = {}) ⇒ Object
119 120 121 122 123 124 125 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 119 def print_rest_errors(errors, ={}) if respond_to?(:my_terminal) Morpheus::Cli::ErrorHandler.new(my_terminal.stderr).print_rest_errors(errors, ) else Morpheus::Cli::ErrorHandler.new.print_rest_errors(errors, ) end end |
#print_rest_exception(e, options = {}) ⇒ Object
111 112 113 114 115 116 117 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 111 def print_rest_exception(e, ={}) if respond_to?(:my_terminal) Morpheus::Cli::ErrorHandler.new(my_terminal.stderr).print_rest_exception(e, ) else Morpheus::Cli::ErrorHandler.new.print_rest_exception(e, ) end end |
#print_results_pagination(json_response, options = {}) ⇒ Object
316 317 318 319 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 316 def print_results_pagination(json_response, ={}) # 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, ) end |
#print_stats_usage(stats, opts = {}) ⇒ Object
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 445 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, ' ') + ": " + (cpu_usage.to_f, 100) + "\n" end if opts[:include].include?(:memory) out << cyan + "Memory".rjust(label_width, ' ') + ": " + (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, ' ') + ": " + (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
908 909 910 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 908 def quote_csv_value(v) '"' + v.to_s.gsub('"', '""') + '"' end |
#records_as_csv(records, options = {}, default_columns = nil) ⇒ Object
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 955 def records_as_csv(records, ={}, 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 [:include_fields] if [:include_fields] == 'all' || [:include_fields].include?('all') cols = all_fields else cols = [:include_fields] end elsif default_columns cols = default_columns else cols = all_fields end out << as_csv(records, cols, ) out end |
#required_blue_prompt ⇒ Object
373 374 375 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 373 def required_blue_prompt "#{cyan}|#{reset}" end |
#sleep_with_dots(sleep_seconds, dots = 3, dot_chr = ".") ⇒ Object
1034 1035 1036 1037 1038 1039 1040 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 1034 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 “…”
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 499 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
891 892 893 894 895 896 897 898 899 900 901 902 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 891 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 |