Module: Mortar::Command

Extended by:
Helpers
Defined in:
lib/mortar/command.rb,
lib/mortar/command/base.rb,
lib/mortar/command/plugins.rb

Defined Under Namespace

Classes: Auth, Base, Clusters, CommandFailed, Config, Describe, Generate, Help, Illustrate, Jobs, Local, Luigi, PigScripts, Plugins, Projects, S3, Spark, Validate, Version

Constant Summary collapse

BaseWithApp =
Base

Class Method Summary collapse

Methods included from Helpers

action, ask, confirm, copy_if_not_present_at_dest, default_host, deprecate, display, display_header, display_object, display_row, display_table, display_with_indent, download_to_file, ensure_dir_exists, error, error_with_failure, error_with_failure=, extended, extended_into, format_bytes, format_date, format_with_bang, full_host, get_terminal_environment, home_directory, host, hprint, hputs, included, included_into, installed_with_omnibus?, json_decode, json_encode, line_formatter, longest, output_with_bang, pending_github_team_state_message, quantify, redisplay, retry_on_exception, running_on_a_mac?, running_on_windows?, set_buffer, shell, spinner, status, string_distance, styled_array, styled_error, styled_hash, styled_header, suggestion, test_name, ticking, time_ago, truncate, warning, with_tty, write_to_file

Class Method Details

.command_aliasesObject



46
47
48
# File 'lib/mortar/command.rb', line 46

def self.command_aliases
  @@command_aliases ||= {}
end

.commandsObject



42
43
44
# File 'lib/mortar/command.rb', line 42

def self.commands
  @@commands ||= {}
end

.current_argsObject



74
75
76
# File 'lib/mortar/command.rb', line 74

def self.current_args
  @current_args
end

.current_commandObject



66
67
68
# File 'lib/mortar/command.rb', line 66

def self.current_command
  @current_command
end

.current_command=(new_current_command) ⇒ Object



70
71
72
# File 'lib/mortar/command.rb', line 70

def self.current_command=(new_current_command)
  @current_command = new_current_command
end

.current_optionsObject



78
79
80
# File 'lib/mortar/command.rb', line 78

def self.current_options
  @current_options ||= {}
end

.display_warningsObject



116
117
118
119
120
# File 'lib/mortar/command.rb', line 116

def self.display_warnings
  unless warnings.empty?
    $stderr.puts(warnings.map {|warning| " !    #{warning}"}.join("\n"))
  end
end

.extract_error(body, options = {}) ⇒ Object



254
255
256
257
# File 'lib/mortar/command.rb', line 254

def self.extract_error(body, options={})
  default_error = block_given? ? yield : "Internal server error."
  parse_error_xml(body) || parse_error_json(body) || parse_error_plain(body) || default_error
end

.filesObject



50
51
52
# File 'lib/mortar/command.rb', line 50

def self.files
  @@files ||= Hash.new {|hash,key| hash[key] = File.readlines(key).map {|line| line.strip}}
end

.global_option(name, *args, &blk) ⇒ Object



122
123
124
# File 'lib/mortar/command.rb', line 122

def self.global_option(name, *args, &blk)
  global_options << { :name => name, :args => args, :proc => blk }
end

.global_optionsObject



82
83
84
# File 'lib/mortar/command.rb', line 82

def self.global_options
  @global_options ||= []
end

.invalid_argumentsObject



86
87
88
# File 'lib/mortar/command.rb', line 86

def self.invalid_arguments
  @invalid_arguments
end

.loadObject



35
36
37
38
39
40
# File 'lib/mortar/command.rb', line 35

def self.load
  Dir[File.join(File.dirname(__FILE__), "command", "*.rb")].each do |file|
    require file
  end
  Mortar::Plugin.load!
end

.namespacesObject



54
55
56
# File 'lib/mortar/command.rb', line 54

def self.namespaces
  @@namespaces ||= {}
end

.parse(cmd) ⇒ Object



250
251
252
# File 'lib/mortar/command.rb', line 250

def self.parse(cmd)
  commands[cmd] || commands[command_aliases[cmd]]
end

.parse_error_json(body) ⇒ Object



266
267
268
269
270
271
272
273
274
275
276
# File 'lib/mortar/command.rb', line 266

def self.parse_error_json(body)
  json = json_decode(body.to_s) rescue false
  case json
  when Array
    json.first.last # message like [['base', 'message']]
  when Hash
    json['error']   # message like {'error' => 'message'}
  else
    nil
  end
end

.parse_error_plain(body) ⇒ Object



278
279
280
281
# File 'lib/mortar/command.rb', line 278

def self.parse_error_plain(body)
  return unless body.respond_to?(:headers) && body.headers[:content_type].to_s.include?("text/plain")
  body.to_s
end

.parse_error_xml(body) ⇒ Object



259
260
261
262
263
264
# File 'lib/mortar/command.rb', line 259

def self.parse_error_xml(body)
  xml_errors = REXML::Document.new(body).elements.to_a("//errors/error")
  msg = xml_errors.map { |a| a.text }.join(" / ")
  return msg unless msg.empty?
rescue Exception
end

.prepare_run(cmd, args = []) ⇒ Object



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/mortar/command.rb', line 132

def self.prepare_run(cmd, args=[])
  command = parse(cmd)

  if args.include?('-h') || args.include?('--help') || args.include?('help')
    args.unshift(cmd) unless cmd =~ /^-.*/
    cmd = 'help'
    command = parse('help')
  end

  unless command
    if %w( -v --version ).include?(cmd)
      cmd = 'version'
      command = parse(cmd)
    # Check if the command tried matches a command file. If it does, the command exists, but doesn't have an index action
    # Otherwise it would have been picked up by the original parse command.
    elsif Dir[File.join(File.dirname(__FILE__), "command", "*.rb")].find { |file| file.include?(cmd) }
      display "#{cmd} command requires arguments"
      display
      # Display the command's help message
      args.unshift(cmd) unless cmd =~ /^-.*/
      cmd = 'help'
      command = parse('help')
    else
      error([
        "`#{cmd}` is not a mortar command.",
        suggestion(cmd, commands.keys + command_aliases.keys),
        "See `mortar help` for a list of available commands."
      ].compact.join("\n"))
    end
  end

  @current_command = cmd

  opts = {}
  invalid_options = []

  parser = OptionParser.new do |parser|
    # overwrite OptionParsers Officious['version'] to avoid conflicts
    # see: https://github.com/ruby/ruby/blob/trunk/lib/optparse.rb#L814
    parser.on("--version") do |value|
      invalid_options << "--version"
    end
    global_options.each do |global_option|
      parser.on(*global_option[:args]) do |value|
        global_option[:proc].call(value) if global_option[:proc]
        opts[global_option[:name]] = value
      end
    end

    command[:options].each do |name, option|
      parser.on("-#{option[:short]}", "--#{option[:long]}", option[:desc]) do |value|
        opt_name_sym = name.gsub("-", "_").to_sym
        if opts[opt_name_sym]
          # convert multiple instances of an option to an array
          unless opts[opt_name_sym].is_a?(Array)
            opts[opt_name_sym] = [opts[opt_name_sym]]
          end
          opts[opt_name_sym] << value
        else
          opts[opt_name_sym] = value
        end
      end
    end
  end

  begin
    parser.order!(args) do |nonopt|
      invalid_options << nonopt
    end
  rescue OptionParser::InvalidOption => ex
    invalid_options << ex.args.first
    retry
  end

  args.concat(invalid_options)

  @current_args = args
  @current_options = opts
  @invalid_arguments = invalid_options

  [ command[:klass].new(args.dup, opts.dup), command[:method] ]
end

.register_command(command) ⇒ Object



58
59
60
# File 'lib/mortar/command.rb', line 58

def self.register_command(command)
  commands[command[:command]] = command
end

.register_namespace(namespace) ⇒ Object



62
63
64
# File 'lib/mortar/command.rb', line 62

def self.register_namespace(namespace)
  namespaces[namespace[:name]] = namespace
end

.run(cmd, arguments = []) ⇒ Object



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
# File 'lib/mortar/command.rb', line 215

def self.run(cmd, arguments=[])
  begin
    object, method = prepare_run(cmd, arguments.dup)
    object.send(method)
  rescue Interrupt, StandardError, SystemExit => error
    # load likely error classes, as they may not be loaded yet due to defered loads
    require 'mortar-api-ruby'
    raise(error)
  end
rescue Mortar::API::Errors::Unauthorized
  puts "Authentication failure"
  unless ENV['MORTAR_API_KEY']
    run "login"
    retry
  end
rescue Mortar::API::Errors::NotFound => e
  error extract_error(e.response.body) {
    e.response.body =~ /^([\w\s]+ not found).?$/ ? $1 : e.message # "Resource not found"
  }
rescue Mortar::Git::GitError => e
  error e.message
rescue Mortar::Project::ProjectError => e
  error e.message
rescue Mortar::API::Errors::Timeout
  error "API request timed out. Please try again, or contact [email protected] if this issue persists."
rescue Mortar::API::Errors::ErrorWithResponse => e
  error extract_error(e.response.body)
rescue CommandFailed => e
  error e.message
rescue OptionParser::ParseError
  commands[cmd] ? run("help", [cmd]) : run("help")
ensure
  display_warnings
end

.shift_argumentObject



90
91
92
93
# File 'lib/mortar/command.rb', line 90

def self.shift_argument
  # dup argument to get a non-frozen string
  @invalid_arguments.shift.dup rescue nil
end

.validate_arguments!Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/mortar/command.rb', line 95

def self.validate_arguments!
  unless invalid_arguments.empty?
    arguments = invalid_arguments.map {|arg| "\"#{arg}\""}
    if arguments.length == 1
      message = "Invalid argument: #{arguments.first}"
    elsif arguments.length > 1
      message = "Invalid arguments: "
      message << arguments[0...-1].join(", ")
      message << " and "
      message << arguments[-1]
    end
    $stderr.puts(format_with_bang(message))
    run(current_command, ["--help"])
    exit(1)
  end
end

.warningsObject



112
113
114
# File 'lib/mortar/command.rb', line 112

def self.warnings
  @warnings ||= []
end