Class: Morpheus::Cli::AliasCommand

Inherits:
Object
  • Object
show all
Includes:
CliCommand
Defined in:
lib/morpheus/cli/commands/alias_command.rb

Overview

This command allows the creation of an alias these aliases are stored in the $MORPHEUS_CLI_HOME/.morpheusrc See Morpheus::Cli::DotFile

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from CliCommand

#add_query_parameter, #apply_options, #build_common_options, #build_get_options, #build_list_options, #build_option_type_options, #build_standard_add_many_options, #build_standard_add_options, #build_standard_api_options, #build_standard_delete_options, #build_standard_get_options, #build_standard_list_options, #build_standard_post_options, #build_standard_put_options, #build_standard_remove_options, #build_standard_update_options, #command_description, #command_name, #confirm, #confirm!, #default_refresh_interval, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #execute_api, #execute_api_payload, #execute_api_request, #find_all, #find_all_json, #find_by_id, #find_by_name, #find_by_name_or_id, #find_record, #find_record_json, #full_command_usage, #get_interface, #get_list_key, #get_object_key, #get_subcommand_description, #handle_each_payload, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_array, #parse_bytes_param, #parse_get_options!, #parse_id_list, #parse_labels, #parse_list_options, #parse_list_options!, #parse_list_subtitles, #parse_options, #parse_parameter_as_resource_id!, #parse_passed_options, #parse_payload, #parse_query_options, #print, #print_error, #println, #prog_name, #puts, #puts_error, #raise_args_error, #raise_command_error, #render_response, #run_command_for_each_arg, #subcommand_aliases, #subcommand_description, #subcommand_usage, #subcommands, #usage, #validate_outfile, #verify_args!, #visible_subcommands

Constructor Details

#initializeAliasCommand

set_default_subcommand :add



14
15
# File 'lib/morpheus/cli/commands/alias_command.rb', line 14

def initialize() 
end

Instance Method Details

#add(args) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/morpheus/cli/commands/alias_command.rb', line 33

def add(args)
  options = {}
  do_export = false
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]='[command]'")
    #build_common_options(opts, options, [])
    opts.on( '-e', '--export', "Export this alias to your .morpheus_profile for future use" ) do
      do_export = true
    end
    opts.on('-h', '--help', "Print this help" ) do
      puts opts
      exit
    end
    formatted_commands_map = "    " + subcommands.sort.collect {|cmd| "\t#{cmd}" }.join("\n")
    opts.footer = <<-EOT
Define a new alias.
[name] is required. This is the alias name. It should be one word.
[command] is required. This is the full command wrapped in quotes.
Aliases can be exported for future use with the -e option.
The `alias add` command can be invoked with `alias [name]=[command]`

Examples: 
  alias cloud=clouds
  alias ij='instances get -j'
  alias new-hosts='hosts list -S id -D'
For more information, see https://github.com/gomorpheus/morpheus-cli/wiki/Alias
EOT
    
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, min: 1)
  
  # make this super forgiving.. my name = command -j -O value=woot
  # the old way, as one argument "name='command'"
  # no spaces.. name="command -j -O value=woot"
  if (args.count == 1)
    alias_definition = args[0]
  elsif (args.count == 2)
    alias_definition = "#{args[0]}='#{args[1]}'"
  else
    # meh, never gets here now anyway.. 
    # alias_definition = args.join(' ')
    args_alias_str = ""
    alias_parts = args.join(' ').split('=')
    left_side = alias_parts[0]
    right_side = alias_parts[1..-1].join(' ')
    args_alias_str = ""
    alias_definition = "#{left_side}='#{right_side}'"
  end

    
    begin
      alias_name, command_string = Morpheus::Cli::CliRegistry.parse_alias_definition(alias_definition)
      if alias_name.empty? || command_string.empty?
        print_red_alert "invalid alias syntax: #{alias_definition}"
        return false
      end
      Morpheus::Cli::CliRegistry.instance.add_alias(alias_name, command_string)
      #print "registered alias #{alias_name}", "\n"
      if do_export
        # puts "exporting alias '#{alias_name}' now..."
        morpheus_profile = Morpheus::Cli::DotFile.new(Morpheus::Cli::DotFile.morpheus_profile_filename)
        morpheus_profile.export_aliases({(alias_name) => command_string})
      end
    rescue Morpheus::Cli::CliRegistry::BadAlias => err
      print_red_alert "#{err.message}"
      return false
    rescue => err
      # raise err  
      print_red_alert "#{err.message}"
      return false
    end

  if Morpheus::Cli::Shell.has_instance?
    Morpheus::Cli::Shell.instance.recalculate_auto_complete_commands()
  end

end

#export(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/alias_command.rb', line 112

def export(args)
  options = {}
  do_export = false
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[alias] [alias2] [alias3]")
    build_common_options(opts, options, [])
    opts.footer = "Export an alias, saving it to your .morpheus_profile for future use"
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, min: 1)
  alias_names = args
  alias_names.each do |arg|
    if !Morpheus::Cli::CliRegistry.has_alias?(arg)
      print_red_alert "alias not found by name '#{arg}'"
      return false
    end
  end
  alias_definitions = {}
  alias_names.each do |alias_name|
    alias_definitions[alias_name] = Morpheus::Cli::CliRegistry.instance.get_alias(alias_name)
  end
  morpheus_profile = Morpheus::Cli::DotFile.new(Morpheus::Cli::DotFile.morpheus_profile_filename)
  morpheus_profile.export_aliases(alias_definitions)
  
  # Morpheus::Cli::Shell.instance.recalculate_auto_complete_commands() if Morpheus::Cli::Shell.instance

end

#handle(args) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/morpheus/cli/commands/alias_command.rb', line 17

def handle(args)
  if args.empty?
    list(args)
    #add(args)
  elsif self.class.has_subcommand?(args[0])
    handle_subcommand(args)
  elsif (args.count == 1) && (args[0] == '-h' || args[0] == '--help')
    handle_subcommand(args)
  elsif (args.count == 1) || (args.count == 2 && args.include?('-e'))
    add(args)
  else
    handle_subcommand(args)
    #list([])
  end
end

#list(args) ⇒ Object



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/morpheus/cli/commands/alias_command.rb', line 178

def list(args)
  options = {format:'table', sort:'name'}
  do_export = false
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage()
    opts.on( '-f', '--format FORMAT', "The format for the output: export, json, list, table (default)." ) do |val|
      options[:format] = val
    end
    opts.on( '-e', '--export', "Include the '-e' switch after each alias in the output. This implies --format export." ) do
      options[:format] = 'export'
      do_export = true
    end
    build_common_options(opts, options, [:list, :json])
    opts.footer = <<-EOT
Print list of defined aliases.    
Use the --format option to vary output.
The `alias list` command can be abbreviated as just `alias`.
For more information, see https://github.com/gomorpheus/morpheus-cli/wiki/Alias
EOT
  end
  optparse.parse!(args)

  my_aliases = Morpheus::Cli::CliRegistry.all_aliases.collect {|k,v|
    {name: k, command: v}
  }

  # todo: generic support :list options on a local Array
  if options[:phrase]
    # my_aliases = my_aliases.grep(/^#{Regexp.escape(options[:phrase])}/)
    match_regex = /#{Regexp.escape(options[:phrase])}/
    my_aliases = my_aliases.select {|it| 
      it[:name].to_s =~ match_regex || it[:command].to_s =~ match_regex
    }
  end

  options[:sort] ||= 'name'
  options[:direction] ||= 'asc'

  if options[:sort]
    if options[:sort].to_s == 'name' || options[:sort].to_s == 'alias'
      my_aliases = my_aliases.sort {|x,y| x[:name].to_s.downcase <=> y[:name].to_s.downcase }
    elsif options[:sort].to_s == 'command' || options[:sort].to_s == 'command_string'
      # just relies on the order they were registered in, heh...
      my_aliases = my_aliases.sort {|x,y| x[:command].to_s.downcase <=> y[:command].to_s.downcase }
    else
      # a-z is the default, and the best
    end
  end

  if options[:direction] == 'desc'
    my_aliases = my_aliases.reverse
  end
  if options[:offset]
    my_aliases = my_aliases.slice(options[:offset].to_i, my_aliases.size)
  end
  if options[:max]
    my_aliases = my_aliases.first(options[:max].to_i)
  end
  num_aliases = my_aliases.size
  out = ""
  if options[:json]
    options[:format] = 'json'
  end
  if options[:format] == 'json' || options[:json]
    alias_json = {}
    my_aliases.each do |it|
      alias_json[it[:name]] = it[:command]
    end
    out << JSON.pretty_generate({aliases: alias_json})
    out << "\n"
  elsif options[:format] == 'export' || options[:format] == 'e' || options[:format] == 'config'
    # out << "# morpheus aliases for #{`whoami`}\n" # windows!
    #out << "# morpheus aliases\n"
    my_aliases.each do |it|
      out <<  "alias #{it[:name]}='#{it[:command]}'"
      if do_export
        out << " -e"
      end
      out << "\n"
    end
  elsif options[:format] == 'list'
    my_aliases.each do |it|
      out <<  "#{cyan}#{it[:name]}#{reset}='#{it[:command]}'"
      out << "\n"
    end
    out << reset
  else
    # table (default)
    alias_columns = {
      "ALIAS" => lambda {|it| it[:name] },
      "COMMAND" => lambda {|it| it[:command] }
    }
    out << "\n"
    out << cyan
    out << as_pretty_table(my_aliases, alias_columns, {:border_style => :thin}.merge(options))
    out << format_results_pagination({'size' => my_aliases.size, 'total' => my_aliases.size.to_i})
    out << reset
    out << "\n"
  end
  print out
end

#remove(args) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/morpheus/cli/commands/alias_command.rb', line 140

def remove(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[alias1] [alias2]")
    build_common_options(opts, options, [])
    opts.footer = "This is how you remove alias definitions from your .morpheus_profile" + "\n"
                  "Pass one or more alias names to remove."
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  alias_names = args
  alias_names.each do |arg|
    if !Morpheus::Cli::CliRegistry.has_alias?(arg)
      print_red_alert "alias not found by name '#{arg}'"
      return false
    end
  end
  morpheus_profile = Morpheus::Cli::DotFile.new(Morpheus::Cli::DotFile.morpheus_profile_filename)
  morpheus_profile.remove_aliases(alias_names)

  # unregister them
  alias_names.each do |alias_name|
    Morpheus::Cli::CliRegistry.instance.remove_alias(alias_name)
  end

  # if args.count == 1
  #   puts "removed alias '#{alias_names[0]}'"
  # else
  #   puts "removed aliases '#{alias_names.join(', ')}'"
  # end

  Morpheus::Cli::Shell.instance.recalculate_auto_complete_commands() if Morpheus::Cli::Shell.instance

end