Module: Morpheus::Cli::CliCommand

Overview

Module to be included by every CLI command so that commands get registered This mixin defines a print and puts method, and delegates todo: use delegate

Defined Under Namespace

Modules: ClassMethods

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#no_promptObject (readonly)

this setting makes it easy for the called to disable prompting



28
29
30
# File 'lib/morpheus/cli/cli_command.rb', line 28

def no_prompt
  @no_prompt
end

Class Method Details

.included(klass) ⇒ Object



19
20
21
22
23
# File 'lib/morpheus/cli/cli_command.rb', line 19

def self.included(klass)
  klass.send :include, Morpheus::Cli::PrintHelper
  klass.extend ClassMethods
  Morpheus::Cli::CliRegistry.add(klass, klass.command_name)
end

Instance Method Details

#build_common_options(opts, options, includes = []) ⇒ Object

appends to the passed OptionParser all the generic options



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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
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
509
510
511
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
# File 'lib/morpheus/cli/cli_command.rb', line 182

def build_common_options(opts, options, includes=[])
  #opts.separator ""
  # opts.separator "Common options:"
  includes = includes.clone
  while (option_key = includes.shift) do
    case option_key.to_sym

    when :account
      opts.on('-a','--account ACCOUNT', "Account Name") do |val|
        options[:account_name] = val
      end
      opts.on('-A','--account-id ID', "Account ID") do |val|
        options[:account_id] = val
      end

    when :options
      options[:options] ||= {}
      opts.on( '-O', '--option OPTION', "Option in the format -O field=\"value\"" ) do |option|
        # todo: look ahead and parse ALL the option=value args after -O switch
        #custom_option_args = option.split('=')
        custom_option_args = option.sub(/\s?\=\s?/, '__OPTION_DELIM__').split('__OPTION_DELIM__')
        custom_options = options[:options]
        option_name_args = custom_option_args[0].split('.')
        if option_name_args.count > 1
          nested_options = custom_options
          option_name_args.each_with_index do |name_element,index|
            if index < option_name_args.count - 1
              nested_options[name_element] = nested_options[name_element] || {}
              nested_options = nested_options[name_element]
            else
              val = custom_option_args[1]
              if val.to_s[0] == '{' && val.to_s[-1] == '}'
                begin
                  val = JSON.parse(val)
                rescue
                  Morpheus::Logging::DarkPrinter.puts "Failed to parse option value '#{val}' as JSON" if Morpheus::Logging.debug?
                end
              end
              nested_options[name_element] = val
            end
          end
        else
          val = custom_option_args[1]
          if val.to_s[0] == '{' && val.to_s[-1] == '}'
            begin
              val = JSON.parse(val)
            rescue
              Morpheus::Logging::DarkPrinter.puts "Failed to parse option value '#{val}' as JSON" if Morpheus::Logging.debug?
            end
          end
          custom_options[custom_option_args[0]] = val
        end
        # convert "true","on" and "false","off" to true and false
        unless options[:skip_booleanize]
          custom_options.booleanize!
        end
        options[:options] = custom_options
      end
      opts.on('-P','--prompt', "Always prompts. Use passed options as the default value.") do |val|
        options[:always_prompt] = true
        options[:options] ||= {}
        options[:options][:always_prompt] = true
      end
      opts.on('-N','--no-prompt', "Skip prompts. Use default values for all optional fields.") do |val|
        options[:no_prompt] = true
        options[:options] ||= {}
        options[:options][:no_prompt] = true
      end

    when :prompt
      opts.on('-P','--prompt', "Always prompts. Use passed options as the default value.") do |val|
        options[:always_prompt] = true
        options[:options] ||= {}
        options[:options][:always_prompt] = true
      end
      opts.on('-N','--no-prompt', "Skip prompts. Use default values for all optional fields.") do |val|
        options[:no_prompt] = true
        options[:options] ||= {}
        options[:options][:no_prompt] = true
      end

    when :payload
      opts.on('--payload FILE', String, "Payload from a local JSON or YAML file, skip all prompting") do |val|
        options[:payload_file] = val.to_s
        begin
          payload_file = File.expand_path(options[:payload_file])
          if !File.exists?(payload_file) || !File.file?(payload_file)
            raise ::OptionParser::InvalidOption.new("File not found: #{payload_file}")
            #return false
          end
          if payload_file =~ /\.ya?ml\Z/
            options[:payload] = YAML.load_file(payload_file)
          else
            options[:payload] = JSON.parse(File.read(payload_file))
          end
        rescue => ex
          raise ::OptionParser::InvalidOption.new("Failed to parse payload file: #{payload_file} Error: #{ex.message}")
        end
      end
      opts.on('--payload-dir DIRECTORY', String, "Payload from a local directory containing 1-N JSON or YAML files, skip all prompting") do |val|
        options[:payload_dir] = val.to_s
        payload_dir = File.expand_path(options[:payload_dir])
        if !Dir.exists?(payload_dir) || !File.directory?(payload_dir)
          raise ::OptionParser::InvalidOption.new("Directory not found: #{payload_dir}")
        end
        payload = {}
        begin
          merged_payload = {}
          payload_files = []
          payload_files += Dir["#{payload_dir}/*.json"]
          payload_files += Dir["#{payload_dir}/*.yml"]
          payload_files += Dir["#{payload_dir}/*.yaml"]
          if payload_files.empty?
            raise ::OptionParser::InvalidOption.new("No .json/yaml files found in config directory: #{payload_dir}")
          end
          payload_files.each do |payload_file|
            Morpheus::Logging::DarkPrinter.puts "parsing payload file: #{payload_file}" if Morpheus::Logging.debug?
            config_payload = {}
            if payload_file =~ /\.ya?ml\Z/
              config_payload = YAML.load_file(payload_file)
            else
              config_payload = JSON.parse(File.read(payload_file))
            end
            merged_payload.deep_merge!(config_payload)
          end
          options[:payload] = merged_payload
        rescue => ex
          raise ::OptionParser::InvalidOption.new("Failed to parse payload file: #{payload_file} Error: #{ex.message}")
        end
      end
      opts.on('--payload-json JSON', String, "Payload JSON, skip all prompting") do |val|
        begin
          options[:payload] = JSON.parse(val.to_s)
        rescue => ex
          raise ::OptionParser::InvalidOption.new("Failed to parse payload as JSON. Error: #{ex.message}")
        end
      end
      opts.on('--payload-yaml YAML', String, "Payload YAML, skip all prompting") do |val|
        begin
          options[:payload] = YAML.load(val.to_s)
        rescue => ex
          raise ::OptionParser::InvalidOption.new("Failed to parse payload as YAML. Error: #{ex.message}")
        end
      end

    when :list
      opts.on( '-m', '--max MAX', "Max Results" ) do |max|
        options[:max] = max.to_i
      end

      opts.on( '-o', '--offset OFFSET', "Offset Results" ) do |offset|
        options[:offset] = offset.to_i.abs
      end

      opts.on( '-s', '--search PHRASE', "Search Phrase" ) do |phrase|
        options[:phrase] = phrase
      end

      opts.on( '-S', '--sort ORDER', "Sort Order" ) do |v|
        options[:sort] = v
      end

      opts.on( '-D', '--desc', "Reverse Sort Order" ) do |v|
        options[:direction] = "desc"
      end

      # arbitrary query parameters in the format -Q "category=web&phrase=nginx"
      # opts.on( '-Q', '--query PARAMS', "Query parameters. PARAMS format is 'phrase=foobar&category=web'" ) do |val|
      #   options[:query_filters_raw] = val
      #   options[:query_filters] = {}
      #   # todo: smarter parsing
      #   val.split('&').each do |filter| 
      #     k, v = filter.split('=')
      #     # allow "woot:true instead of woot=true"
      #     if (k.include?(":") && v == nil)
      #       k, v = k.split(":")
      #     end
      #     if (!k.to_s.empty?)
      #       options[:query_filters][k.to_s.strip] = v.to_s.strip
      #     end
      #   end
      # end

    when :query, :query_filters
      # arbitrary query parameters in the format -Q "category=web&phrase=nginx"
      opts.on( '-Q', '--query PARAMS', "Query parameters. PARAMS format is 'phrase=foobar&category=web'" ) do |val|
        options[:query_filters_raw] = val
        options[:query_filters] = {}
        # todo: smarter parsing
        val.split('&').each do |filter| 
          k, v = filter.split('=')
          # allow "woot:true instead of woot=true"
          if (k.include?(":") && v == nil)
            k, v = k.split(":")
          end
          if (!k.to_s.empty?)
            if options[:query_filters].key?(k.to_s.strip)
              cur_val = options[:query_filters][k.to_s.strip]
              if cur_val.instance_of?(Array)
                options[:query_filters][k.to_s.strip] << v.to_s.strip
              else
                options[:query_filters][k.to_s.strip] = [cur_val, v.to_s.strip]
              end
            else
              options[:query_filters][k.to_s.strip] = v.to_s.strip
            end
          end
        end
      end

    when :last_updated
      # opts.on("--last-updated TIME", Time, "Filter by gte last updated") do |time|
      opts.on("--last-updated TIME", String, "Filter by Last Updated (gte)") do |time|
        begin
          options[:lastUpdated] = parse_time(time)
        rescue => e
          raise OptionParser::InvalidArgument.new "Failed to parse time '#{time}'. Error: #{e}"
        end
      end

    when :remote

      # this is the only option now... 
      # first, you must do `remote use [appliance]`
      opts.on( '-r', '--remote REMOTE', "Remote Appliance Name to use for this command. The active appliance is used by default." ) do |val|
        options[:remote] = val
      end

      # todo: also require this for talking to plain old HTTP
      opts.on('-I','--insecure', "Allow insecure HTTPS communication.  i.e. bad SSL certificate.") do |val|
        options[:insecure] = true
        Morpheus::RestClient.enable_ssl_verification = false
      end

      opts.on( '-T', '--token ACCESS_TOKEN', "Access Token for api requests. While authenticated to a remote, the current saved credentials are used." ) do |remote|
        options[:remote_token] = remote
      end

      # skipping the rest of this for now..

      next

      # opts.on( '-r', '--remote REMOTE', "Remote Appliance" ) do |remote|
      #   options[:remote] = remote
      # end

      opts.on( '-U', '--url REMOTE', "API Url" ) do |remote|
        options[:remote_url] = remote
      end

      opts.on( '-u', '--username USERNAME', "Username" ) do |remote|
        options[:remote_username] = remote
      end

      opts.on( '-p', '--password PASSWORD', "Password" ) do |remote|
        options[:remote_password] = remote
      end

      opts.on( '-T', '--token ACCESS_TOKEN', "Access Token" ) do |remote|
        options[:remote_token] = remote
      end
      
    when :auto_confirm
      opts.on( '-y', '--yes', "Auto Confirm" ) do
        options[:yes] = true
      end

    when :json
      opts.on('-j','--json', "JSON Output") do
        options[:json] = true
        options[:format] = :json
      end

      opts.on('--json-raw', String, "JSON Output that is not so pretty.") do |val|
        options[:json] = true
        options[:format] = :json
        options[:pretty_json] = false
      end
      opts.add_hidden_option('json-raw') if opts.is_a?(Morpheus::Cli::OptionParser)

    when :yaml
      opts.on(nil, '--yaml', "YAML Output") do
        options[:yaml] = true
        options[:format] = :yaml
      end
      opts.on(nil, '--yml', "alias for --yaml") do
        options[:yaml] = true
        options[:format] = :yaml
      end
      opts.add_hidden_option('yml') if opts.is_a?(Morpheus::Cli::OptionParser)

    when :csv
      opts.on(nil, '--csv', "CSV Output") do
        options[:csv] = true
        options[:format] = :csv
        #options[:csv_delim] = options[:csv_delim] || ","
      end

      opts.on('--csv-delim CHAR', String, "Delimiter for CSV Output values. Default: ','") do |val|
        options[:csv] = true
        options[:format] = :csv
        val = val.gsub("\\n", "\n").gsub("\\r", "\r").gsub("\\t", "\t") if val.include?("\\")
        options[:csv_delim] = val
      end

      opts.on('--csv-newline [CHAR]', String, "Delimiter for CSV Output rows. Default: '\\n'") do |val|
        options[:csv] = true
        options[:format] = :csv
        if val == "no" || val == "none"
          options[:csv_newline] = ""
        else
          val = val.gsub("\\n", "\n").gsub("\\r", "\r").gsub("\\t", "\t") if val.include?("\\")
          options[:csv_newline] = val
        end
      end

      opts.on(nil, '--csv-quotes', "Wrap CSV values with \". Default: false") do
        options[:csv] = true
        options[:format] = :csv
        options[:csv_quotes] = true
      end

      opts.on(nil, '--csv-no-header', "Exclude header for CSV Output.") do
        options[:csv] = true
        options[:format] = :csv
        options[:csv_no_header] = true
      end

    when :fields
      opts.on('-F', '--fields x,y,z', Array, "Filter Output to a limited set of fields. Default is all fields.") do |val|
        options[:include_fields] = val
      end

    when :outfile
      opts.on('--out FILE', String, "Write standard output to a file instead of the terminal.") do |val|
        # could validate directory is writable..
        options[:outfile] = val
      end

    when :dry_run
      opts.on('-d','--dry-run', "Dry Run, print the API request instead of executing it") do
        options[:dry_run] = true
      end

    when :quiet
      opts.on('-q','--quiet', "No Output, do not print to stdout") do
        options[:quiet] = true
      end

    else
      raise "Unknown common_option key: #{option_key}"
    end
  end

  # options that are always included

  # disable ANSI coloring
  opts.on('-C','--nocolor', "Disable ANSI coloring") do
    Term::ANSIColor::coloring = false
  end

  opts.on('-V','--debug', "Print extra output for debugging.") do
    options[:debug] = true
    Morpheus::Logging.set_log_level(Morpheus::Logging::Logger::DEBUG)
    ::RestClient.log = Morpheus::Logging.debug? ? Morpheus::Logging::DarkPrinter.instance : nil
    # perhaps...
    # create a new logger instance just for this command instance
    # this way we don't elevate the global level for subsequent commands in a shell
    # @logger = Morpheus::Logging::Logger.new(STDOUT)
    # if [email protected]?
    #   @logger.log_level = Morpheus::Logging::Logger::DEBUG
    # end
  end

  opts.on('-h', '--help', "Prints this help" ) do
    puts opts
    exit
  end

  opts
end

#build_option_type_options(opts, options, option_types = []) ⇒ Object

Appends Array of OptionType definitions to an OptionParser instance This adds an option like –fieldContext.fieldName=“VALUE”



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

def build_option_type_options(opts, options, option_types=[])
  #opts.separator ""
  #opts.separator "Options:"
  options[:options] ||= {} # this is where these go..for now
  custom_options = options[:options]
  
  # add each one to the OptionParser
  option_types.each do |option_type|
    field_namespace = []
    field_name = option_type['fieldName'].to_s
    if field_name.empty?
      puts "Missing fieldName for option type: #{option_type}" if Morpheus::Logging.debug?
      next
    end
    
    if !option_type['fieldContext'].to_s.empty?
      option_type['fieldContext'].split(".").each do |ns|
        field_namespace << ns
      end
    end
    
    full_field_name = field_name
    if !field_namespace.empty?
      full_field_name = "#{field_namespace.join('.')}.#{field_name}"
    end

    description = "#{option_type['fieldLabel']}#{option_type['fieldAddOn'] ? ('(' + option_type['fieldAddOn'] + ') ') : '' }#{!option_type['required'] ? ' (optional)' : ''}#{option_type['defaultValue'] ? ' Default: '+option_type['defaultValue'].to_s : ''}"
    if option_type['description']
      # description << "\n                                     #{option_type['description']}"
      description << " - #{option_type['description']}"
    end
    if option_type['helpBlock']
      description << "\n                                     #{option_type['helpBlock']}"
    end
    # description = option_type['description'].to_s
    # if option_type['defaultValue']
    #   description = "#{description} Default: #{option_type['defaultValue']}"
    # end
    # if option_type['required'] == true
    #   description = "(Required) #{description}"
    # end
    
    value_label = "VALUE"
    if option_type['placeHolder']
      value_label = option_type['placeHolder']
    elsif option_type['type'] == 'checkbox'
      value_label = 'on|off' # or.. true|false
    elsif option_type['type'] == 'number'
      value_label = 'NUMBER'
    # elsif option_type['type'] == 'select'
    #   value_label = 'SELECT'
    # elsif option['type'] == 'select'
    end
    opts.on("--#{full_field_name} #{value_label}", String, description) do |val|
      cur_namespace = custom_options
      field_namespace.each do |ns|
        next if ns.empty?
        cur_namespace[ns.to_s] ||= {}
        cur_namespace = cur_namespace[ns.to_s]
      end
      cur_namespace[field_name] = val
    end

    # todo: all the various types
    # number 
    # checkbox [on|off]
    # select for optionSource and selectOptions

  end
  opts
end

#command_nameObject



564
565
566
# File 'lib/morpheus/cli/cli_command.rb', line 564

def command_name
  self.class.command_name
end

#default_subcommandObject



576
577
578
# File 'lib/morpheus/cli/cli_command.rb', line 576

def default_subcommand
  self.class.default_subcommand
end

#establish_remote_appliance_connection(options) ⇒ Object

This supports the simple remote option eg. ‘instances add –remote “qa”` It will establish a connection to the pre-configured appliance named “qa” The calling command can populate @appliances and/or @appliance_name Otherwise, the current active appliance is used… This returns a new instance of Morpheus::APIClient (and sets @access_token, and @appliance) Your command should be ready to make api requests after this.



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

def establish_remote_appliance_connection(options)
  # todo: probably refactor and don't rely on this method to set these instance vars
  @appliance_name, @appliance_url, @access_token = nil, nil, nil
  @api_client = nil

  appliance = nil # @appliance..why not? laff
  if options[:remote]
    appliance = ::Morpheus::Cli::Remote.load_remote(options[:remote])
    if !appliance
      if ::Morpheus::Cli::Remote.appliances.empty?
        raise_command_error "You have no appliances configured. See the `remote add` command."
      else
        raise_command_error "Remote appliance not found by the name '#{options[:remote]}'"
      end
    end
  else
    appliance = ::Morpheus::Cli::Remote.load_active_remote()
    if !appliance
      if ::Morpheus::Cli::Remote.appliances.empty?
        raise_command_error "You have no appliances configured. See the `remote add` command."
      else
        raise_command_error "No current appliance, see `remote use`."
      end
    end
  end
  @appliance_name = appliance[:name]
  @appliance_url = appliance[:host] || appliance[:url] # it's :host in the YAML..heh

  # instead of toggling this global value
  # this should just be an attribute of the api client
  # for now, this fixes the issue where passing --insecure or --remote
  # would then apply to all subsequent commands...
  if !Morpheus::Cli::Shell.insecure
    if options[:insecure]
      Morpheus::RestClient.enable_ssl_verification = false
    else
      if appliance[:insecure] && Morpheus::RestClient.ssl_verification_enabled?
        Morpheus::RestClient.enable_ssl_verification = false
      elsif !appliance[:insecure] && !Morpheus::RestClient.ssl_verification_enabled?
        Morpheus::RestClient.enable_ssl_verification = true
      end
    end
  end

  # todo: support old way of accepting --username and --password on the command line
  # it's probably better not to do that tho, just so it stays out of history files
  

  # if !@appliance_name && !@appliance_url
  #   raise_command_error "Please specify a remote appliance with -r or see the command `remote use`"
  # end

  Morpheus::Logging::DarkPrinter.puts "establishing connection to [#{@appliance_name}] #{@appliance_url}" if options[:debug]
  #puts "#{dark} #=> establishing connection to [#{@appliance_name}] #{@appliance_url}#{reset}\n" if options[:debug]

  
  # punt.. and just allow passing an access token instead for now..
  # this skips saving to the appliances file and all that..
  if options[:token]
    @access_token = options[:token]
  end

  # ok, get some credentials.
  # this prompts for username, password  without options[:no_prompt]
  # used saved credentials please
  @api_credentials = Morpheus::Cli::Credentials.new(@appliance_name, @appliance_url)
  if options[:remote_token]
    @access_token = options[:remote_token]
  else
    @access_token = @api_credentials.load_saved_credentials()
    if @access_token.to_s.empty?
      unless options[:no_prompt]
        @access_token = @api_credentials.request_credentials(options)
      end
    end
    # bail if we got nothing still
    unless options[:skip_verify_access_token]
      verify_access_token!
    end
  end

  # ok, connect to the appliance.. actually this just instantiates an ApiClient
  api_client = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url)
  @api_client = api_client # meh, just return w/o setting instance attrs
  return api_client
end

#full_command_usageObject

a string to describe the usage of your command this is what the –help option feel free to override this in your commands



606
607
608
609
610
611
612
613
614
615
616
617
618
619
# File 'lib/morpheus/cli/cli_command.rb', line 606

def full_command_usage
  out = ""
  out << usage.to_s.strip if usage
  out << "\n"
  if !subcommands.empty?
    out << "Commands:"
    out << "\n"
    subcommands.sort.each {|cmd, method|
      out << "\t#{cmd.to_s}\n"
    }
  end
  # out << "\n"
  out
end

#handle(args) ⇒ Object



655
656
657
# File 'lib/morpheus/cli/cli_command.rb', line 655

def handle(args)
  raise "#{self} has not defined handle()!"
end

#handle_subcommand(args) ⇒ Object

a default handler



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

def handle_subcommand(args)
  commands = subcommands
  if subcommands.empty?
    raise "#{self.class} has no available subcommands"
  end
  # meh, could deprecate and make subcommand define handle() itself
  # if args.count == 0 && default_subcommand
  #   # p "using default subcommand #{default_subcommand}"
  #   return self.send(default_subcommand, args || [])
  # end
  subcommand_name = args[0]
  if args.empty?
    print_error Morpheus::Terminal.angry_prompt
    puts_error "[command] argument is required"
    puts full_command_usage
    exit 127
  end
  if args[0] == "-h" || args[0] == "--help" || args[0] == "help"
    puts full_command_usage
    return 0
  end
  if subcommand_aliases[subcommand_name]
    subcommand_name = subcommand_aliases[subcommand_name]
  end
  cmd_method = subcommands[subcommand_name]
  if !cmd_method
    print_error Morpheus::Terminal.angry_prompt
    puts_error "'#{subcommand_name}' is not a morpheus #{self.command_name} command. See '#{my_help_command}'"
    return 127
  end
  self.send(cmd_method, args[1..-1])
end

#interactive?Boolean

whether to prompt or not, this is true by default.



82
83
84
# File 'lib/morpheus/cli/cli_command.rb', line 82

def interactive?
  @no_prompt != true
end

#my_help_commandObject



588
589
590
# File 'lib/morpheus/cli/cli_command.rb', line 588

def my_help_command
  "morpheus #{command_name} --help"
end

#my_terminalMorpheus::Terminal



31
32
33
# File 'lib/morpheus/cli/cli_command.rb', line 31

def my_terminal
  @my_terminal ||= Morpheus::Terminal.instance
end

#my_terminal=(term) ⇒ Object

set the terminal this is running this command.



38
39
40
41
42
43
# File 'lib/morpheus/cli/cli_command.rb', line 38

def my_terminal=(term)
  if !t.is_a?(Morpheus::Terminal)
    raise "CliCommand #{self.class} terminal= expects object of type Terminal and instead got a #{t.class}"
  end
  @my_terminal = t
end

#parse_id_list(id_list, delim = /\s*\,\s*/) ⇒ Object

parse_id_list splits returns the given id_list with its values split on a comma

your id values cannot contain a comma, atm...


95
96
97
# File 'lib/morpheus/cli/cli_command.rb', line 95

def parse_id_list(id_list, delim=/\s*\,\s*/)
  [id_list].flatten.collect {|it| it ? it.to_s.split(delim) : nil }.flatten.compact
end

#parse_list_options(options = {}) ⇒ Object

parse the parameters provided by the common :list options returns Hash of params the format => “foobar”, “max”: 100



777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
# File 'lib/morpheus/cli/cli_command.rb', line 777

def parse_list_options(options={})
  list_params = {}
  [:phrase, :offset, :max, :sort, :direction, :lastUpdated].each do |k|
    if options.key?(k)
      list_params[k.to_s] = options[k]
    elsif options.key?(k.to_s)
      list_params[k.to_s] = options[k.to_s]
    end
  end
  # arbitrary filters
  if options[:query_filters]
    options[:query_filters].each do |k, v|
      if k
        list_params[k] = v
      end
    end
  end
  return list_params
end

#parse_list_subtitles(options = {}) ⇒ Object

parse the subtitles provided by the common :list options returns Array of subtitles as strings in the format [“Phrase: blah”, “Max: 100”]



799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
# File 'lib/morpheus/cli/cli_command.rb', line 799

def parse_list_subtitles(options={})
  subtitles = []
  list_params = {}
  [:phrase, :offset, :max, :sort, :direction, :lastUpdated].each do |k|
    if options.key?(k)
      subtitles << "#{k.to_s}: #{options[k]}"
    elsif options.key?(k.to_s)
      subtitles << "#{k.to_s}: #{options[k.to_s]}"
    end
  end
  # arbitrary filters
  if options[:query_filters]
    formatted_filters = options[:query_filters].collect {|k,v| "#{k.to_s}=#{v}" }.join('&')
    subtitles << "Query: #{formatted_filters}"
    # options[:query_filters].each do |k, v|
    #   subtitles << "#{k.to_s}: #{v}"
    # end
  end
  return subtitles
end

delegate :print, to: :my_terminal delegate :puts, to: :my_terminal or . . . bum bum bummm a paradigm shift away from include and use module functions instead. module_function :print, puts delegate :puts, to: :my_terminal



53
54
55
# File 'lib/morpheus/cli/cli_command.rb', line 53

def print(*msgs)
  my_terminal.stdout.print(*msgs)
end


61
62
63
# File 'lib/morpheus/cli/cli_command.rb', line 61

def print_error(*msgs)
  my_terminal.stderr.print(*msgs)
end


820
821
822
823
824
825
826
827
828
829
830
831
832
833
# File 'lib/morpheus/cli/cli_command.rb', line 820

def print_to_file(txt, filename)
  Morpheus::Logging::DarkPrinter.puts "Writing #{txt.to_s.bytesize} bytes to file #{filename}" if Morpheus::Logging.debug?
  outfile = nil
  begin
    outfile = File.open(File.expand_path(filename), 'w')
    outfile.print(txt)
    return 0
  rescue => ex
    puts_error "Error printing to outfile '#{filename}'. Error: #{ex}"
    return 1
  ensure
    outfile.close if outfile
  end
end

#puts(*msgs) ⇒ Object



57
58
59
# File 'lib/morpheus/cli/cli_command.rb', line 57

def puts(*msgs)
  my_terminal.stdout.puts(*msgs)
end

#puts_error(*msgs) ⇒ Object



65
66
67
# File 'lib/morpheus/cli/cli_command.rb', line 65

def puts_error(*msgs)
  my_terminal.stderr.puts(*msgs)
end

#raise_command_error(msg) ⇒ Object



86
87
88
# File 'lib/morpheus/cli/cli_command.rb', line 86

def raise_command_error(msg)
  raise Morpheus::Cli::CommandError.new(msg)
end

#render_with_format(json_response, options, object_key = nil) ⇒ Object

basic rendering for options :json, :yaml, :csv, :fields, and :outfile returns the string rendered, or nil if nothing was rendered.



837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
# File 'lib/morpheus/cli/cli_command.rb', line 837

def render_with_format(json_response, options, object_key=nil)
  output = nil
  if options[:json]
    output = as_json(json_response, options, object_key)
  elsif options[:yaml]
    output = as_yaml(json_response, options, object_key)
  elsif options[:csv]
    row = object_key ? json_response[object_key] : json_response
    output = records_as_csv([row], options)
  end
  if output
    if options[:outfile]
      print_to_file(output, options[:outfile])
    else
      puts output
    end
  end
  return output
end

#run_command_for_each_arg(args, &block) ⇒ 0|1

executes block with each argument in the list



661
662
663
664
665
666
667
668
669
670
671
672
673
# File 'lib/morpheus/cli/cli_command.rb', line 661

def run_command_for_each_arg(args, &block)
  cmd_results = []
  args.each do |arg|
    begin
      cur_result = yield arg
    rescue SystemExit => err
      cur_result = err.success? ? 0 : 1
    end
    cmd_results << cur_result
  end
  failed_cmd = cmd_results.find {|cmd_result| cmd_result == false || (cmd_result.is_a?(Integer) && cmd_result != 0) }
  return failed_cmd ? failed_cmd : 0
end

#subcommand_aliasesObject



572
573
574
# File 'lib/morpheus/cli/cli_command.rb', line 572

def subcommand_aliases
  self.class.subcommand_aliases
end

#subcommand_usage(*extra) ⇒ Object



592
593
594
595
596
597
598
599
600
601
# File 'lib/morpheus/cli/cli_command.rb', line 592

def subcommand_usage(*extra)
  calling_method = caller[0][/`([^']*)'/, 1].to_s.sub('block in ', '')
  subcommand_name = subcommands.key(calling_method)
  extra = extra.flatten
  if !subcommand_name.empty? && extra.first == subcommand_name
    extra.shift
  end
  #extra = ["[options]"] if extra.empty?
  "Usage: morpheus #{command_name} #{subcommand_name} #{extra.join(' ')}".squeeze(' ').strip
end

#subcommandsObject



568
569
570
# File 'lib/morpheus/cli/cli_command.rb', line 568

def subcommands
  self.class.subcommands
end

#usageObject



580
581
582
583
584
585
586
# File 'lib/morpheus/cli/cli_command.rb', line 580

def usage
  if !subcommands.empty?
    "Usage: morpheus #{command_name} [command] [options]"
  else
    "Usage: morpheus #{command_name} [options]"
  end
end

#verify_access_token!Object



768
769
770
771
772
773
# File 'lib/morpheus/cli/cli_command.rb', line 768

def verify_access_token!
  if @access_token.empty?
    raise_command_error "Unable to acquire access token. Please verify your credentials and try again."
  end
  true
end