Class: Morpheus::Cli::CliRegistry

Inherits:
Object
  • Object
show all
Extended by:
Term::ANSIColor
Defined in:
lib/morpheus/cli/cli_registry.rb

Defined Under Namespace

Classes: BadAlias, BadCommandDefinition

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCliRegistry

Returns a new instance of CliRegistry.



18
19
20
21
# File 'lib/morpheus/cli/cli_registry.rb', line 18

def initialize
  @commands = {} # this is command => Class that includes ::CliCommand
  @aliases = {} # this is alias => String full input string
end

Class Method Details

.add(klass, command_name = nil) ⇒ Object



181
182
183
184
185
186
187
188
# File 'lib/morpheus/cli/cli_registry.rb', line 181

def add(klass, command_name=nil)
  klass_command_name = cli_ize(klass.name.split('::')[-1])
  if has_command?(klass_command_name)
    instance.remove(klass_command_name)
  end
  command_name ||= klass_command_name
  instance.add(command_name, klass)
end

.allObject



206
207
208
# File 'lib/morpheus/cli/cli_registry.rb', line 206

def all
  instance.all
end

.all_aliasesObject



210
211
212
# File 'lib/morpheus/cli/cli_registry.rb', line 210

def all_aliases
  instance.all_aliases
end

.cli_ize(klass_name) ⇒ Object



214
215
216
217
218
219
220
221
222
223
224
# File 'lib/morpheus/cli/cli_registry.rb', line 214

def cli_ize(klass_name)
  # borrowed from ActiveSupport
  return klass_name unless klass_name =~ /[A-Z-]|::/
  word = klass_name.to_s.gsub(/::/, '/')
  word.gsub!(/(?:(?<=([A-Za-z\d]))|\b)(?=\b|[^a-z])/) { "#{$1 && '_'}" }
  word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
  word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
  word.tr!("-", "_")
  word.downcase!
  word.chop.tr('_', '-')
end

.exec(command_name, args) ⇒ Object

todo: move execution out of the CliRegistry



74
75
76
# File 'lib/morpheus/cli/cli_registry.rb', line 74

def exec(command_name, args)
  exec_command(command_name, args)
end

.exec_alias(alias_name, args) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/morpheus/cli/cli_registry.rb', line 91

def exec_alias(alias_name, args)
  found_alias_command = instance.get_alias(alias_name)
  if !found_alias_command
    raise Morpheus::Cli::CommandError.new("'#{alias_name}' is not a defined alias.")
  end
  # if !is_valid_expression(found_alias_command)
  #   raise Morpheus::Cli::CommandError.new("alias '#{alias_name}' is not a valid expression: #{found_alias_command}")
  # end
  input = found_alias_command
  if args && !args.empty?
    input = "#{found_alias_command} " + args.collect {|arg| arg.include?(" ") ? "\"#{arg}\"" : "#{arg}" }.join(" ")
  end
  exec_expression(input)
end

.exec_command(command_name, args) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/morpheus/cli/cli_registry.rb', line 78

def exec_command(command_name, args)
  #puts "exec_command(#{command_name}, #{args})"
  found_alias_command = instance.get_alias(command_name)
  if has_alias?(command_name)
    exec_alias(command_name, args)
  elsif has_command?(command_name)
    instance.get(command_name).new.handle(args)
  else
    # todo: need to just return error instead of raise
    raise CommandNotFoundError.new("'#{command_name}' is not a morpheus command.")
  end
end

.exec_expression(input) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/morpheus/cli/cli_registry.rb', line 106

def exec_expression(input)
  # puts "exec_expression(#{input})"
  flow = input
  if input.is_a?(String)
    begin
      flow = Morpheus::Cli::ExpressionParser.parse(input)
    rescue Morpheus::Cli::ExpressionParser::InvalidExpression => e
      raise e
    end
  end
  # puts "executing flow: #{flow.inspect}"
  final_command_result = nil
  if flow.size == 0
    # no input eh?
  else
    last_command_result = nil
    if ['&&','||', '|'].include?(flow.first)
      raise Morpheus::Cli::ExpressionParser::InvalidExpression.new "#{Morpheus::Terminal.angry_prompt}invalid command format, begins with an operator: #{input}"
    elsif ['&&','||', '|'].include?(flow.last)
      raise Morpheus::Cli::ExpressionParser::InvalidExpression.new "#{Morpheus::Terminal.angry_prompt}invalid command format, ends with an operator: #{input}"
    # elsif ['&&','||', '|'].include?(flow.last)
    #   raise Morpheus::Cli::ExpressionParser::InvalidExpression.new "invalid command format, consecutive operators: #{cmd}"
    else
      #Morpheus::Logging::DarkPrinter.puts "Executing command flow: #{flow.inspect}" if Morpheus::Logging.debug?
      previous_command = nil
      previous_command_result = nil
      current_operator = nil
      still_executing = true
      # need to error before executing anything, could be dangerous otherwise!
      # also maybe only pass flow commands if they have a space on either side..
      if flow.include?("|")
        raise Morpheus::Cli::ExpressionParser::InvalidExpression.new "The PIPE (|) operator is not yet supported. You can wrap your arguments in quotations."
      end
      flow.each do |flow_cmd|
        if still_executing
          if flow_cmd == '&&'
            # AND operator
            current_operator = flow_cmd
            exit_code, cmd_err = parse_command_result(previous_command_result)
            if exit_code != 0
              still_executing = false
            end
          elsif flow_cmd == '||' # or with previous command
            current_operator = flow_cmd
            exit_code, err = parse_command_result(previous_command_result)
            if exit_code == 0
              still_executing = false
            end
          elsif flow_cmd == '|' # or with previous command
            # todo, handle pipe!
            raise Morpheus::Cli::ExpressionParser::InvalidExpression.new "The PIPE (|) operator is not yet supported. You can wrap your arguments in quotations."
            previous_command_result = nil
            still_executing = false
            # or just continue?
          elsif flow_cmd.is_a?(Array)
            # this is a subexpression, execute it as such
            current_operator = nil
            previous_command_result = exec_expression(flow_cmd)
          else # it's a command, not an operator
            current_operator = nil
            flow_argv = Shellwords.shellsplit(flow_cmd)
            previous_command_result = exec_command(flow_argv[0], flow_argv[1..-1])
          end
          previous_command = flow_cmd
        else
          #Morpheus::Logging::DarkPrinter.puts "operator skipped command: #{flow_cmd}" if Morpheus::Logging.debug?
        end
        # previous_command = flow_cmd
      end
      final_command_result = previous_command_result
    end
  end
  return final_command_result
end

.has_alias?(alias_name) ⇒ Boolean

Returns:

  • (Boolean)


198
199
200
201
202
203
204
# File 'lib/morpheus/cli/cli_registry.rb', line 198

def has_alias?(alias_name)
  if alias_name.nil? || alias_name == ''
    false
  else
    !instance.get_alias(alias_name).nil?
  end
end

.has_command?(command_name) ⇒ Boolean

Returns:

  • (Boolean)


190
191
192
193
194
195
196
# File 'lib/morpheus/cli/cli_registry.rb', line 190

def has_command?(command_name)
  if command_name.nil? || command_name == ''
    false
  else
    !instance.get(command_name).nil?
  end
end

.instanceObject



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

def instance
  @instance ||= CliRegistry.new
end

.parse_alias_definition(input) ⇒ Object



226
227
228
229
230
231
232
233
234
# File 'lib/morpheus/cli/cli_registry.rb', line 226

def parse_alias_definition(input)
  # todo: one multi group regex would work
  alias_name, command_string = nil, nil
  chunks = input.to_s.sub(/^alias\s+/, "").split('=')
  alias_name = chunks.shift
  command_string = chunks.compact.reject {|it| it.empty? }.join('=')
  command_string = command_string.strip.sub(/^'/, "").sub(/'\Z/, "").strip
  return alias_name, command_string
end

.parse_command_result(cmd_result) ⇒ Array

parse any object into a command result [exit_code, error] 0 means success. This treats nil, true, or an object success. 0 or

Returns:

  • (Array)

    exit_code, error. Success returns [0, nil].



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

def parse_command_result(cmd_result)
  exit_code, err = nil, nil
  if cmd_result.is_a?(Array)
    exit_code = cmd_result[0] || 0
    err = cmd_result[1]
  elsif cmd_result.is_a?(Hash)
    exit_code = cmd_result[:exit_code] || 0
    err = cmd_result[:error] || cmd_result[:err]
  elsif cmd_result == nil || cmd_result == true
    exit_code = 0
  elsif cmd_result == false
    exit_code = 1
  elsif cmd_result.is_a?(Integer)
    exit_code = cmd_result
  elsif cmd_result.is_a?(Float)
    exit_code = cmd_result.to_i
  elsif cmd_result.is_a?(String)
    exit_code = cmd_result.to_i
  else
    if cmd_result.respond_to?(:to_i)
      exit_code = cmd_result.to_i
    else
      # happens for aliases right now.. and execution flow probably, need to handle Array
      # uncomment to track them down, proceed with exit 0 for now
      #Morpheus::Logging::DarkPrinter.puts "debug: command #{command_name} produced an unexpected result: (#{cmd_result.class}) #{cmd_result}" if Morpheus::Logging.debug?
      exit_code = 0
    end
  end
  return exit_code, err
end

Instance Method Details

#add(cmd_name, klass) ⇒ Object



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

def add(cmd_name, klass)
  @commands[cmd_name.to_sym] = klass
end

#add_alias(alias_name, command_string) ⇒ Object



52
53
54
55
56
57
58
59
60
# File 'lib/morpheus/cli/cli_registry.rb', line 52

def add_alias(alias_name, command_string)
  #return @commands[alias_name.to_sym]
  if self.class.has_command?(alias_name)
    raise BadAlias.new "alias name '#{alias_name}' is invalid. That is the name of a morpheus command."
  elsif alias_name.to_s.downcase.strip == command_string.to_s.downcase.strip
    raise BadAlias.new "alias #{alias_name}=#{command_string} is invalid..."
  end
  @aliases[alias_name.to_sym] = command_string
end

#allObject



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

def all
  @commands.reject {|cmd, klass| klass.hidden_command }
end

#all_aliasesObject



44
45
46
# File 'lib/morpheus/cli/cli_registry.rb', line 44

def all_aliases
  @aliases
end

#flushObject



23
24
25
26
# File 'lib/morpheus/cli/cli_registry.rb', line 23

def flush
  @commands = {}
  @aliases = {}
end

#get(cmd_name) ⇒ Object



32
33
34
# File 'lib/morpheus/cli/cli_registry.rb', line 32

def get(cmd_name)
  @commands[cmd_name.to_sym]
end

#get_alias(alias_name) ⇒ Object



48
49
50
# File 'lib/morpheus/cli/cli_registry.rb', line 48

def get_alias(alias_name)
  @aliases[alias_name.to_sym]
end

#remove(cmd_name) ⇒ Object



40
41
42
# File 'lib/morpheus/cli/cli_registry.rb', line 40

def remove(cmd_name)
  @commands.delete(cmd_name.to_sym)
end

#remove_alias(alias_name) ⇒ Object



62
63
64
# File 'lib/morpheus/cli/cli_registry.rb', line 62

def remove_alias(alias_name)
  @aliases.delete(alias_name.to_sym)
end