Module: Heroku::Command

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

Defined Under Namespace

Classes: Account, Accounts, Addons, Apps, Auth, Base, Certs, CommandFailed, Config, Db, Domains, Drains, Fork, Git, Help, Keys, Labs, Logs, Maintenance, Pg, Pgbackups, Plugins, Ps, Regions, Releases, Run, Sharing, Ssl, Stack, Status, Update, 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, display, display_header, display_object, display_row, display_table, 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, host_name, hprint, hputs, included, included_into, json_decode, json_encode, launchy, line_formatter, longest, 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

Class Method Details

.command_aliasesObject



23
24
25
# File 'lib/heroku/command.rb', line 23

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

.commandsObject



19
20
21
# File 'lib/heroku/command.rb', line 19

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

.current_argsObject



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

def self.current_args
  @current_args
end

.current_commandObject



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

def self.current_command
  @current_command
end

.current_command=(new_current_command) ⇒ Object



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

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

.current_optionsObject



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

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

.display_warningsObject



93
94
95
96
97
# File 'lib/heroku/command.rb', line 93

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

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



265
266
267
268
# File 'lib/heroku/command.rb', line 265

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

.filesObject



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

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

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



99
100
101
102
# File 'lib/heroku/command.rb', line 99

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



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

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

.invalid_argumentsObject



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

def self.invalid_arguments
  @invalid_arguments
end

.loadObject



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

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

.namespacesObject



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

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

.parse(cmd) ⇒ Object



261
262
263
# File 'lib/heroku/command.rb', line 261

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

.parse_error_json(body) ⇒ Object



277
278
279
280
281
282
283
284
285
286
287
# File 'lib/heroku/command.rb', line 277

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']   # message like {'error' => 'message'}
  else
    nil
  end
end

.parse_error_plain(body) ⇒ Object



289
290
291
292
# File 'lib/heroku/command.rb', line 289

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



270
271
272
273
274
275
# File 'lib/heroku/command.rb', line 270

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



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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/heroku/command.rb', line 112

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 pogoapp command.",
      suggestion(cmd, commands.keys + command_aliases.keys),
      "See `pogo help` for a list of available commands."
    ].compact.join("\n"))
  end
end

.register_command(command) ⇒ Object



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

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

.register_namespace(namespace) ⇒ Object



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

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

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



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

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 'heroku-api'
    require 'rest_client'
    raise(error)
  end
rescue Heroku::API::Errors::Unauthorized, RestClient::Unauthorized
  puts "Authentication failure"
  unless ENV['HEROKU_API_KEY']
    run "login"
    retry
  end
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::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 Heroku API, please check internet connectivity and try again.")
  else
    raise(e)
  end
ensure
  display_warnings
end

.shift_argumentObject



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

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

.validate_arguments!Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/heroku/command.rb', line 72

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



89
90
91
# File 'lib/heroku/command.rb', line 89

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