Module: Morpheus::Cli::OptionTypes

Includes:
Term::ANSIColor
Defined in:
lib/morpheus/cli/option_types.rb

Class Method Summary collapse

Class Method Details

.checkbox_prompt(option_type) ⇒ Object

this is a funky one, the user is prompted for yes/no but the return value is ‘on’,‘off’,nil todo: maybe make this easier to use, and have the api’s be flexible too..

Parameters:

  • option_type (Hash)

    option type object with type,fieldName,fieldLabel,etc..



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
# File 'lib/morpheus/cli/option_types.rb', line 663

def self.checkbox_prompt(option_type)
  value_found = false
  value = nil
  has_default = option_type['defaultValue'] != nil
  default_yes = has_default ? ['on', 'true', 'yes', '1'].include?(option_type['defaultValue'].to_s.downcase) : false
  while !value_found do
    print "#{option_type['fieldLabel']} (yes/no)#{has_default ? ' ['+(default_yes ? 'yes' : 'no')+']' : ''}: "
    input = $stdin.gets.chomp!
    if input == '?'
      help_prompt(option_type)
      next
    end
    if input.downcase == 'yes'
      value_found = true
      value = 'on'
    elsif input.downcase == 'no'
      value_found = true
      value = 'off'
    elsif input == '' && has_default
      value_found = true
      value = default_yes ? 'on' : 'off'
    end
    if value.nil? && option_type['required']
      puts "Invalid Option... Please try again."
      next
    end
    if value.nil? && !option_type['required']
      value_found = true
    end
  end
  return value
end

.confirm(message, options = {}) ⇒ Object

include Morpheus::Cli::PrintHelper



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/morpheus/cli/option_types.rb', line 10

def self.confirm(message,options={})
  if options[:yes] == true
    return true
  end
  default_value = options[:default]
  value_found = false
  while value_found == false do
    if default_value.nil?
      print "#{message} (yes/no): "
    else
      print "#{message} (yes/no) [#{!!default_value ? 'yes' : 'no'}]: "
    end
    input = $stdin.gets.chomp!
    if input.empty? && !default_value.nil?
      return !!default_value
    end
    if input.downcase == 'yes' || input.downcase == 'y'
      return true
    elsif input.downcase == 'no' || input.downcase == 'n'
      return false
    else
      puts "Invalid Option... Please try again."
    end
  end
end

.display_option_types_help(option_types, opts = {}) ⇒ Object



981
982
983
# File 'lib/morpheus/cli/option_types.rb', line 981

def self.display_option_types_help(option_types, opts={})
  puts self.format_option_types_help(option_types, opts)
end

.display_select_options(opt, select_options = [], paging = nil) ⇒ Object



961
962
963
# File 'lib/morpheus/cli/option_types.rb', line 961

def self.display_select_options(opt, select_options = [], paging = nil)
  puts format_select_options_help(opt, select_options, paging)
end

.field_input_prompt(option_type) ⇒ Object



696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
# File 'lib/morpheus/cli/option_types.rb', line 696

def self.field_input_prompt(option_type)
  value_found = false
  value = nil

  input_field_label = option_type['fieldInput'].gsub(/[A-Z]/, ' \0').split(' ').collect {|it| it.capitalize}.join(' ')
  input_field_name = option_type['fieldName'].split('.').reverse.drop(1).reverse.push(option_type['fieldInput']).join('.')
  input_option_type = option_type.merge({'fieldName' => input_field_name, 'fieldLabel' => input_field_label, 'required' => true, 'type' => 'text'})

  while !value_found do
    print "#{input_field_label}#{option_type['defaultInputValue'] ? " [#{option_type['defaultInputValue']}]" : ''}: "
    input = $stdin.gets.chomp!
    value = input.empty? ? option_type['defaultInputValue'] : input
    if input == '?'
      help_prompt(input_option_type)
    elsif !value.nil?
      value_found = true
    end
  end
  return value
end

.file_content_prompt(option_type, options = {}, api_client = nil, api_params = {}) ⇒ Object

file_content_prompt() prompts for source (local,repository,url) and then content or repo or. returns a Hash like sourceType:“local”,content:“yadda”,contentPath:null,contentRef:null



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
# File 'lib/morpheus/cli/option_types.rb', line 814

def self.file_content_prompt(option_type, options={}, api_client=nil, api_params={})
  file_params = {}
  options ||= {}
  full_field_key = option_type['fieldContext'] ? "#{option_type['fieldContext']}.#{option_type['fieldName']}" : "#{option_type['fieldName']}"
  passed_file_params = get_object_value(options, full_field_key)
  if passed_file_params.is_a?(Hash)
    file_params = passed_file_params
  end
  is_required = option_type['required']
  if file_params['source']
    file_params['sourceType'] = file_params.delete('source')
  end
  source_type = file_params['sourceType']
  # source
  if source_type.nil?
    source_type = select_prompt({'fieldContext' => full_field_key, 'fieldName' => 'source', 'fieldLabel' => 'Source', 'type' => 'select', 'optionSource' => 'fileContentSource', 'required' => is_required, 'defaultValue' => (is_required ? 'local' : nil)}, api_client, {}, options[:no_prompt])
    file_params['sourceType'] = source_type
  end
  # source type options
  if source_type == "local"
    # prompt for content
    if file_params['content'].nil?
      if options[:no_prompt]
        print Term::ANSIColor.red, "\nMissing Required Option\n\n", Term::ANSIColor.reset
        print Term::ANSIColor.red, "  * Content [-O #{full_field_key}.content=] - File Content\n", Term::ANSIColor.reset
        print "\n"
        exit 1
      else
        file_params['content'] = multiline_prompt({'fieldContext' => full_field_key, 'fieldName' => 'content', 'type' => 'code-editor', 'fieldLabel' => 'Content', 'required' => true})
      end
    end
  elsif source_type == "url"
    if file_params['url']
      file_params['contentPath'] = file_params.delete('url')
    end
    if file_params['contentPath'].nil?
      if options[:no_prompt]
        print Term::ANSIColor.red, "\nMissing Required Option\n\n", Term::ANSIColor.reset
        print Term::ANSIColor.red, "  * URL [-O #{full_field_key}.url=] - Path of file in the repository\n", Term::ANSIColor.reset
        print "\n"
        exit 1
      else
        file_params['contentPath'] = generic_prompt({'fieldContext' => full_field_key, 'fieldName' => 'url', 'fieldLabel' => 'URL', 'type' => 'text', 'required' => true})
      end
    end
  elsif source_type == "repository"
    if file_params['repository'].nil?
      repository_id = select_prompt({'fieldContext' => full_field_key, 'fieldName' => 'repositoryId', 'fieldLabel' => 'Repository', 'type' => 'select', 'optionSource' => 'codeRepositories', 'required' => true}, api_client, {}, options[:no_prompt])
      file_params['repository'] = {'id' => repository_id}
    end
    if file_params['contentPath'].nil?
      if options[:no_prompt]
        print Term::ANSIColor.red, "\nMissing Required Option\n\n", Term::ANSIColor.reset
        print Term::ANSIColor.red, "  * File Path [-O #{full_field_key}.path=] - Path of file in the repository\n", Term::ANSIColor.reset
        print "\n"
        exit 1
      else
        file_params['contentPath'] = generic_prompt({'fieldContext' => full_field_key, 'fieldName' => 'path', 'fieldLabel' => 'File Path', 'type' => 'text', 'required' => true})
      end
    end
    if !file_params.key?('contentRef')
      if options[:no_prompt]
        # pass
      else
        file_params['contentRef'] = generic_prompt({'fieldContext' => full_field_key, 'fieldName' => 'ref', 'fieldLabel' => 'Version Ref', 'type' => 'text'})
      end
    end
  end
  return file_params
end

.file_prompt(option_type) ⇒ Object



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
# File 'lib/morpheus/cli/option_types.rb', line 778

def self.file_prompt(option_type)
  value_found = false
  value = nil
  while !value_found do
    #print "#{option_type['fieldLabel']}#{option_type['fieldAddOn'] ? ('(' + option_type['fieldAddOn'] + ') ') : '' }#{optional_label(option_type)}#{option_type['defaultValue'] ? ' ['+option_type['defaultValue'].to_s+']' : ''}: "
    Readline.completion_append_character = ""
    Readline.basic_word_break_characters = ''
    Readline.completion_proc = proc {|s| Readline::FILENAME_COMPLETION_PROC.call(s) }
    input = Readline.readline("#{option_type['fieldLabel']}#{option_type['fieldAddOn'] ? ('(' + option_type['fieldAddOn'] + ') ') : '' }#{optional_label(option_type)}#{option_type['defaultValue'] ? ' ['+option_type['defaultValue'].to_s+']' : ''}: ", false).to_s
    input = input.chomp.strip
    #input = $stdin.gets.chomp!
    value = input.empty? ? option_type['defaultValue'] : input.to_s
    if input == '?'
      help_prompt(option_type)
    elsif value.empty? && option_type['required'] != true
      value = nil
      value_found = true
    elsif value
      filename = File.expand_path(value)
      if !File.exists?(filename)
        # print_red_alert "File not found: #{filename}"
        # exit 1
        print Term::ANSIColor.red,"  File not found: #{filename}",Term::ANSIColor.reset, "\n"
      elsif !File.file?(filename)
        print Term::ANSIColor.red,"  Argument is not a file: #{filename}",Term::ANSIColor.reset, "\n"
      else
        value = filename
        value_found = true
      end
    end
  end
  return value
end

.format_option_types_help(option_types, opts = {}) ⇒ Object



965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
# File 'lib/morpheus/cli/option_types.rb', line 965

def self.format_option_types_help(option_types, opts={})
  if option_types.empty?
    "#{opts[:color]}#{opts[:title] || "Available Options:"}\nNone\n\n"
  else
    if opts[:include_context]
      option_lines = option_types.sort {|it| it['displayOrder']}.collect {|it|
        field_context = (opts[:context_map] || {})[it['fieldContext']] || it['fieldContext']
        "    -O #{field_context && field_context != '' ? "#{field_context}." : ''}#{it['fieldName']}=\"value\""
      }
    else
      option_lines = option_types.sort {|it| it['displayOrder']}.collect {|it| "    -O #{it['fieldName']}=\"value\"" }
    end
    "#{opts[:color]}#{opts[:title] || "Available Options:"}\n#{option_lines.join("\n")}\n\n"
  end
end

.format_select_options_help(opt, select_options = [], paging = nil) ⇒ Object



942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
# File 'lib/morpheus/cli/option_types.rb', line 942

def self.format_select_options_help(opt, select_options = [], paging = nil)
  out = ""
  header = opt['fieldLabel'] ? "#{opt['fieldLabel']} Options" : "Options"
  if paging
    offset = paging[:cur_page] * paging[:page_size]
    limit = [offset + paging[:page_size], select_options.count].min - 1
    header = "#{header} (#{offset+1}-#{limit+1} of #{paging[:total]})"
    select_options = select_options[(offset)..(limit)]
  end
  out = ""
  out << "\n"
  out << "#{header}\n"
  out << "===============\n"
  select_options.each do |option|
    out << " * #{option['name']} [#{option['value']}]\n"
  end
  return out
end

.generic_prompt(option_type) ⇒ Object



717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
# File 'lib/morpheus/cli/option_types.rb', line 717

def self.generic_prompt(option_type)
  value_found = false
  value = nil
  while !value_found do
    print "#{option_type['fieldLabel']}#{option_type['fieldAddOn'] ? ('(' + option_type['fieldAddOn'] + ') ') : '' }#{!option_type['required'] ? ' (optional)' : ''}#{!option_type['defaultValue'].to_s.empty? ? ' ['+option_type['defaultValue'].to_s+']' : ''}: "
    input = $stdin.gets.chomp!
    value = input.empty? ? option_type['defaultValue'] : input
    if input == '?'
      help_prompt(option_type)
    elsif !value.nil? || option_type['required'] != true
      value_found = true
    end
  end
  return value
end

.get_last_selectObject



348
349
350
# File 'lib/morpheus/cli/option_types.rb', line 348

def self.get_last_select()
  Thread.current[:_last_select]
end

.grails_params(data, context = nil) ⇒ Object



276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/morpheus/cli/option_types.rb', line 276

def self.grails_params(data, context=nil)
  params = {}
  data.each do |k,v|
    if v.is_a?(Hash)
      params.merge!(grails_params(v, context ? "#{context}.#{k.to_s}" : k))
    else
      if context
        params["#{context}.#{k.to_s}"] = v
      else
        params[k.to_s] = v
      end
    end
  end
  return params
end

.help_prompt(option_type) ⇒ Object



921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
# File 'lib/morpheus/cli/option_types.rb', line 921

def self.help_prompt(option_type)
  field_key = [option_type['fieldContext'], option_type['fieldName']].select {|it| it && it != '' }.join('.')
  help_field_key = option_type[:help_field_prefix] ? "#{option_type[:help_field_prefix]}.#{field_key}" : field_key
  # an attempt at prompting help for natural options without the -O switch
  if option_type[:fmt] == :natural
    print Term::ANSIColor.green,"  * #{option_type['fieldLabel']} [--#{help_field_key}=] ", Term::ANSIColor.reset , "#{option_type['description']}\n"
  else
    print Term::ANSIColor.green,"  * #{option_type['fieldLabel']} [-O #{help_field_key}=] - ", Term::ANSIColor.reset , "#{option_type['description']}\n"
  end
  if option_type['type'].to_s == 'typeahead'
    print "This is a typeahead input. Enter the name or value of an option.\n"
    print "If the specified input matches more than one option, they will be printed and you will be prompted again.\n"
    print "the matching options will be shown and you can try again.\n"
  end
end

.load_options(option_type, api_client, api_params, query_value = nil) ⇒ Object



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
915
916
917
918
919
# File 'lib/morpheus/cli/option_types.rb', line 885

def self.load_options(option_type, api_client, api_params, query_value=nil)
  select_options = []
  # local array of options
  if option_type['selectOptions']
    # calculate from inline lambda
    if option_type['selectOptions'].is_a?(Proc)
      select_options = option_type['selectOptions'].call(api_client, grails_params(api_params || {}))
    else
      select_options = option_type['selectOptions']
    end
    # filter options ourselves
    if query_value.to_s != ""
      filtered_options = select_options.select { |it| it['value'].to_s == query_value.to_s }
      if filtered_options.empty?
        filtered_options = select_options.select { |it| it['name'].to_s == query_value.to_s }
      end
      select_options = filtered_options
    end
  elsif option_type['optionSource']
    # calculate from inline lambda
    if option_type['optionSource'].is_a?(Proc)
      select_options = option_type['optionSource'].call(api_client, grails_params(api_params || {}))
    elsif option_type['optionSource'] == 'list'
      # /api/options/list is a special action for custom OptionTypeLists, just need to pass the optionTypeId parameter
      select_options = load_source_options(option_type['optionSource'], api_client, grails_params(api_params || {}).merge({'optionTypeId' => option_type['id']}))
    else
      # remote optionSource aka /api/options/$optionSource?
      select_options = load_source_options(option_type['optionSource'], api_client, grails_params(api_params || {}))
    end
  else
    raise "option '#{field_key}' is type: 'typeahead' and missing selectOptions or optionSource!"
  end

  return select_options
end

.load_source_options(source, api_client, params) ⇒ Object



938
939
940
# File 'lib/morpheus/cli/option_types.rb', line 938

def self.load_source_options(source,api_client,params)
  api_client.options.options_for_source(source,params)['data']
end

.multiline_prompt(option_type) ⇒ Object



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
# File 'lib/morpheus/cli/option_types.rb', line 733

def self.multiline_prompt(option_type)
  value_found = false
  value = nil
  while !value_found do
    if value.nil?
      print "#{option_type['fieldLabel']}#{option_type['fieldAddOn'] ? ('(' + option_type['fieldAddOn'] + ') ') : '' }#{optional_label(option_type)} [Type 'EOF' to stop input]: \n"
    end
    input = $stdin.gets.chomp!
    # value = input.empty? ? option_type['defaultValue'] : input
    if input == '?' && value.nil?
      help_prompt(option_type)
    elsif input.chomp == '' && value.nil?
      # just hit enter right away to skip this
      value_found = true
    elsif input.chomp == 'EOF'
      value_found = true
    else
      if value.nil?
        value = ''
      end
      value << input + "\n"
    end
  end
  return value ? value.strip : value
end

.no_prompt(option_types, options = {}, api_client = nil, api_params = {}) ⇒ Object



36
37
38
# File 'lib/morpheus/cli/option_types.rb', line 36

def self.no_prompt(option_types, options={}, api_client=nil,api_params={})
  prompt(option_types, options, api_client, api_params, true)
end

.number_prompt(option_type) ⇒ Object



326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/morpheus/cli/option_types.rb', line 326

def self.number_prompt(option_type)
  value_found = false
  value = nil
  while !value_found do
    print "#{option_type['fieldLabel']}#{option_type['fieldAddOn'] ? ('(' + option_type['fieldAddOn'] + ') ') : '' }#{!option_type['required'] ? ' (optional)' : ''}#{!option_type['defaultValue'].to_s.empty? ? ' ['+option_type['defaultValue'].to_s+']' : ''}: "
    input = $stdin.gets.chomp!
    value = input.empty? ? option_type['defaultValue'] : input
    value = value.to_s.include?('.') ? value.to_f : value.to_i
    if input == '?'
      help_prompt(option_type)
    elsif !value.nil? || option_type['required'] != true
      value_found = true
    end
  end
  return value
end

.optional_label(option_type) ⇒ Object



985
986
987
988
989
990
991
992
# File 'lib/morpheus/cli/option_types.rb', line 985

def self.optional_label(option_type)
  # removing this for now, for the sake of providing less to look at
  if option_type[:fmt] == :natural # || true
    return ""
  else
    return option_type['required'] ? '' : ' (optional)'
  end
end

.password_prompt(option_type) ⇒ Object



759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
# File 'lib/morpheus/cli/option_types.rb', line 759

def self.password_prompt(option_type)
  value_found = false
  while !value_found do
    print "#{option_type['fieldLabel']}#{option_type['fieldAddOn'] ? ('(' + option_type['fieldAddOn'] + ') ') : '' }#{optional_label(option_type)}#{option_type['defaultValue'] ? ' ['+option_type['defaultValue'].to_s+']' : ''}: "
    input = $stdin.noecho(&:gets).chomp!
    value = input
    print "\n"
    if input == '?'
      help_prompt(option_type)
    elsif input == "" && option_type['defaultValue'] != nil
      value = option_type['defaultValue'].to_s
      value_found = true
    elsif !value.empty? || option_type['required'] != true
      value_found = true
    end
  end
  return value
end

.prompt(option_types, options = {}, api_client = nil, api_params = {}, no_prompt = false, paging_enabled = false) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
82
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
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
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
# File 'lib/morpheus/cli/option_types.rb', line 40

def self.prompt(option_types, options={}, api_client=nil, api_params={}, no_prompt=false, paging_enabled=false)
  paging_enabled = false if Morpheus::Cli.windows?
  results = {}
  options = options || {}
  # inject cli only stuff into option_types (should clone() here)
  option_types.each do |option_type|
    if options[:help_field_prefix]
      option_type[:help_field_prefix] = options[:help_field_prefix]
    end
  end
  # puts "Options Prompt #{options}"
  # only sort if displayOrder is set
  sorted_option_types = (option_types[0] && option_types[0]['displayOrder']) ? option_types.sort { |x,y| x['displayOrder'].to_i <=> y['displayOrder'].to_i } : option_types
  sorted_option_types.each do |option_type|
    context_map = results
    value = nil
    value_found=false

    # How about this instead?
    # option_type = option_type.clone
    # field_key = [option_type['fieldContext'], option_type['fieldName']].select {|it| it && it != '' }.join('.')
    # if field_key != ''
    #   value = get_object_value(options, field_key)
    #   if value != nil && options[:always_prompt] != true
    #     value_found = true
    #   end
    # end

    # allow for mapping of domain to relevant type: domain.zone => router.zone
    option_type['fieldContext'] = (options[:context_map] || {})[option_type['fieldContext']] || option_type['fieldContext']
    field_key = [option_type['fieldContext'], option_type['fieldName']].select {|it| it && it != '' }.join('.')
    help_field_key = option_type[:help_field_prefix] ? "#{option_type[:help_field_prefix]}.#{field_key}" : field_key
    namespaces = field_key.split(".")
    field_name = namespaces.pop

    # respect optionType.dependsOnCode
    # i guess this switched to visibleOnCode, respect one or the other
    visible_option_check_value = option_type['dependsOnCode']
    if !option_type['visibleOnCode'].to_s.empty?
      visible_option_check_value = option_type['visibleOnCode']
    end
    if !visible_option_check_value.to_s.empty?
      # support formats code=value or code:value OR code:(value|value2|value3)
      # OR fieldContext.fieldName=value
      parts = visible_option_check_value.include?("=") ? visible_option_check_value.split("=") : visible_option_check_value.split(":")
      depends_on_code = parts[0]
      depends_on_value = parts[1].to_s.strip
      depends_on_values = []
      if depends_on_value.size > 0
        # strip parenthesis
        if depends_on_value[0] && depends_on_value[0].chr == "("
          depends_on_value = depends_on_value[1..-1]
        end
        depends_on_value.chomp(")")
        depends_on_values = depends_on_value.split("|").collect { |it| it.strip }
      end
      depends_on_option_type = option_types.find {|it| it["code"] == depends_on_code }
      if !depends_on_option_type
        depends_on_option_type = option_types.find {|it| 
          (it['fieldContext'] ? "#{it['fieldContext']}.#{it['fieldName']}" : it['fieldName']) == depends_on_code
        }
      end
      if depends_on_option_type
        # dependent option type has a different value
        depends_on_field_key = depends_on_option_type['fieldContext'] ? "#{depends_on_option_type['fieldContext']}.#{depends_on_option_type['fieldName']}" : "#{depends_on_option_type['fieldName']}"
        found_dep_value = get_object_value(results, depends_on_field_key) || get_object_value(options, depends_on_field_key)
        if depends_on_values.size > 0
          # must be in the specified values
          # todo: uhh this actually needs to change to parse regex
          if !depends_on_values.include?(found_dep_value)
            next
          end
        else
          # no value found
          if found_dep_value.to_s.empty?
            next
          end
        end
      else
        # could not find the dependent option type, proceed and prompt
      end
    end

    cur_namespace = options
    parent_context_map = context_map
    parent_ns = field_name

    namespaces.each do |ns|
      next if ns.empty?
      parent_context_map = context_map
      parent_ns = ns
      cur_namespace[ns.to_s] ||= {}
      cur_namespace = cur_namespace[ns.to_s]
      context_map[ns.to_s] ||= {}
      context_map = context_map[ns.to_s]
    end

    # use the value passed in the options map
    if cur_namespace.respond_to?('key?') && cur_namespace.key?(field_name)
      value = cur_namespace[field_name]
      input_value = ['select', 'multiSelect','typeahead', 'multiTypeahead'].include?(option_type['type']) && option_type['fieldInput'] ? cur_namespace[option_type['fieldInput']] : nil
      if option_type['type'] == 'number'
        value = value.to_s.include?('.') ? value.to_f : value.to_i
      # these select prompts should just fall down through below, with the extra params no_prompt, use_value
      elsif option_type['type'] == 'select'
        value = select_prompt(option_type.merge({'defaultValue' => value, 'defaultInputValue' => input_value}), api_client, (option_type['noParams'] ? {} : (api_params || {}).merge(results)), true)
      elsif option_type['type'] == 'multiSelect'
        # support value as csv like "thing1, thing2"
        value_list = value.is_a?(String) ? value.parse_csv.collect {|v| v ? v.to_s.strip : v } : [value].flatten
        input_value_list = input_value.is_a?(String) ? input_value.parse_csv.collect {|v| v ? v.to_s.strip : v } : [input_value].flatten
        select_value_list = []
        value_list.each_with_index do |v, i|
          select_value_list << select_prompt(option_type.merge({'defaultValue' => v, 'defaultInputValue' => input_value_list[i]}), api_client, (option_type['noParams'] ? {} : (api_params || {}).merge(results)), true)
        end
        value = select_value_list
      elsif option_type['type'] == 'typeahead'
        value = typeahead_prompt(option_type.merge({'defaultValue' => value, 'defaultInputValue' => input_value}), api_client, (option_type['noParams'] ? {} : (api_params || {}).merge(results)), true)
      elsif option_type['type'] == 'multiTypeahead'
        # support value as csv like "thing1, thing2"
        value_list = value.is_a?(String) ? value.parse_csv.collect {|v| v ? v.to_s.strip : v } : [value].flatten
        input_value_list = input_value.is_a?(String) ? input_value.parse_csv.collect {|v| v ? v.to_s.strip : v } : [input_value].flatten
        select_value_list = []
        value_list.each_with_index do |v, i|
          select_value_list << typeahead_prompt(option_type.merge({'defaultValue' => v, 'defaultInputValue' => input_value_list[i]}), api_client, (option_type['noParams'] ? {} : (api_params || {}).merge(results)), true)
        end
        value = select_value_list
      end
      if options[:always_prompt] != true
        value_found = true
      end
    end

    # set the value that has been passed to the option type default value
    if value != nil # && value != ''
      option_type = option_type.clone
      option_type['defaultValue'] = value
    end
    # no_prompt means skip prompting and instead
    # use default value or error if a required option is not present
    no_prompt = no_prompt || options[:no_prompt]
    if no_prompt
      if !value_found
        if option_type['defaultValue'] != nil && !['select', 'multiSelect','typeahead','multiTypeahead'].include?(option_type['type'])
          value = option_type['defaultValue']
          value_found = true
        end
        if !value_found
          # select type is special because it supports skipSingleOption
          # and prints the available options on error
          if ['select', 'multiSelect'].include?(option_type['type'])
            value = select_prompt(option_type, api_client, (option_type['noParams'] ? {} : (api_params || {}).merge(results)), true)
            value_found = !!value
          end
          if ['typeahead', 'multiTypeahead'].include?(option_type['type'])
            value = typeahead_prompt(option_type, api_client, (option_type['noParams'] ? {} : (api_params || {}).merge(results)), true)
            value_found = !!value
          end
          if !value_found
            if option_type['required']
              print Term::ANSIColor.red, "\nMissing Required Option\n\n", Term::ANSIColor.reset
              print Term::ANSIColor.red, "  * #{option_type['fieldLabel']} [-O #{help_field_key}=] - #{option_type['description']}\n", Term::ANSIColor.reset
              print "\n"
              exit 1
            else
              next
            end
          end
        end
      end
    end

    if !value_found
      if option_type['type'] == 'number'
        value = number_prompt(option_type)
      elsif option_type['type'] == 'password'
        value = password_prompt(option_type)
      elsif option_type['type'] == 'checkbox'
        value = checkbox_prompt(option_type)
      elsif option_type['type'] == 'radio'
        value = radio_prompt(option_type)
      elsif option_type['type'] == 'textarea'
        value = multiline_prompt(option_type)
      elsif option_type['type'] == 'code-editor'
        value = multiline_prompt(option_type)
      elsif ['select', 'multiSelect'].include?(option_type['type'])
        # so, the /api/options/source is may need ALL the previously
        # selected values that are being accumulated in options
        # api_params is just extra params to always send
        # I suppose the entered value should take precedence
        # api_params = api_params.merge(options) # this might be good enough
        # dup it
        value = select_prompt(option_type, api_client, (option_type['noParams'] ? {} : (api_params || {}).merge(results)), options[:no_prompt], nil, paging_enabled)
        if value && option_type['type'] == 'multiSelect'
          value = [value]
          while self.confirm("Add another #{option_type['fieldLabel']}?", {:default => false}) do
            if addn_value = select_prompt(option_type, api_client, (option_type['noParams'] ? {} : (api_params || {}).merge(results)), options[:no_prompt], nil, paging_enabled)
              value << addn_value
            else
              break
            end
          end
        end
      elsif ['typeahead', 'multiTypeahead'].include?(option_type['type'])
        value = typeahead_prompt(option_type, api_client, (option_type['noParams'] ? {} : (api_params || {}).merge(results)), options[:no_prompt], nil, paging_enabled)
        if value && option_type['type'] == 'multiTypeahead'
          value = [value]
          while self.confirm("Add another #{option_type['fieldLabel']}?", {:default => false}) do
            if addn_value = typeahead_prompt(option_type, api_client, (option_type['noParams'] ? {} : (api_params || {}).merge(results)), options[:no_prompt], nil, paging_enabled)
              value << addn_value
            else
              break
            end
          end
        end
      elsif option_type['type'] == 'hidden'
        value = option_type['defaultValue']
        input = value
      elsif option_type['type'] == 'file'
        value = file_prompt(option_type)
      elsif option_type['type'] == 'file-content'
        value = file_content_prompt(option_type, options, api_client, {})
      else
        value = generic_prompt(option_type)
      end
    end

    if option_type['type'] == 'multiSelect'
      value = [value] if !value.nil? && !value.is_a?(Array)
      parent_context_map[parent_ns] = value
    else
      context_map[field_name] = value
    end
  end
  results
end

.radio_prompt(option_type) ⇒ Object



292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
# File 'lib/morpheus/cli/option_types.rb', line 292

def self.radio_prompt(option_type)
  value_found = false
  value = nil
  options = []
  if option_type['config'] and option_type['config']['radioOptions']
    option_type['config']['radioOptions'].each do |radio_option|
      options << {key: radio_option['key'], checked: radio_option['checked']}
    end
  end
  optionString = options.collect{ |b| b[:checked] ? "(#{b[:key]})" : b[:key]}.join(', ')
  while !value_found do
    print "#{option_type['fieldLabel']}#{option_type['fieldAddOn'] ? ('(' + option_type['fieldAddOn'] + ') ') : '' }[#{optionString}]: "
    input = $stdin.gets.chomp!
    if input == '?'
      help_prompt(option_type)
    else
      if input.nil? || input.empty?
        selectedOption = options.find{|o| o[:checked] == true}
      else
        selectedOption = options.find{|o| o[:key].downcase == input.downcase}
      end
      if selectedOption
        value = selectedOption[:key]
      else
        puts "Invalid Option. Please select from #{optionString}."
      end
      if !value.nil? || option_type['required'] != true
        value_found = true
      end
    end
  end
  return value
end

.select_prompt(option_type, api_client, api_params = {}, no_prompt = false, use_value = nil, paging_enabled = false) ⇒ Object



352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
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
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
504
505
506
507
508
# File 'lib/morpheus/cli/option_types.rb', line 352

def self.select_prompt(option_type,api_client, api_params={}, no_prompt=false, use_value=nil, paging_enabled=false)
  paging_enabled = false if Morpheus::Cli.windows?
  field_key = [option_type['fieldContext'], option_type['fieldName']].select {|it| it && it != '' }.join('.')
  help_field_key = option_type[:help_field_prefix] ? "#{option_type[:help_field_prefix]}.#{field_key}" : field_key
  value_found = false
  value = nil
  value_field = (option_type['config'] ? option_type['config']['valueField'] : nil) || 'value'
  default_value = option_type['defaultValue']
  default_value = default_value['id'] if default_value && default_value.is_a?(Hash) && !default_value['id'].nil?
  api_params ||= {}
  # local array of options
  if option_type['selectOptions']
    # calculate from inline lambda
    if option_type['selectOptions'].is_a?(Proc)
      select_options = option_type['selectOptions'].call(api_client, grails_params(api_params || {}))
    else
      # todo: better type validation
      select_options = option_type['selectOptions']
    end
  elsif option_type['optionSource']
    # calculate from inline lambda
    if option_type['optionSource'].is_a?(Proc)
      select_options = option_type['optionSource'].call(api_client, grails_params(api_params || {}))
    elsif option_type['optionSource'] == 'list'
      # /api/options/list is a special action for custom OptionTypeLists, just need to pass the optionTypeId parameter
      select_options = load_source_options(option_type['optionSource'], api_client, grails_params(api_params || {}).merge({'optionTypeId' => option_type['id']}))
    else
      # remote optionSource aka /api/options/$optionSource?
      select_options = load_source_options(option_type['optionSource'], api_client, grails_params(api_params || {}))
    end
  else
    raise "option '#{field_key}' is type: 'select' and missing selectOptions or optionSource!"
  end

  # ensure the preselected value (passed as an option) is in the dropdown
  if !use_value.nil?
    matched_option = select_options.find {|opt| opt[value_field].to_s == use_value.to_s || opt['name'].to_s == use_value.to_s }
    if !matched_option.nil?
      value = matched_option[value_field]
      value_found = true
    else
      print Term::ANSIColor.red, "\nInvalid Option #{option_type['fieldLabel']}: [#{use_value}]\n\n", Term::ANSIColor.reset
      print Term::ANSIColor.red, "  * #{option_type['fieldLabel']} [-O #{option_type['fieldContext'] ? (option_type['fieldContext']+'.') : ''}#{option_type['fieldName']}=] - #{option_type['description']}\n", Term::ANSIColor.reset
      if select_options && select_options.size > 10
        display_select_options(option_type, select_options.first(10))
        puts " (#{select_options.size-10} more)"
      else
        display_select_options(option_type, select_options)
      end
      print "\n"
      exit 1
    end
  # skipSingleOption is no longer supported
  # elsif !select_options.nil? && select_options.count == 1 && option_type['skipSingleOption'] == true
  #   value_found = true
  #   value = select_options[0]['value']
  # if there is just one option, use it as the defaultValue
  elsif !select_options.nil? && select_options.count == 1
    if option_type['required'] && default_value.nil?
      default_value = select_options[0]['name'] # name is prettier than value
    end
  elsif !select_options.nil?
    if default_value.nil?
      found_default_option = select_options.find {|opt| opt['isDefault'] == true }
      if found_default_option
        default_value = found_default_option['name'] # name is prettier than value
      end
    else
      found_default_option  = select_options.find {|opt| opt[value_field].to_s == default_value.to_s}
      if found_default_option
        default_value = found_default_option['name'] # name is prettier than value
      end
    end
  end

  if no_prompt
    if !value_found
      if !default_value.nil? && !select_options.nil? && select_options.find {|it| it['name'] == default_value || it[value_field].to_s == default_value.to_s}
        value_found = true
        value = select_options.find {|it| it['name'] == default_value || it[value_field].to_s == default_value.to_s}[value_field]
      elsif !select_options.nil? && select_options.count > 1 && option_type['autoPickOption'] == true
        value_found = true
        value = select_options[0][value_field]
      elsif option_type['required']
        print Term::ANSIColor.red, "\nMissing Required Option\n\n", Term::ANSIColor.reset
        print Term::ANSIColor.red, "  * #{option_type['fieldLabel']} [-O #{help_field_key}=] - #{option_type['description']}\n", Term::ANSIColor.reset
        if select_options && select_options.size > 10
          display_select_options(option_type, select_options.first(10))
          puts " (#{select_options.size-10} more)"
        else
          display_select_options(option_type, select_options)
        end
        print "\n"
        exit 1
      else
        return nil
      end
    end
  end

  paging = nil
  if paging_enabled
    option_count = select_options ? select_options.count : 0
    page_size = Readline.get_screen_size[0] - 6
    if page_size < option_count
      paging = {:cur_page => 0, :page_size => page_size, :total => option_count}
    end
  end

  while !value_found do
    Readline.completion_append_character = ""
    Readline.basic_word_break_characters = ''
    Readline.completion_proc = proc {|s| 
      matches = []
      available_options = (select_options || [])
      available_options.each{|option| 
        if option['name'] && option['name'] =~ /^#{Regexp.escape(s)}/
          matches << option['name']
        # elsif option['id'] && option['id'].to_s =~ /^#{Regexp.escape(s)}/
        elsif option[value_field] && option[value_field].to_s == s
          matches << option['name']
        end
      }
      matches
    }

    has_more_pages = paging && (paging[:cur_page] * paging[:page_size]) < paging[:total]
    input = Readline.readline("#{option_type['fieldLabel']}#{option_type['fieldAddOn'] ? ('(' + option_type['fieldAddOn'] + ') ') : '' }#{!option_type['required'] ? ' (optional)' : ''}#{!default_value.to_s.empty? ? ' ['+default_value.to_s+']' : ''} ['?' for#{has_more_pages && paging[:cur_page] > 0 ? ' more ' : ' '}options]: ", false).to_s
    input = input.chomp.strip
    if input.empty? && default_value
      input = default_value.to_s
    end
    select_option = select_options.find{|b| b['name'] == input || (!b['value'].nil? && b['value'].to_s == input) || (!b[value_field].nil? && b[value_field].to_s == input) || (b[value_field].nil? && input.empty?)}
    if select_option
      value = select_option[value_field]
      set_last_select(select_option)
    elsif !input.nil?  && !input.to_s.empty?
      input = '?'
    end
    
    if input == '?'
      help_prompt(option_type)
      display_select_options(option_type, select_options, paging)
      if paging
        paging[:cur_page] = (paging[:cur_page] + 1) * paging[:page_size] < paging[:total] ? paging[:cur_page] + 1 : 0
      end
    elsif !value.nil? || option_type['required'] != true
      value_found = true
    end
  end

  # wrap in object when using fieldInput
  if value && !option_type['fieldInput'].nil?
    value = {option_type['fieldName'].split('.').last => value, option_type['fieldInput'] => (no_prompt ? option_type['defaultInputValue'] : field_input_prompt(option_type))}
  end
  value
end

.set_last_select(obj) ⇒ Object



344
345
346
# File 'lib/morpheus/cli/option_types.rb', line 344

def self.set_last_select(obj)
  Thread.current[:_last_select] = obj
end

.typeahead_prompt(option_type, api_client, api_params = {}, no_prompt = false, use_value = nil, paging_enabled = false) ⇒ Object

this works like select_prompt, but refreshes options with ?query=value between inputs paging_enabled is ignored right now



512
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
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
# File 'lib/morpheus/cli/option_types.rb', line 512

def self.typeahead_prompt(option_type,api_client, api_params={}, no_prompt=false, use_value=nil, paging_enabled=false)
  select_options = []
  field_key = [option_type['fieldContext'], option_type['fieldName']].select {|it| it && it != '' }.join('.')
  help_field_key = option_type[:help_field_prefix] ? "#{option_type[:help_field_prefix]}.#{field_key}" : field_key
  input = ""
  value_found = false
  value = nil
  value_field = (option_type['config'] ? option_type['config']['valueField'] : nil) || 'value'
  default_value = option_type['defaultValue']
  default_value = default_value['id'] if default_value && default_value.is_a?(Hash) && !default_value['id'].nil?

  while !value_found do
    # ok get input, refresh options and see if it matches
    # if matches one, cool otherwise print matches and reprompt or error
    if use_value
      input = use_value
    elsif no_prompt
      input = default_value
    else
      Readline.completion_append_character = ""
      Readline.basic_word_break_characters = ''
      Readline.completion_proc = proc {|s| 
        matches = []
        available_options = (select_options || [])
        available_options.each{|option| 
          if option['name'] && option['name'] =~ /^#{Regexp.escape(s)}/
            matches << option['name']
          # elsif option['id'] && option['id'].to_s =~ /^#{Regexp.escape(s)}/
          elsif option[value_field] && option[value_field].to_s == s
            matches << option['name']
          end
        }
        matches
      }
      # prompt for typeahead input value
      input = Readline.readline("#{option_type['fieldLabel']}#{option_type['fieldAddOn'] ? ('(' + option_type['fieldAddOn'] + ') ') : '' }#{!option_type['required'] ? ' (optional)' : ''}#{!default_value.to_s.empty? ? ' ['+default_value.to_s+']' : ''} ['?' for options]: ", false).to_s
      input = input.chomp.strip
    end

    # just hit enter, use [default] if set
    if input.empty? && default_value
      input = default_value.to_s
    end
    
    # not required and no value? ok proceed
    if input.to_s == "" && option_type['required'] != true
      value_found = true
      value = nil # or "" # hmm
      #next
      break
    end

    # required and no value? you need help
    # if input.to_s == "" && option_type['required'] == true
    #   help_prompt(option_type)
    #   display_select_options(option_type, select_options) unless select_options.empty?
    #   next
    # end

    # looking for help with this input
    if input == '?'
      help_prompt(option_type)
      display_select_options(option_type, select_options) unless select_options.empty?
      next
    end

    # just hit enter? scram
    # looking for help with this input
    # if input == ""
    #   help_prompt(option_type)
    #   display_select_options(option_type, select_options)
    #   next
    # end

    # this is how typeahead works, it keeps refreshing the options with a new ?query={value}
    # query_value = (value || use_value || default_value || '')
    query_value = (input || '')
    api_params ||= {}
    api_params['query'] = query_value
    # skip refresh if you just hit enter
    if !query_value.empty?
      select_options = load_options(option_type, api_client, api_params, query_value)
    end

    # match input to option name or value
    # actually that is redundant, it should already be filtered to matches
    # and can just do this:
    # select_option = select_options.size == 1 ? select_options[0] : nil
    select_option = select_options.find{|b| (b[value_field] && (b[value_field].to_s == input.to_s)) || ((b[value_field].nil? || b[value_field].empty?) && (input == "")) }
    if select_option.nil?
      select_option = select_options.find{|b| b['name'] && b['name'] == input }
    end

    # found matching value, else did not find a value, show matching options and prompt again or error
    if select_option
      value = select_option[value_field]
      set_last_select(select_option)
      value_found = true
    else
      if use_value || no_prompt
        # todo: make this nicer
        # help_prompt(option_type)
        print Term::ANSIColor.red, "\nMissing Required Option\n\n", Term::ANSIColor.reset
        print Term::ANSIColor.red, "  * #{option_type['fieldLabel']} [-O #{help_field_key}=] - #{option_type['description']}\n", Term::ANSIColor.reset
        if select_options && select_options.size > 10
          display_select_options(option_type, select_options.first(10))
          puts " (#{select_options.size-10} more)"
        else
          display_select_options(option_type, select_options)
        end
        print "\n"
        if select_options.empty?
          print "The value '#{input}' matched 0 options.\n"
          # print "Please try again.\n"
        else
          print "The value '#{input}' matched #{select_options.size()} options.\n"
          print "Perhaps you meant one of these? #{ored_list(select_options.collect {|i|i['name']}, 3)}\n"
          # print "Please try again.\n"
        end
        print "\n"
        exit 1
      else
        #help_prompt(option_type)
        display_select_options(option_type, select_options)
        print "\n"
        if select_options.empty?
          print "The value '#{input}' matched 0 options.\n"
          print "Please try again.\n"
        else
          print "The value '#{input}' matched #{select_options.size()} options.\n"
          print "Perhaps you meant one of these? #{ored_list(select_options.collect {|i|i['name']}, 3)}\n"
          print "Please try again.\n"
        end
        print "\n"
        # reprompting now...
      end
    end
  end # end while !value_found

  # wrap in object when using fieldInput
  if value && !option_type['fieldInput'].nil?
    value = {option_type['fieldName'].split('.').last => value, option_type['fieldInput'] => (no_prompt ? option_type['defaultInputValue'] : field_input_prompt(option_type))}
  end
  value
end