Module: Morpheus::Cli::CliCommand

Included in:
AccessTokenCommand, AccountGroupsCommand, ActivityCommand, AliasCommand, ApplianceSettingsCommand, ApprovalsCommand, Apps, ArchivesCommand, BackupJobsCommand, BackupSettingsCommand, BackupsCommand, BenchmarkCommand, BlueprintsCommand, BootScriptsCommand, BudgetsCommand, CatCommand, CatalogCommand, CatalogItemTypesCommand, CertificatesCommand, ChangePasswordCommand, CloudDatastoresCommand, CloudFoldersCommand, CloudResourcePoolsCommand, Clouds, Clusters, ColoringCommand, ContainersCommand, CurlCommand, CypherCommand, DashboardCommand, DebugCommand, Deploy, Deployments, Deploys, DocCommand, Echo, EditProfileCommand, EditRcCommand, EnvironmentsCommand, ExecuteSchedulesCommand, ExecutionRequestCommand, ExitCommand, FileCopyRequestCommand, ForgotPassword, GetPromptCommand, Groups, GuidanceCommand, HealthCommand, HistoryCommand, Hosts, ImageBuilderCommand, InstanceTypes, Instances, IntegrationsCommand, InvoicesCommand, JobsCommand, KeyPairs, LibraryClusterLayoutsCommand, LibraryContainerScriptsCommand, LibraryContainerTemplatesCommand, LibraryContainerTypesCommand, LibraryInstanceTypesCommand, LibraryLayoutsCommand, LibraryOptionListsCommand, LibraryOptionTypesCommand, LibrarySpecTemplatesCommand, LibraryUpgradesCommand, License, LoadBalancers, LogLevelCommand, LogSettingsCommand, Login, Logout, LogsCommand, ManCommand, MonitoringAlertsCommand, MonitoringAppsCommand, MonitoringChecksCommand, MonitoringContactsCommand, MonitoringGroupsCommand, MonitoringIncidentsCommand, NetworkDomainsCommand, NetworkGroupsCommand, NetworkPoolServersCommand, NetworkPoolsCommand, NetworkProxiesCommand, NetworkRoutersCommand, NetworkServicesCommand, NetworksCommand, PackagesCommand, Ping, PoliciesCommand, PowerSchedulesCommand, PreseedScriptsCommand, PriceSetsCommand, PricesCommand, Processes, Projects, ProvisioningLicensesCommand, ProvisioningSettingsCommand, RecentActivityCommand, Remote, RemoveFileCommand, ReportsCommand, Roles, SearchCommand, SecurityGroupRules, SecurityGroups, ServicePlanCommand, SetPromptCommand, Setup, Shell, Sleep, SourceCommand, SslVerificationCommand, StorageProvidersCommand, SubnetsCommand, Tasks, TeeCommand, TenantsCommand, UpdateCommand, UsageCommand, UserGroupsCommand, UserSettingsCommand, UserSourcesCommand, Users, VdiAllocationsCommand, VdiAppsCommand, VdiCommand, VdiGatewaysCommand, VdiPoolsCommand, VersionCommand, VirtualImages, WhitelabelSettingsCommand, Whoami, WikiCommand, Workflows
Defined in:
lib/morpheus/cli/cli_command.rb

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



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

def no_prompt
  @no_prompt
end

Class Method Details

.included(klass) ⇒ Object



21
22
23
24
25
26
# File 'lib/morpheus/cli/cli_command.rb', line 21

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

Instance Method Details

#apply_options(payload, options, object_key = nil) ⇒ Object

support -O OPTION switch



1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
# File 'lib/morpheus/cli/cli_command.rb', line 1292

def apply_options(payload, options, object_key=nil)
  payload ||= {}
  if options[:options]
    if object_key
      payload.deep_merge!({object_key => options[:options].reject {|k,v| k.is_a?(Symbol)}})
    else
      payload.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol)})
    end
  end
  payload
end

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

appends to the passed OptionParser all the generic options

Parameters:

  • opts (OptionParser)

    the option parser object being constructed

  • options (Hash)

    the output Hash that is to being modified

  • includes (Array) (defaults to: [])

    which options to include eg. :options, :json, :remote

Returns:

  • opts



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
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
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
869
870
871
872
873
874
875
876
877
878
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
# File 'lib/morpheus/cli/cli_command.rb', line 291

def build_common_options(opts, options, includes=[], excludes=[])
  #opts.separator ""
  # opts.separator "Common options:"
  option_keys = includes.clone
  # todo: support --quiet everywhere
  # turn on some options all the time..
  # unless command_name == "shell"
  #   option_keys << :quiet unless option_keys.include?(:quiet)
  # end

  # ensure commands can always access options[:options], until we can deprecate it...
  options[:options] ||= {}

  while (option_key = option_keys.shift) do
    case option_key.to_sym

    when :tenant, :account
      # todo: let's deprecate this in favor of :tenant --tenant to keep -a reserved for --all perhaps?
      opts.on('--tenant TENANT', String, "Tenant (Account) Name or ID") do |val|
        options[:account] = val
      end
      opts.on('--tenant-id ID', String, "Tenant (Account) ID") do |val|
        options[:account_id] = val
      end
      # todo: let's deprecate this in favor of :tenant --tenant to keep -a reserved for --all perhaps?
      opts.on('-a','--account ACCOUNT', "Alias for --tenant") do |val|
        options[:account] = val
      end
      opts.on('-A','--account-id ID', "Tenant (Account) ID") do |val|
        options[:account_id] = val
      end
      opts.add_hidden_option('--tenant-id') if opts.is_a?(Morpheus::Cli::OptionParser)
      opts.add_hidden_option('-a, --account') if opts.is_a?(Morpheus::Cli::OptionParser)
      opts.add_hidden_option('-A, --account-id') if opts.is_a?(Morpheus::Cli::OptionParser)

    when :details
      opts.on('-a', '--all', "Show all details." ) do
        options[:details] = true
      end
      opts.on('--details', '--details', "Show more details" ) do
        options[:details] = true
      end
      opts.add_hidden_option('--details')

    when :sigdig
      opts.on('--sigdig DIGITS', "Significant digits to display for prices (currency). Default is #{default_sigdig}.") do |val|
        options[:sigdig] = val.to_i
      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] == '}') || (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] == '}') || (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 |val|
        # api supports max=-1 for all at the moment..
        if val.to_s == "all" || val.to_s == "-1"
          options[:max] = "-1"
        else
          max = val.to_i
          if max <= 0
            raise ::OptionParser::InvalidArgument.new("must be a positive integer")
          end
          options[:max] = max
        end
      end

      opts.on( '-o', '--offset OFFSET', "Offset Results" ) do |val|
        offset = val.to_i
        if offset <= 0
          raise ::OptionParser::InvalidArgument.new("must be a positive integer")
        end
        options[:offset] = offset
      end

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

      opts.on( '-S', '--sort ORDER', "Sort Order. DIRECTION may be included as \"ORDER [asc|desc]\"." ) do |v|
        if v.to_s.include?(",")
          # sorting on multiple properties, just pass it as is, newer api supports multiple fields
          options[:sort] = v
        else
          v_parts = v.to_s.split(" ")
          if v_parts.size > 1
            options[:sort] = v_parts[0]
            options[:direction] = (v_parts[1].strip == "desc") ? "desc" : "asc"
          else
            options[:sort] = v
          end
        end
      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 'foo=bar&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"
      # or pass it many times like -Q foo=bar -Q hello=world
      opts.on( '-Q', '--query PARAMS', "Query parameters. PARAMS format is 'foo=bar&category=web'" ) do |val|
        if options[:query_filters_raw] && !options[:query_filters_raw].empty?
          options[:query_filters_raw] += ("&" + val)
        else
          options[:query_filters_raw] = val
        end
        options[:query_filters] ||= {}
        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 :find_by_name
      opts.on('--find-by-name', "Always treat the identifier argument as a name, never an ID. Useful for specifying names that look like numbers. eg. '1234'" ) do
        options[:find_by_name] = true
      end
      # opts.add_hidden_option('--find-by-name') if opts.is_a?(Morpheus::Cli::OptionParser)

    when :remote
      opts.on( '-r', '--remote REMOTE', "Remote name. The current remote is used by default." ) do |val|
        options[:remote] = val
      end
      opts.on( '--remote-url URL', '--remote-url URL', "Remote url. This allows adhoc requests instead of using a configured remote." ) do |val|
        options[:remote_url] = val
      end
      opts.on( '-T', '--token TOKEN', "Access token for authentication with --remote. Saved credentials are used by default." ) do |val|
        options[:remote_token] = val
      end unless excludes.include?(:remote_token)
      opts.on( '--token-file FILE', String, "Token File, read a file containing the access token." ) do |val|
        token_file = File.expand_path(val)
        if !File.exists?(token_file) || !File.file?(token_file)
          raise ::OptionParser::InvalidOption.new("File not found: #{token_file}")
        end
        options[:remote_token] = File.read(token_file).to_s.split("\n").first.strip
      end
      opts.add_hidden_option('--token-file') if opts.is_a?(Morpheus::Cli::OptionParser)
      opts.on( '-U', '--username USERNAME', "Username for authentication." ) do |val|
        options[:remote_username] = val
      end unless excludes.include?(:remote_username)
      

      unless excludes.include?(:remote_password)
        opts.on( '-P', '--password PASSWORD', "Password for authentication." ) do |val|
          options[:remote_password] = val
        end
        opts.on( '--password-file FILE', String, "Password File, read a file containing the password for authentication." ) do |val|
          password_file = File.expand_path(val)
          if !File.exists?(password_file) || !File.file?(password_file)
            raise ::OptionParser::InvalidOption.new("File not found: #{password_file}")
          end
          file_content = File.read(password_file) #.strip
          options[:remote_password] = File.read(password_file).to_s.split("\n").first
        end
        opts.add_hidden_option('--password-file') if opts.is_a?(Morpheus::Cli::OptionParser)
      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
    
    #when :header, :headers
      opts.on( '-H', '--header HEADER', "Additional HTTP header to include with requests." ) do |val|
        options[:headers] ||= {}
        # header_list = val.to_s.split(',')
        header_list = [val.to_s]
        header_list.each do |h|
          header_parts = val.to_s.split(":")
          header_key, header_value = header_parts[0], header_parts[1..-1].join(":").strip
          if header_parts.size() < 2
            header_parts = val.to_s.split("=")
            header_key, header_value = header_parts[0], header_parts[1..-1].join("=").strip
          end
          if header_parts.size() < 2
            raise_command_error "Invalid HEADER value '#{val}'. HEADER should contain a key and a value. eg. -H 'X-Morpheus-Lease: $MORPHEUS_LEASE_TOKEN'"
          end
          options[:headers][header_key] = header_value
        end
      end
      # opts.add_hidden_option('-H') if opts.is_a?(Morpheus::Cli::OptionParser)
      # opts.add_hidden_option('--header') if opts.is_a?(Morpheus::Cli::OptionParser)
      opts.add_hidden_option('-H, --header') if opts.is_a?(Morpheus::Cli::OptionParser)

    #when :timeout
      opts.on( '--timeout SECONDS', "Timeout for api requests. Default is typically 30 seconds." ) do |val|
        options[:timeout] = val ? val.to_f : nil
      end
      opts.add_hidden_option('--timeout') if opts.is_a?(Morpheus::Cli::OptionParser)

    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
      # -y for --yes and for --yaml
      if includes.include?(:auto_confirm)
        opts.on(nil, '--yaml', "YAML Output") do
          options[:yaml] = true
          options[:format] = :yaml
        end
      else
        opts.on('-y', '--yaml', "YAML Output") do
          options[:yaml] = true
          options[:format] = :yaml
        end
      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
      # deprecated --csv-delim, use --delimiter instead
      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.add_hidden_option('--csv-delim') if opts.is_a?(Morpheus::Cli::OptionParser)

      # deprecated --csv-newline, use --newline instead
      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.to_s.gsub("\\n", "\n").gsub("\\r", "\r").gsub("\\t", "\t") if val.include?("\\")
          options[:csv_newline] = val
        end
      end
      opts.add_hidden_option('--csv-newline') if opts.is_a?(Morpheus::Cli::OptionParser)

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

      opts.on(nil, '--csv-no-header', "Exclude header for CSV Output.") do
        options[:csv] = true
        options[:format] = :csv
        options[:csv_no_header] = true
      end
      opts.add_hidden_option('--csv-no-header') if opts.is_a?(Morpheus::Cli::OptionParser)

      opts.on(nil, '--quotes', "Wrap CSV values with \". Default: false") do
        options[:csv_quotes] = true
      end
      opts.add_hidden_option('--csv-quotes') if opts.is_a?(Morpheus::Cli::OptionParser)

      opts.on(nil, '--no-header', "Exclude header for CSV Output.") do
        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 for json,csv,yaml.") do |val|
        if val.size == 1 && val[0].downcase == 'all'
          options[:all_fields] = true
        else
          options[:include_fields] = val
        end
      end
      opts.on('-F', '--old-fields x,y,z', Array, "alias for -f, --fields") do |val|
        if val.size == 1 && val[0].downcase == 'all'
          options[:all_fields] = true
        else
          options[:include_fields] = val
        end
      end
      opts.add_hidden_option('-F,') if opts.is_a?(Morpheus::Cli::OptionParser)
      opts.on(nil, '--all-fields', "Show all fields present in the data.") do
        options[:all_fields] = true
      end
      opts.on(nil, '--wrap', "Wrap table columns instead hiding them when terminal is not wide enough.") do
        options[:wrap] = true
      end
    when :select
      #opts.add_hidden_option('--all-fields') if opts.is_a?(Morpheus::Cli::OptionParser)
      opts.on('--select x,y,z', String, "Filter Output to just print the value(s) of specific fields.") do |val|
        options[:select_fields] = val.split(',').collect {|r| r.strip}
      end

    when :delim
      opts.on('--delimiter [CHAR]', String, "Delimiter for output values. Default: ',', use with --select and --csv") do |val|
        options[:csv] = true
        options[:format] = :csv
        val = val.to_s
        val = val.gsub("\\n", "\n").gsub("\\r", "\r").gsub("\\t", "\t") if val.include?("\\")
        options[:delim] = val
      end

      opts.on('--newline [CHAR]', String, "Delimiter for output rows. Default: '\\n', use with --select and --csv") do |val|
        options[:csv] = true
        options[:format] = :csv
        val = val.to_s
        if val == "no" || val == "none"
          options[:newline] = ""
        else
          val = val.to_s.gsub("\\n", "\n").gsub("\\r", "\r").gsub("\\t", "\t") if val.include?("\\")
          options[:newline] = val
        end
      end
    when :thin
      opts.on( '--thin', '--thin', "Format headers and columns with thin borders." ) do |val|
        options[:border_style] = :thin
      end
      
    

    when :dry_run
      opts.on('-d','--dry-run', "Dry Run, print the API request instead of executing it.") do
        # todo: this should print after parsing obv..
        # need a hook after parse! or a standard_handle(options) { ... } paradigm
        # either that or hook it up in every command somehow, maybe a hook on connect()
        #puts "#{cyan}#{dark} #=> DRY RUN#{reset}"
        # don't print this for --json combined with -d
        # print once and dont munge json
        if !options[:curl] && !options[:json]
          puts "#{cyan}#{bold}#{dark}DRY RUN#{reset}"
        end
        options[:dry_run] = true
      end
      opts.on(nil,'--curl', "Curl, print the API request as a curl command instead of executing it.") do
        # print once and dont munge json
        if !options[:dry_run] && !options[:json]
          puts "#{cyan}#{bold}#{dark}DRY RUN#{reset}"
        end
        options[:dry_run] = true
        options[:curl] = true
      end
      opts.on(nil,'--scrub', "Mask secrets in output, such as the Authorization header. For use with --curl and --dry-run.") do
        options[:scrub] = true
      end
      # dry run comes with hidden outfile options
      #opts.add_hidden_option('--scrub') if opts.is_a?(Morpheus::Cli::OptionParser)
      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
      opts.add_hidden_option('--out') if opts.is_a?(Morpheus::Cli::OptionParser)
      opts.on('--overwrite', '--overwrite', "Overwrite output file if it already exists.") do
        options[:overwrite] = true
      end
      opts.add_hidden_option('--overwrite') if opts.is_a?(Morpheus::Cli::OptionParser)

    when :outfile
      opts.on('--out FILE', String, "Write standard output to a file instead of the terminal.") do |val|
        options[:outfile] = val
      end
      opts.on('--overwrite', '--overwrite', "Overwrite output file if it already exists.") do |val|
        options[:overwrite] = 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

  # always support thin, but hidden because mostly not hooked up at the moment...
  unless includes.include?(:thin)
    opts.on( '--thin', '--thin', "Format headers and columns with thin borders." ) do |val|
      options[:border_style] = :thin
    end
    opts.add_hidden_option('--thin') if opts.is_a?(Morpheus::Cli::OptionParser)
  end

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


  # Benchmark this command?
  # Also useful for seeing exit status for every command.
  opts.on('-B','--benchmark', "Print benchmark time and exit/error after the command is finished.") do
    options[:benchmark] = true
    # this is hacky, but working!  
    # shell handles returning to false
    #Morpheus::Benchmarking.enabled = true
    #my_terminal.benchmarking = true
    #start_benchmark(args.join(' '))
    # ok it happens outside of handle() alltogether..
    # wow, simplify me plz
  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

  # A way to ensure debugging is off, it should go back on after the command is complete.
  opts.on('--no-debug','--no-debug', "Disable debugging.") do
    options[:debug] = false
    Morpheus::Logging.set_log_level(Morpheus::Logging::Logger::INFO)
    ::RestClient.log = Morpheus::Logging.debug? ? Morpheus::Logging::DarkPrinter.instance : nil
  end
  opts.add_hidden_option('--no-debug') if opts.is_a?(Morpheus::Cli::OptionParser)

  opts.on('--hidden-help', "Print help that includes all the hidden options, like this one." ) do
    puts opts.full_help_message({show_hidden_options:true})
    exit # return 0 maybe?
  end
  opts.add_hidden_option('--hidden-help') if opts.is_a?(Morpheus::Cli::OptionParser)
  opts.on('-h', '--help', "Print this help" ) do
    puts opts
    exit # return 0 maybe?
  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”

Parameters:

  • opts (OptionParser)
  • options (Hash)

    output map that is being constructed

  • option_types (Array) (defaults to: [])

    list of OptionType definitions to add

Returns:

  • void, this modifies the opts in place.



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

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)' : ''}"
    if option_type['description']
      # description << "\n                                     #{option_type['description']}"
      description << " - #{option_type['description']}"
    end
    if option_type['defaultValue']
      description << ". Default: #{option_type['defaultValue']}"
    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'] == 'multiSelect'
      value_label = 'LIST'
    # elsif option_type['type'] == 'select'
    #   value_label = 'SELECT'
    # elsif option['type'] == 'select'
    end
    full_option = "--#{full_field_name} #{value_label}"
    # switch is an alias for the full option name, fieldName is the default
    if option_type['switch']
      full_option = "--#{option_type['switch']} #{value_label}"
    end
    arg1, arg2 = full_option, String
    if option_type['shorthand']
      arg1, arg2 = full_option, option_type['shorthand']
    end
    opts.on(arg1, arg2, description) do |val|
      if option_type['type'] == 'checkbox'
        val = (val.to_s != 'false' && val.to_s != 'off')
      else
        # attempt to parse JSON, this allows blank arrays for multiSelect like --tenants []
        if (val.to_s[0] == '{' && val.to_s[-1] == '}') || (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
      end
      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

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



269
270
271
# File 'lib/morpheus/cli/cli_command.rb', line 269

def build_standard_add_options(opts, options, includes=[], excludes=[])
  build_standard_post_options(opts, options, includes, excludes)
end

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



260
261
262
# File 'lib/morpheus/cli/cli_command.rb', line 260

def build_standard_delete_options(opts, options, includes=[], excludes=[])
  build_common_options(opts, options, includes + [:auto_confirm, :query, :json, :quiet, :dry_run, :remote], excludes)
end

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

the standard options for a command that makes api requests (most of them)



248
249
250
# File 'lib/morpheus/cli/cli_command.rb', line 248

def build_standard_get_options(opts, options, includes=[], excludes=[])
  build_common_options(opts, options, includes + [:query, :json, :yaml, :csv, :fields, :select, :delim, :quiet, :dry_run, :remote], excludes)
end

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

list is GET that supports phrase,max,offset,sort,direction



265
266
267
# File 'lib/morpheus/cli/cli_command.rb', line 265

def build_standard_list_options(opts, options, includes=[], excludes=[])
  build_standard_get_options(opts, options, [:list] + includes, excludes=[])
end

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



252
253
254
# File 'lib/morpheus/cli/cli_command.rb', line 252

def build_standard_post_options(opts, options, includes=[], excludes=[])
  build_common_options(opts, options, includes + [:options, :payload, :json, :quiet, :dry_run, :remote], excludes)
end

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



256
257
258
# File 'lib/morpheus/cli/cli_command.rb', line 256

def build_standard_put_options(opts, options, includes=[], excludes=[])
  build_standard_post_options(opts, options, includes, excludes)
end

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



277
278
279
# File 'lib/morpheus/cli/cli_command.rb', line 277

def build_standard_remove_options(opts, options, includes=[], excludes=[])
  build_standard_delete_options(opts, options, includes, excludes)
end

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



273
274
275
# File 'lib/morpheus/cli/cli_command.rb', line 273

def build_standard_update_options(opts, options, includes=[], excludes=[])
  build_standard_put_options(opts, options, includes, excludes)
end

#command_descriptionObject



918
919
920
# File 'lib/morpheus/cli/cli_command.rb', line 918

def command_description
  self.class.command_description
end

#command_nameObject



914
915
916
# File 'lib/morpheus/cli/cli_command.rb', line 914

def command_name
  self.class.command_name
end

#default_refresh_intervalObject



952
953
954
# File 'lib/morpheus/cli/cli_command.rb', line 952

def default_refresh_interval
  self.class.default_refresh_interval
end

#default_sigdigObject

number of decimal places to show with curreny



282
283
284
# File 'lib/morpheus/cli/cli_command.rb', line 282

def default_sigdig
  2
end

#default_subcommandObject



948
949
950
# File 'lib/morpheus/cli/cli_command.rb', line 948

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” By default it will connect to the active (current) remote appliance 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. This will prompt for credentials if none are found, use :skip_login Credentials will be saved unless –remote-url or –token is being used.



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
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
# File 'lib/morpheus/cli/cli_command.rb', line 1076

def establish_remote_appliance_connection(options)
  # todo: probably refactor and don't rely on this method to set these instance vars
  @remote_appliance = nil
  @appliance_name, @appliance_url, @access_token = nil, nil, nil
  @api_client = nil
  @do_save_credentials = true
  # skip saving if --remote-url or --username or --password are passed in
  if options[:remote_url] || options[:remote_token] || options[:remote_username] || options[:remote_password]
    @do_save_credentials = false
  end
  appliance = nil
  if options[:remote_url]
    # --remote-url means use an arbitrary url, do not save any appliance config
    # appliance = {name:'remote-url', url:options[:remote_url]}
    appliance = {url:options[:remote_url]}
    appliance[:temporary] = true
    #appliance[:status] = "ready" # or  "unknown"
    # appliance[:last_check] = nil
  elsif options[:remote]
    # --remote means use the specified remote
    appliance = ::Morpheus::Cli::Remote.load_remote(options[:remote])
    if appliance.nil?
      if ::Morpheus::Cli::Remote.appliances.empty?
        raise_command_error "No remote appliances exist, see the command `remote add`."
      else
        raise_command_error "Remote appliance not found by the name '#{options[:remote]}', see `remote list`"
      end
    end
  else
    # use active remote
    appliance = ::Morpheus::Cli::Remote.load_active_remote()
    if !appliance
      if ::Morpheus::Cli::Remote.appliances.empty?
        raise_command_error "No remote appliances exist, see the command `remote add`"
      else
        raise_command_error "#{command_name} requires a remote to be specified, try the option -r [remote] or see the command `remote use`"
      end
    end
  end
  @remote_appliance = appliance
  @appliance_name = appliance[:name]
  @appliance_url = appliance[:url] || appliance[:host] # it used to store :host in the YAML
  # set enable_ssl_verification
  # 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...
  allow_insecure = false
  if options[:insecure] || appliance[:insecure] || Morpheus::Cli::Shell.insecure
    allow_insecure = true
  end
  @verify_ssl = !allow_insecure
  # Morpheus::RestClient.enable_ssl_verification = allow_insecure != true
  if allow_insecure && Morpheus::RestClient.ssl_verification_enabled?
    Morpheus::RestClient.enable_ssl_verification = false
  elsif !allow_insecure && !Morpheus::RestClient.ssl_verification_enabled?
    Morpheus::RestClient.enable_ssl_verification = true
  end

  # always support 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 remote #{display_appliance(@appliance_name, @appliance_url)}" if Morpheus::Logging.debug? # && !options[:quiet]

  if options[:no_authorization]
    # maybe handle this here..
    options[:skip_login] = true
    options[:skip_verify_access_token] = true
  end

  # ok, get some credentials.
  # use saved credentials by default or prompts for username, password.
  # passing --remote-url will skip loading saved credentials and prompt for login to use with the url
  # passing --token skips login prompting and uses the provided token.
  # passing --token or --username will skip saving credentials to appliance config, they are just used for one command
  # ideally this should not prompt now and wait until the client is used on a protected endpoint.
  # @wallet = nil
  if options[:remote_token]
    @wallet = {'access_token' => options[:remote_token]} #'username' => 'anonymous'
  elsif options[:remote_url]
    credentials = Morpheus::Cli::Credentials.new(@appliance_name, @appliance_url)
    unless options[:skip_login]
      @wallet = credentials.request_credentials(options, @do_save_credentials)
    end
  else
    credentials = Morpheus::Cli::Credentials.new(@appliance_name, @appliance_url)
    # use saved credentials unless --username or passed
    unless options[:remote_username]
      @wallet = credentials.load_saved_credentials()
    end
    # using active remote OR --remote flag
    # used saved credentials or login
    # ideally this sould not prompt now and wait  until the client is used on a protected endpoint.

    
    if @wallet.nil? || @wallet['access_token'].nil?
      unless options[:skip_login]
        @wallet = credentials.request_credentials(options, @do_save_credentials)
      end
    end
    
  end
  @access_token = @wallet ? @wallet['access_token'] : nil

  # validate we have a token
  # hrm...
  unless options[:skip_verify_access_token]
    if @access_token.empty?
      raise AuthorizationRequiredError.new("Failed to acquire access token for #{display_appliance(@appliance_name, @appliance_url)}. Verify your credentials are correct.")  
    end
  end

  # ok, connect to the appliance.. actually this just instantiates an ApiClient
  api_client = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url, @verify_ssl)
  @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



982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
# File 'lib/morpheus/cli/cli_command.rb', line 982

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

#get_subcommand_description(subcmd) ⇒ Object

def subcommand_descriptions

self.class.subcommand_descriptions

end



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

def get_subcommand_description(subcmd)
  self.class.get_subcommand_description(subcmd)
end

#handle(args) ⇒ Object



1037
1038
1039
# File 'lib/morpheus/cli/cli_command.rb', line 1037

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

#handle_subcommand(args) ⇒ Object

a default handler



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

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
    error_msg = "'#{command_name} #{subcommand_name}' is not a #{prog_name} command.\n#{full_command_usage}"
    raise CommandNotFoundError.new(error_msg)
  end
  self.send(cmd_method, args[1..-1])
end

#interactive?Boolean

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

Returns:

  • (Boolean)


97
98
99
# File 'lib/morpheus/cli/cli_command.rb', line 97

def interactive?
  @no_prompt != true
end

#my_help_commandObject



964
965
966
# File 'lib/morpheus/cli/cli_command.rb', line 964

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

#my_terminalMorpheus::Terminal

Returns the terminal this command is being executed inside of.

Returns:



34
35
36
# File 'lib/morpheus/cli/cli_command.rb', line 34

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

#my_terminal=(term) ⇒ Object

set the terminal running this command.

Parameters:

  • term (MorpheusTerminal)

    the terminal this command is assigned to

Returns:

  • the Terminal this command is being executed inside of



41
42
43
44
45
46
# File 'lib/morpheus/cli/cli_command.rb', line 41

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

#parse_bytes_param(bytes_param, option, assumed_unit = nil) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/morpheus/cli/cli_command.rb', line 118

def parse_bytes_param(bytes_param, option, assumed_unit = nil)
  if bytes_param && bytes_param.to_f > 0
    bytes_param.upcase!
    multiplier = 1
    unit = nil
    number = (bytes_param.to_f == bytes_param.to_i ? bytes_param.to_i : bytes_param.to_f)
    if (bytes_param.end_with? 'GB') || ((!bytes_param.end_with? 'MB') && assumed_unit == 'GB')
      unit = 'GB'
      multiplier = 1024 * 1024 * 1024
    elsif (bytes_param.end_with? 'MB') || assumed_unit == 'MB'
      unit = 'MB'
      multiplier = 1024 * 1024
    end
    return {:bytes_param => bytes_param, :bytes => number * multiplier, :number => number, :multiplier => multiplier, :unit => unit}
  end
  raise_command_error "Invalid value for #{option} option"
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...

Parameters:

  • id_list (String or Array of Strings)
  • delim (String) (defaults to: /\s*\,\s*/)

    Default is a comma and any surrounding white space.

Returns:

  • array of values



114
115
116
# File 'lib/morpheus/cli/cli_command.rb', line 114

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 this includes the :query options too via parse_query_options(). returns Hash of params the format => “foobar”, “max”: 100



1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
# File 'lib/morpheus/cli/cli_command.rb', line 1228

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
  list_params.merge!(parse_query_options(options))
  
  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”]



1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
# File 'lib/morpheus/cli/cli_command.rb', line 1260

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

#parse_passed_options(options) ⇒ Object

this returns all the options passed in by -O, parsed all nicely into objects.



137
138
139
140
# File 'lib/morpheus/cli/cli_command.rb', line 137

def parse_passed_options(options)
  passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
  return passed_options
end

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



1281
1282
1283
1284
1285
1286
1287
1288
1289
# File 'lib/morpheus/cli/cli_command.rb', line 1281

def parse_payload(options={}, object_key=nil)
  payload = nil
  if options[:payload]
    payload = options[:payload]
    # support -O OPTION switch on top of --payload
    apply_options(payload, options, object_key)
  end
  payload
end

#parse_query_options(options = {}) ⇒ Object

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



1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
# File 'lib/morpheus/cli/cli_command.rb', line 1245

def parse_query_options(options={})
  list_params = {}
  # 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

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



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

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


69
70
71
# File 'lib/morpheus/cli/cli_command.rb', line 69

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

#println(*msgs) ⇒ Object



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

def println(*msgs)
  print(*msgs)
  print "\n"
end

#prog_nameObject



910
911
912
# File 'lib/morpheus/cli/cli_command.rb', line 910

def prog_name
  self.class.prog_name
end

#puts(*msgs) ⇒ Object



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

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

#puts_error(*msgs) ⇒ Object



73
74
75
# File 'lib/morpheus/cli/cli_command.rb', line 73

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

#raise_args_error(msg, args = [], optparse = nil, exit_code = nil) ⇒ Object



105
106
107
# File 'lib/morpheus/cli/cli_command.rb', line 105

def raise_args_error(msg, args=[], optparse=nil, exit_code=nil)
  raise Morpheus::Cli::CommandArgumentsError.new(msg, args, optparse, exit_code)
end

#raise_command_error(msg, args = [], optparse = nil, exit_code = nil) ⇒ Object



101
102
103
# File 'lib/morpheus/cli/cli_command.rb', line 101

def raise_command_error(msg, args=[], optparse=nil, exit_code=nil)
  raise Morpheus::Cli::CommandError.new(msg, args, optparse, exit_code)
end

#render_response(json_response, options, object_key = nil, &block) ⇒ Object Also known as: render_with_format

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



1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
# File 'lib/morpheus/cli/cli_command.rb', line 1329

def render_response(json_response, options, object_key=nil, &block)
  output = nil
  if options[:select_fields]
    row = object_key ? json_response[object_key] : json_response
    row = [row].flatten()
    if row.is_a?(Array)
      output = [row].flatten.collect { |record| 
        options[:select_fields].collect { |field| 
          value = get_object_value(record, field)
          value.is_a?(String) ? value : JSON.fast_generate(value)
        }.join(options[:delim] || ",")
      }.join(options[:newline] || "\n")
    else
      output = records_as_csv([row], options)
    end
  elsif 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
    if row.is_a?(Array)
      output = records_as_csv(row, options)
    else
      output = records_as_csv([row], options)
    end
  end
  if options[:outfile]
    full_outfile = File.expand_path(options[:outfile])
    if output
      print_to_file(output, options[:outfile], options[:overwrite])
      print "#{cyan}Wrote output to file #{options[:outfile]} (#{File.size(full_outfile)} B)\n" unless options[:quiet]
    else
      # uhhh ok lets try this
      Morpheus::Logging::DarkPrinter.puts "using experimental feature: --out without a common format like json, yml or csv" if Morpheus::Logging.debug?
      result = with_stdout_to_file(options[:outfile], options[:overwrite], 'w+', &block)
      if result && result != 0
        return result
      end
      print "#{cyan}Wrote output to file #{options[:outfile]} (#{File.size(full_outfile)} B)\n" unless options[:quiet]
      return 0, nil
    end
  else
    # --quiet means do not render, still want to print to outfile though
    if options[:quiet]
      return 0, nil
    end
    # render ouput generated above
    if output
      puts output
      return 0, nil
    else
      # no render happened, so calling the block if given
      if block_given?
        result = yield
        if result
          return result
        else
          return 0, nil
        end
      else
        # nil means nothing was rendered, some methods still using render_with_format() are relying on this
        return nil
      end
    end
  end
end

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

executes block with each argument in the list

Returns:

  • (0|1)

    0 if they were all successful, else 1



1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
# File 'lib/morpheus/cli/cli_command.rb', line 1043

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
  # find a bad result and return it
  cmd_results = cmd_results.collect do |cmd_result| 
    if cmd_result.is_a?(Array)
      cmd_result
    else
      [cmd_result, nil]
    end
  end
  failed_result = cmd_results.find {|cmd_result| cmd_result[0] == false || (cmd_result[0].is_a?(Integer) && cmd_result[0] != 0) }
  return failed_result ? failed_result : cmd_results.last
end

#subcommand_aliasesObject



930
931
932
# File 'lib/morpheus/cli/cli_command.rb', line 930

def subcommand_aliases
  self.class.subcommand_aliases
end

#subcommand_descriptionObject



942
943
944
945
946
# File 'lib/morpheus/cli/cli_command.rb', line 942

def subcommand_description()
  calling_method = caller[0][/`([^']*)'/, 1].to_s.sub('block in ', '')
  subcommand_name = subcommands.key(calling_method)
  subcommand_name ? get_subcommand_description(subcommand_name) : nil
end

#subcommand_usage(*extra) ⇒ Object



968
969
970
971
972
973
974
975
976
977
# File 'lib/morpheus/cli/cli_command.rb', line 968

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: #{prog_name} #{command_name} #{subcommand_name} #{extra.join(' ')}".squeeze(' ').strip
end

#subcommandsObject



922
923
924
# File 'lib/morpheus/cli/cli_command.rb', line 922

def subcommands
  self.class.subcommands
end

#usageObject



956
957
958
959
960
961
962
# File 'lib/morpheus/cli/cli_command.rb', line 956

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

#validate_outfile(outfile, options) ⇒ Object



1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
# File 'lib/morpheus/cli/cli_command.rb', line 1304

def validate_outfile(outfile, options)
  full_filename = File.expand_path(outfile)
  outdir = File.dirname(full_filename)
  if Dir.exists?(full_filename)
    print_red_alert "[local-file] is invalid. It is the name of an existing directory: #{outfile}"
    return false
  end
  if !Dir.exists?(outdir)
    if options[:mkdir]
      print cyan,"Creating local directory #{outdir}",reset,"\n"
      FileUtils.mkdir_p(outdir)
    else
      print_red_alert "[local-file] is invalid. Directory not found: #{outdir}"
      return false
    end
  end
  if File.exists?(full_filename) && !options[:overwrite]
    print_red_alert "[local-file] is invalid. File already exists: #{outfile}\nUse -f to overwrite the existing file."
    return false
  end
  return true
end

#verify_args!(opts = {}) ⇒ Object

verify_args! verifies that the right number of commands were passed and raises a command error if not. Example: verify_args!(args:args, count:1, optparse:optparse) this could go be done in optparse.parse instead perhaps



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/cli_command.rb', line 1202

def verify_args!(opts={})
  args = opts[:args] || []
  if opts[:count]
    if args.count < opts[:count]
      raise_args_error("not enough arguments, expected #{opts[:count]} and got #{args.count == 0 ? '0' : args.count.to_s + ': '}#{args.join(', ')}", args, opts[:optparse])
    elsif args.count > opts[:count]
      raise_args_error("too many arguments, expected #{opts[:count]} and got #{args.count == 0 ? '0' : args.count.to_s + ': '}#{args.join(', ')}", args, opts[:optparse])
    end
  else
    if opts[:min]
      if args.count < opts[:min]
        raise_args_error("not enough arguments, expected #{opts[:min] || '0'}-#{opts[:max] || 'N'} and got #{args.count == 0 ? '0' : args.count.to_s + ': '}#{args.join(', ')}", args, opts[:optparse])
      end
    end
    if opts[:max]
      if args.count > opts[:max]
        raise_args_error("too many arguments, expected #{opts[:min] || '0'}-#{opts[:max] || 'N'} and got #{args.count == 0 ? '0' : args.count.to_s + ': '}#{args.join(', ')}", args, opts[:optparse])
      end
    end
  end
  true
end

#visible_subcommandsObject



926
927
928
# File 'lib/morpheus/cli/cli_command.rb', line 926

def visible_subcommands
  self.class.visible_subcommands
end