Module: Nimbu::Command

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

Defined Under Namespace

Classes: Auth, Base, Browse, CommandFailed, Help, Init, Server, Sites, Themes, Version

Constant Summary collapse

BaseWithApp =
Base

Class Method Summary collapse

Methods included from Helpers

action, ask, confirm, confirm_billing, confirm_command, create_git_remote, deprecate, disable_error_capture, display, display_header, display_object, display_row, display_table, enable_error_capture, error, error_with_failure, error_with_failure=, extended, extended_into, fail, format_bytes, format_date, format_error, format_with_bang, get_terminal_environment, git, has_git?, home_directory, hprint, hputs, included, included_into, json_decode, json_encode, launchy, line_formatter, longest, output, output_with_arrow, output_with_bang, quantify, redisplay, retry_on_exception, run_command, running_on_a_mac?, running_on_windows?, set_buffer, shell, spinner, status, string_distance, styled_array, styled_error, styled_hash, styled_header, suggestion, time_ago, truncate, with_tty

Methods included from Helpers::System

#browser_launcher, #command?, #osx?, #tmp_dir, #which, #windows?

Class Method Details

.command_aliasesObject



26
27
28
# File 'lib/nimbu/command.rb', line 26

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

.commandsObject



22
23
24
# File 'lib/nimbu/command.rb', line 22

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

.current_argsObject



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

def self.current_args
  @current_args
end

.current_commandObject



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

def self.current_command
  @current_command
end

.current_command=(new_current_command) ⇒ Object



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

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

.current_optionsObject



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

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

.display_warningsObject



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

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

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



237
238
239
240
# File 'lib/nimbu/command.rb', line 237

def self.extract_error(body, _options = {})
  default_error = block_given? ? yield : "Internal server error.\nRun 'nimbu status' to check for known platform issues."
  parse_error_xml(body) || parse_error_json(body) || parse_error_plain(body) || default_error
end

.filesObject



30
31
32
# File 'lib/nimbu/command.rb', line 30

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

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



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

def self.global_option(name, *args, &blk)
  global_options << { name: name.to_s, args: args.sort.reverse, proc: blk }
end

.global_optionsObject



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

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

.loadObject



16
17
18
19
20
# File 'lib/nimbu/command.rb', line 16

def self.load
  Dir[File.join(File.dirname(__FILE__), 'command', '*.rb')].sort.each do |file|
    require file
  end
end

.namespacesObject



34
35
36
# File 'lib/nimbu/command.rb', line 34

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

.parse(cmd) ⇒ Object



233
234
235
# File 'lib/nimbu/command.rb', line 233

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

.parse_error_json(body) ⇒ Object



249
250
251
252
253
254
255
256
# File 'lib/nimbu/command.rb', line 249

def self.parse_error_json(body)
  json = begin
    json_decode(body.to_s)
  rescue StandardError
    false
  end
  json ? json['error'] : nil
end

.parse_error_plain(body) ⇒ Object



258
259
260
261
262
# File 'lib/nimbu/command.rb', line 258

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



242
243
244
245
246
247
# File 'lib/nimbu/command.rb', line 242

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



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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/nimbu/command.rb', line 81

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

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

  if ['--version', '-v'].include?(cmd)
    cmd = 'version'
    command = parse(cmd)
  end

  @current_command = cmd
  @anonymized_args = []
  @normalized_args = []

  opts = {}
  invalid_options = []

  parser = OptionParser.new do |parser|
    parser.base.long.delete('version')
    (global_options + (command && command[:options] || [])).each do |option|
      parser.on(*option[:args]) do |value|
        option[:proc].call(value) if option[:proc]
        opts[option[:name].gsub('-', '_').to_sym] = value
        ARGV.join(' ') =~ /(#{option[:args].map { |arg| arg.split(' ', 2).first }.join('|')})/
        @anonymized_args << "#{Regexp.last_match(1)} _"
        @normalized_args << "#{option[:args].last.split(' ', 2).first} _"
      end
    end
  end

  parser.version = Nimbu::VERSION

  begin
    parser.order!(args) do |nonopt|
      invalid_options << nonopt
      @anonymized_args << '!'
      @normalized_args << '!'
    end
  rescue OptionParser::InvalidOption => e
    invalid_options << e.args.first
    @anonymized_args << '!'
    @normalized_args << '!'
    retry
  end

  args.concat(invalid_options)

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

  Nimbu.debug = true if opts[:debug]

  @anonymous_command = [ARGV.first, *@anonymized_args].join(' ')
  begin
    usage_directory = "#{home_directory}/.nimbu/usage"
    FileUtils.mkdir_p(usage_directory)
    usage_file = usage_directory << "/#{Nimbu::VERSION}"
    usage = if File.exist?(usage_file)
              json_decode(File.read(usage_file).force_encoding('UTF-8'))
            else
              {}
            end
    usage[@anonymous_command] ||= 0
    usage[@anonymous_command] += 1
    File.write(usage_file, json_encode(usage) + "\n")
  rescue StandardError
    # usage writing is not important, allow failures
  end

  if command
    command_instance = command[:klass].new(args.dup, opts.dup)

    if !@normalized_args.include?('--app _') && (implied_app = begin
      command_instance.app
    rescue StandardError
      nil
    end)
      @normalized_args << '--app _'
    end
    @normalized_command = [ARGV.first, @normalized_args.sort_by { |arg| arg.gsub('-', '') }].join(' ')

    [command_instance, command[:method]]
  else
    error([
      "`#{cmd}` is not a Nimbu command.",
      suggestion(cmd, commands.keys + command_aliases.keys),
      'See `Nimbu help` for a list of available commands.'
    ].compact.join("\n"))
  end
end

.register_command(command) ⇒ Object



38
39
40
# File 'lib/nimbu/command.rb', line 38

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

.register_namespace(namespace) ⇒ Object



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

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

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



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

def self.run(cmd, arguments = [])
  begin
    object, method = prepare_run(cmd, arguments.dup)
    object.send(method)
  rescue Interrupt, StandardError, SystemExit => e
    # load likely error classes, as they may not be loaded yet due to defered loads
    raise(e)
  end
# rescue Nimbu::API::Errors::Unauthorized, RestClient::Unauthorized
#   puts "Authentication failure"
#   unless ENV['Nimbu_API_KEY']
#     run "login"
#     retry
#   end
# rescue Nimbu::API::Errors::VerificationRequired, RestClient::PaymentRequired => e
#   retry if Nimbu::Helpers.confirm_billing
# rescue Nimbu::API::Errors::NotFound => e
#   error extract_error(e.response.body) {
#     e.response.body =~ /^([\w\s]+ not found).?$/ ? $1 : "Resource not found"
#   }
# rescue RestClient::ResourceNotFound => e
#   error extract_error(e.http_body) {
#     e.http_body =~ /^([\w\s]+ not found).?$/ ? $1 : "Resource not found"
#   }
# rescue Nimbu::API::Errors::Locked => e
#   app = e.response.headers[:x_confirmation_required]
#   if confirm_command(app, extract_error(e.response.body))
#     arguments << '--confirm' << app
#     retry
#   end
# rescue RestClient::Locked => e
#   app = e.response.headers[:x_confirmation_required]
#   if confirm_command(app, extract_error(e.http_body))
#     arguments << '--confirm' << app
#     retry
#   end
# rescue Nimbu::API::Errors::Timeout, RestClient::RequestTimeout
#   error "API request timed out. Please try again, or contact [email protected] if this issue persists."
# rescue Nimbu::API::Errors::ErrorWithResponse => e
#   error extract_error(e.response.body)
# rescue RestClient::RequestFailed => e
#   error extract_error(e.http_body)
rescue CommandFailed => e
  error e.message
rescue OptionParser::ParseError
  commands[cmd] ? run('help', [cmd]) : run('help')
rescue Excon::Errors::SocketError => e
  if e.message == 'getaddrinfo: nodename nor servname provided, or not known (SocketError)'
    error('Unable to connect to Nimbu API, please check internet connectivity and try again.')
  else
    raise(e)
  end
ensure
  display_warnings
end

.warningsObject



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

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