Module: Heroku::Command

Extended by:
Helpers
Defined in:
lib/heroku/command.rb,
lib/heroku/command/base.rb,
lib/heroku/command/keys.rb,
lib/heroku/command/fork.rb,
lib/heroku/command/stack.rb,
lib/heroku/command/local.rb,
lib/heroku/command/drains.rb,
lib/heroku/command/addons.rb,
lib/heroku/command/domains.rb,
lib/heroku/command/plugins.rb,
lib/heroku/command/sharing.rb,
lib/heroku/command/pgbackups.rb,
lib/heroku/command/buildpack.rb,
lib/heroku/command/two_factor.rb

Defined Under Namespace

Classes: Addons, Apps, Auth, Base, Buildpack, Certs, CommandFailed, Config, Domains, Drains, Features, Fork, Git, Help, Keys, Labs, Local, Logs, Maintenance, Members, Orgs, Pg, Pgbackups, Plugins, Ps, Regions, Releases, Run, Sharing, Stack, Status, TwoFactor, Update, Version

Constant Summary collapse

BaseWithApp =
Base

Class Attribute Summary collapse

Class Method Summary collapse

Methods included from Helpers

action, app_owner, ask, confirm, confirm_command, create_git_remote, debug, debugging?, default_org_host, deprecate, display, display_header, display_object, display_row, display_table, error, error_log, error_log_path, 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?, has_git_remote?, has_http_git_entry_in_netrc, home_directory, hprint, hputs, included, included_into, json_decode, json_encode, launchy, line_formatter, longest, org?, org_host, output_with_bang, quantify, redisplay, retry_on_exception, run_command, running_on_a_mac?, running_on_windows?, set_buffer, shell, spinner, status, stderr_print, stderr_puts, string_distance, styled_array, styled_error, styled_hash, styled_header, suggestion, time_ago, truncate, update_git_remote, warn_if_using_jruby, with_tty

Class Attribute Details

.requires_preauthObject

Returns the value of attribute requires_preauth


14
15
16
# File 'lib/heroku/command.rb', line 14

def requires_preauth
  @requires_preauth
end

Class Method Details

.command_aliasesObject


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

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

.commandsObject


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

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

.current_argsObject


64
65
66
# File 'lib/heroku/command.rb', line 64

def self.current_args
  @current_args
end

.current_commandObject


56
57
58
# File 'lib/heroku/command.rb', line 56

def self.current_command
  @current_command
end

.current_command=(new_current_command) ⇒ Object


60
61
62
# File 'lib/heroku/command.rb', line 60

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

.current_optionsObject


68
69
70
# File 'lib/heroku/command.rb', line 68

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

.display_warningsObject


106
107
108
109
110
# File 'lib/heroku/command.rb', line 106

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

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


299
300
301
302
# File 'lib/heroku/command.rb', line 299

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

.filesObject


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

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

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


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

def self.global_option(name, *args, &blk)
  # args.sort.reverse gives -l, --long order
  global_options << { :name => name.to_s, :args => args.sort.reverse, :proc => blk }
end

.global_optionsObject


72
73
74
# File 'lib/heroku/command.rb', line 72

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

.handle_auth_error(e) ⇒ Object


281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/heroku/command.rb', line 281

def self.handle_auth_error(e)
  if ENV['HEROKU_API_KEY']
    puts "Authentication failure with HEROKU_API_KEY"
    exit 1
  elsif wrong_two_factor_code?(e)
    puts "Invalid two-factor code"
    false
  else
    puts "Authentication failure"
    run "login"
    true
  end
end

.invalid_argumentsObject


76
77
78
# File 'lib/heroku/command.rb', line 76

def self.invalid_arguments
  @invalid_arguments
end

.loadObject


17
18
19
20
21
22
23
24
# File 'lib/heroku/command.rb', line 17

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

.namespacesObject


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

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

.parse(cmd) ⇒ Object


295
296
297
# File 'lib/heroku/command.rb', line 295

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

.parse_error_json(body) ⇒ Object


311
312
313
314
315
316
317
318
319
320
321
# File 'lib/heroku/command.rb', line 311

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

.parse_error_plain(body) ⇒ Object


323
324
325
326
# File 'lib/heroku/command.rb', line 323

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


304
305
306
307
308
309
# File 'lib/heroku/command.rb', line 304

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
end

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


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

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 cmd == '--version'
    cmd = 'version'
    command = parse(cmd)
  end

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

  opts = {}
  invalid_options = []

  parser = OptionParser.new do |parser|
    # remove OptionParsers Officious['version'] to avoid conflicts
    # see: https://github.com/ruby/ruby/blob/trunk/lib/optparse.rb#L814
    parser.base.long.delete('version')
    (global_options + (command && command[:options] || [])).each do |option|
      parser.on(*option[:args]) do |value|
        if option[:proc]
          option[:proc].call(value)
        end
        opts[option[:name].gsub('-', '_').to_sym] = value
        ARGV.join(' ') =~ /(#{option[:args].map {|arg| arg.split(' ', 2).first}.join('|')})/
        @anonymized_args << "#{$1} _"
        @normalized_args << "#{option[:args].last.split(' ', 2).first} _"
      end
    end
  end

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

  args.concat(invalid_options)

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

  @anonymous_command = [ARGV.first, *@anonymized_args].join(' ')
  begin
    usage_directory = "#{home_directory}/.heroku/usage"
    FileUtils.mkdir_p(usage_directory)
    usage_file = usage_directory << "/#{Heroku::VERSION}"
    usage = if File.exists?(usage_file)
      json_decode(File.read(usage_file))
    else
      {}
    end
    usage[@anonymous_command] ||= 0
    usage[@anonymous_command] += 1
    File.write(usage_file, json_encode(usage) + "\n")
  rescue
    # 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 = command_instance.app rescue nil)
      @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 heroku command.",
      suggestion(cmd, commands.keys + command_aliases.keys),
      "See `heroku help` for a list of available commands."
    ].compact.join("\n"))
  end
end

.register_command(command) ⇒ Object


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

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

.register_namespace(namespace) ⇒ Object


52
53
54
# File 'lib/heroku/command.rb', line 52

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

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


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
279
# File 'lib/heroku/command.rb', line 221

def self.run(cmd, arguments=[])
  object, method = prepare_run(cmd, arguments.dup)
  object.send(method)
rescue Heroku::API::Errors::Unauthorized, RestClient::Unauthorized => e
   = handle_auth_error(e)
  retry if 
rescue Heroku::API::Errors::VerificationRequired, RestClient::PaymentRequired => e
  retry if Heroku::Helpers.confirm_billing
rescue Heroku::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 Heroku::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 Heroku::API::Errors::Timeout, RestClient::RequestTimeout
  error "API request timed out. Please try again, or contact [email protected] if this issue persists."
rescue Heroku::API::Errors::Forbidden => e
  if e.response.headers.has_key?("Heroku-Two-Factor-Required")
    if requires_preauth
      Heroku::Auth.preauth
    else
      Heroku::Auth.ask_for_second_factor
    end
    retry
  else
    error extract_error(e.response.body)
  end
rescue Heroku::API::Errors::ErrorWithResponse => e
  error extract_error(e.response.body)
rescue RestClient::RequestFailed => e
  if e.response.code == 403 && e.response.headers.has_key?(:heroku_two_factor_required)
    Heroku::Auth.preauth
    retry
  else
    error extract_error(e.http_body)
  end
rescue CommandFailed => e
  error e.message, false
rescue OptionParser::ParseError
  commands[cmd] ? run("help", [cmd]) : run("help")
rescue Excon::Errors::SocketError, SocketError => e
  error("Unable to connect to Heroku API, please check internet connectivity and try again.")
ensure
  display_warnings
end

.shift_argumentObject


80
81
82
83
# File 'lib/heroku/command.rb', line 80

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

.unregister_commands_made_private_after_the_factObject


46
47
48
49
50
# File 'lib/heroku/command.rb', line 46

def self.unregister_commands_made_private_after_the_fact
  commands.values \
    .select { |c| c[:klass].private_method_defined? c[:method] } \
    .each   { |c| commands.delete c[:command] }
end

.validate_arguments!Object


85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/heroku/command.rb', line 85

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


102
103
104
# File 'lib/heroku/command.rb', line 102

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

.wrong_two_factor_code?(e) ⇒ Boolean

Returns:

  • (Boolean)

328
329
330
331
332
333
334
# File 'lib/heroku/command.rb', line 328

def self.wrong_two_factor_code?(e)
  error = json_decode(e.response.body)

  # the server could have responded with XML, in which case `error` will be
  # `nil`
  error && error["id"] == "invalid_two_factor_code"
end