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_percent(val, sig_dig = 2) ⇒ Object
-
#format_rate(amount, unit = 's', sig_dig = 2) ⇒ Object
returns 0.50 / s ie {value} / {unit}.
- #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.
- #parse_rest_exception(e, options = {}) ⇒ Object
-
#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 = nil) ⇒ 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
- #print_to_file(txt, filename, overwrite = false, access_mode = 'w+') ⇒ 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 “…”.
-
#truncate_string_right(value, width, prefix = "...") ⇒ Object
truncate_string truncates a string and appends the prefix “…”.
- #wrap(s, width, indent = 0) ⇒ Object
Class Method Details
.included(klass) ⇒ Object
12 13 14 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 12 def self.included(klass) klass.send :include, Term::ANSIColor end |
.terminal_width ⇒ Object
16 17 18 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 16 def self.terminal_width @@terminal_width ||= 80 end |
.terminal_width=(v) ⇒ Object
20 21 22 23 24 25 26 27 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 20 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
1174 1175 1176 1177 1178 1179 1180 1181 1182 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 1174 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
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 1059 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, {})
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 879 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 out << format_dt_dd(row[:label], value, label_width, justify, do_wrap) + "\n" end out << reset if color return out end |
#as_json(data, options = {}, object_key = nil) ⇒ Object
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 1127 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], options[:include_fields]) 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})
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 720 721 722 723 724 725 726 727 728 729 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 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 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 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 678 def as_pretty_table(data, columns, ={}) data = [data].flatten # support --fields x,y,z and --all-fields or --fields all all_fields = data.first ? data.first.keys : [] if [:include_fields] if ([:include_fields].is_a?(Array) && [:include_fields].size == 1 && [:include_fields][0] == 'all') || [:include_fields] == 'all' columns = all_fields else # so let's use the passed in column definitions instead of the raw data properties # columns = options[:include_fields] new_columns = [] [:include_fields].each do |f| matching_column = nil # column definitions vary right now, array of symbols/strings/hashes or perhaps a single hash if columns.is_a?(Array) && columns[0] && columns[0].is_a?(Hash) matching_column = columns.find {|c| if c.is_a?(Hash) c.keys[0].to_s.downcase == f.to_s.downcase else c && c.to_s.downcase == f.to_s.downcase end } elsif columns.is_a?(Hash) matching_key = columns.keys.find {|k| k.to_s.downcase == f.to_s.downcase } if matching_key matching_column = columns[matching_key] end end new_columns << (matching_column ? matching_column : f) end columns = new_columns end elsif [:all_fields] columns = all_fields else columns = columns end 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 [:wrap] != true # && options[:include_fields].nil? && options[: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
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 1152 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 } })
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 933 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
34 35 36 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 34 def current_terminal_width return IO.console.winsize[1] rescue 0 end |
#format_available_options(option_types) ⇒ Object
543 544 545 546 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 543 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
1047 1048 1049 1050 1051 1052 1053 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 1047 def format_boolean(v) if v == true || v == "true" || v == "on" "Yes" else "No" end 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"
}'
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 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 319 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, )}'" 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
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 548 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 && value.include?(" ") && Morpheus::Cli::PrintHelper.terminal_width value_width = Morpheus::Cli::PrintHelper.terminal_width - label_width if value_width > 0 && value.gsub(/\e\[(\d+)m/, '').to_s.size > value_width wrap_indent = label_width + 1 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_percent(val, sig_dig = 2) ⇒ Object
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 1225 def format_percent(val, sig_dig=2) if val.nil? return "" end percent_value = val.to_f if percent_value == 0 return "0%" else return percent_value.round(sig_dig).to_s + "%" end end |
#format_rate(amount, unit = 's', sig_dig = 2) ⇒ Object
returns 0.50 / s ie {value} / {unit}
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 1238 def format_rate(amount, unit='s', sig_dig=2) if amount.to_f == 0 return "0.00" + " / " + unit.to_s else rtn = amount.to_f.round(2).to_s parts = rtn.split('.') # number_str = format_number(parts[0]) number_str = parts[0].to_s decimal_str = "#{parts[1]}".ljust(sig_dig, "0") number_str + "." + decimal_str return number_str + "." + decimal_str + " / " + unit.to_s end end |
#format_results_pagination(json_response, options = {}) ⇒ Object
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 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 389 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
662 663 664 665 666 667 668 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 662 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
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 504 505 506 507 508 509 510 511 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 448 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.
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 646 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 |
#parse_rest_exception(e, options = {}) ⇒ Object
142 143 144 145 146 147 148 149 150 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 142 def parse_rest_exception(e, ={}) data = {} begin data = JSON.parse(e.response.to_s) rescue => ex # Morpheus::Logging::DarkPrinter.puts "Failed to parse error response as JSON: #{ex}" if Morpheus::Logging.debug? end return data end |
#print_description_list(columns, obj, opts = {}) ⇒ Object
print_description_list() is an alias for ‘print generate_description_list()`
917 918 919 920 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 917 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
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 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 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 152 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 headers && headers[:params] # params inside headers for restclient reasons.. params = 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}" content_type = (headers && headers['Content-Type']) ? headers['Content-Type'] : 'application/x-www-form-urlencoded' # write to a file? if [:outfile] output = "" if api_request[:curl] || [:curl] output = format_curl_command(http_method, url, headers, payload, ) else # body payload output = payload if content_type == 'application/json' if payload.is_a?(String) begin payload = JSON.parse(payload) rescue => e #payload = "(unparsable) #{payload}" end end output = JSON.pretty_generate(payload) else if payload.is_a?(File) pretty_size = "#{payload.size} B" output = "File: #{payload.path} (#{pretty_size})" elsif payload.is_a?(String) output = 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 output = body_str else begin output = JSON.pretty_generate(payload) rescue output = payload.to_s end end end end end if [:scrub] output = Morpheus::Logging.(output) end print_result = print_to_file(output, [:outfile], [:overwrite]) return print_result end # curl output? if api_request[:curl] || [:curl] print "\n" puts "#{cyan}#{bold}#{dark}CURL COMMAND#{reset}" print format_curl_command(http_method, url, headers, payload, ) print "\n" return end print "\n" puts "#{cyan}#{bold}#{dark}REQUEST#{reset}" request_string = "#{http_method.to_s.upcase} #{url}".strip print request_string, "\n" print cyan if payload print "\n" if 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}" if [:scrub] print Morpheus::Logging.(JSON.pretty_generate(payload)) else print JSON.pretty_generate(payload) end else print "Content-Type: #{content_type}", "\n" print reset if payload.is_a?(File) pretty_size = "#{payload.size} B" print "File: #{payload.path} (#{pretty_size})" elsif payload.is_a?(String) if [:scrub] print Morpheus::Logging.(payload) else print payload end 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 if [:scrub] print Morpheus::Logging.(body_str) else print body_str end else if [:scrub] print Morpheus::Logging.(payload) else print payload end end end end end print "\n" print reset end |
#print_green_success(msg = nil) ⇒ Object
puts green message to stdout
47 48 49 50 51 52 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 47 def print_green_success(msg=nil) if msg.nil? msg = "success" end 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
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 60 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 # auto include remote name in h1 titles # eg. Morpheus Instances [dev] # if title && @appliance_name # title = "#{title} [#{@appliance_name}]" # end if subtitles.is_a?(Hash) = subtitles subtitles = ([:subtitles] || []).flatten end if subtitles.is_a?(String) subtitles = [subtitles] 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
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 98 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)
40 41 42 43 44 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 40 def print_red_alert(msg) $stderr.print "#{red}#{msg}#{reset}\n" #print_error "#{red}#{msg}#{reset}\n" #puts_error "#{red}#{msg}#{reset}" end |
#print_rest_errors(errors, options = {}) ⇒ Object
134 135 136 137 138 139 140 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 134 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
126 127 128 129 130 131 132 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 126 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
384 385 386 387 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 384 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
513 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 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 513 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] ||= [:cpu, :memory, :storage] if opts[:include].include?(:max_cpu) cpu_usage = stats['cpuUsagePeak'] out << cyan + "Max CPU".rjust(label_width, ' ') + ": " + (cpu_usage.to_f, 100) + "\n" end if opts[:include].include?(:avg_cpu) cpu_usage = stats['cpuUsageAvg'] out << cyan + "Avg. CPU".rjust(label_width, ' ') + ": " + (cpu_usage.to_f, 100) + "\n" end if opts[:include].include?(:cpu) cpu_usage = stats['cpuUsage'] || stats['usedCpu'] 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 |
#print_to_file(txt, filename, overwrite = false, access_mode = 'w+') ⇒ Object
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 1192 def print_to_file(txt, filename, overwrite=false, access_mode = 'w+') Morpheus::Logging::DarkPrinter.puts "Writing #{txt.to_s.bytesize} bytes to file #{filename} ..." if Morpheus::Logging.debug? outfile = nil begin full_filename = File.(filename) if File.exists?(full_filename) if !overwrite print "#{red}Output file '#{filename}' already exists.#{reset}\n" print "#{red}Use --overwrite to overwrite the existing file.#{reset}\n" return 1 end end if Dir.exists?(full_filename) print "#{red}Output file '#{filename}' is invalid. It is the name of an existing directory.#{reset}\n" return 1 end target_dir = File.dirname(full_filename) if !Dir.exists?(target_dir) FileUtils.mkdir_p(target_dir) end outfile = File.open(full_filename, access_mode) outfile.print(txt) print "#{cyan}Wrote #{txt.to_s.bytesize} bytes to file #{filename}\n" return 0 rescue => ex # puts_error "Error writing to outfile '#{filename}'. Error: #{ex}" print "#{red}Error writing to file '#{filename}'. Error: #{ex}#{reset}\n" return 1 ensure outfile.close if outfile end end |
#quote_csv_value(v) ⇒ Object
1055 1056 1057 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 1055 def quote_csv_value(v) '"' + v.to_s.gsub('"', '""') + '"' end |
#records_as_csv(records, options = {}, default_columns = nil) ⇒ Object
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 1102 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].is_a?(Array) && [:include_fields].size == 1 && [:include_fields][0] == 'all') || [:include_fields] == 'all' cols = all_fields else cols = [:include_fields] end elsif [:all_fields] cols = all_fields elsif default_columns cols = default_columns else cols = all_fields end out << as_csv(records, cols, ) out end |
#required_blue_prompt ⇒ Object
441 442 443 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 441 def required_blue_prompt "#{cyan}|#{reset}" end |
#sleep_with_dots(sleep_seconds, dots = 3, dot_chr = ".") ⇒ Object
1184 1185 1186 1187 1188 1189 1190 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 1184 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 “…”
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 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 575 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 |
#truncate_string_right(value, width, prefix = "...") ⇒ Object
truncate_string truncates a string and appends the prefix “…”
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 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 610 def truncate_string_right(value, width, prefix="...") 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 prefix trimmed_value = prefix + uncolored_value[(uncolored_value.size - width - prefix.size)..-1] else trimmed_value = uncolored_value[(uncolored_value.size - width)..-1] end return value.gsub(uncolored_value, trimmed_value) else return value end else if value.size > width if prefix return prefix + value[(value.size - width - prefix.size)..-1] else return value[(value.size - width)..-1] end else return value end end end |
#wrap(s, width, indent = 0) ⇒ Object
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 |
# File 'lib/morpheus/cli/mixins/print_helper.rb', line 1034 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 |