Module: Heroku::Helpers

Defined Under Namespace

Modules: HerokuPostgresql, PgDiagnose Classes: LogDisplayer

Constant Summary

@@kb =
1024
@@mb =
1024 * @@kb
@@gb =
1024 * @@mb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.error_with_failureObject



288
289
290
# File 'lib/heroku/helpers.rb', line 288

def self.error_with_failure
  @@error_with_failure ||= false
end

.error_with_failure=(new_error_with_failure) ⇒ Object



292
293
294
# File 'lib/heroku/helpers.rb', line 292

def self.error_with_failure=(new_error_with_failure)
  @@error_with_failure = new_error_with_failure
end

.extended(base) ⇒ Object



308
309
310
# File 'lib/heroku/helpers.rb', line 308

def self.extended(base)
  extended_into << base
end

.extended_intoObject



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

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

.included(base) ⇒ Object



304
305
306
# File 'lib/heroku/helpers.rb', line 304

def self.included(base)
  included_into << base
end

.included_intoObject



296
297
298
# File 'lib/heroku/helpers.rb', line 296

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

Instance Method Details

#action(message, options = {}) ⇒ Object

DISPLAY HELPERS



248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/heroku/helpers.rb', line 248

def action(message, options={})
  message = "#{message} in organization #{org}" if options[:org]
  display("#{message}... ", false)
  Heroku::Helpers.error_with_failure = true
  ret = yield
  Heroku::Helpers.error_with_failure = false
  display((options[:success] || "done"), false)
  if @status
    display(", #{@status}", false)
    @status = nil
  end
  display
  ret
end

#app_owner(email) ⇒ Object



555
556
557
# File 'lib/heroku/helpers.rb', line 555

def app_owner email
  org?(email) ? email.gsub(/^(.*)@#{org_host}$/,'\1') : email
end

#askObject



83
84
85
# File 'lib/heroku/helpers.rb', line 83

def ask
  $stdin.gets.to_s.strip
end

#confirm(message = "Are you sure you wish to continue? (y/n)") ⇒ Object



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

def confirm(message="Are you sure you wish to continue? (y/n)")
  display("#{message} ", false)
  ['y', 'yes'].include?(ask.downcase)
end

#confirm_command(app_to_confirm = app, message = nil) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/heroku/helpers.rb', line 57

def confirm_command(app_to_confirm = app, message=nil)
  if confirmed_app = Heroku::Command.current_options[:confirm]
    unless confirmed_app == app_to_confirm
      raise(Heroku::Command::CommandFailed, "Confirmed app #{confirmed_app} did not match the selected app #{app_to_confirm}.")
    end
    return true
  else
    display
    message ||= "WARNING: Destructive Action\nThis command will affect the app: #{app_to_confirm}"
    message << "\nTo proceed, type \"#{app_to_confirm}\" or re-run this command with --confirm #{app_to_confirm}"
    output_with_bang(message)
    display
    display "> ", false
    if ask.downcase != app_to_confirm
      error("Confirmation did not match #{app_to_confirm}. Aborted.")
    else
      true
    end
  end
end

#create_git_remote(remote, url) ⇒ Object



165
166
167
168
169
# File 'lib/heroku/helpers.rb', line 165

def create_git_remote(remote, url)
  return if has_git_remote? remote
  git "remote add #{remote} #{url}"
  display "Git remote #{remote} added" if $?.success?
end

#debug(*args) ⇒ Object



36
37
38
# File 'lib/heroku/helpers.rb', line 36

def debug(*args)
  $stderr.puts(*args) if debugging?
end

#debugging?Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/heroku/helpers.rb', line 48

def debugging?
  ENV['HEROKU_DEBUG']
end

#default_org_hostObject



547
548
549
# File 'lib/heroku/helpers.rb', line 547

def default_org_host
  "herokumanager.com"
end

#deprecate(message) ⇒ Object



32
33
34
# File 'lib/heroku/helpers.rb', line 32

def deprecate(message)
  display "WARNING: #{message}"
end

#display(msg = "", new_line = true) ⇒ Object



19
20
21
22
23
24
25
26
# File 'lib/heroku/helpers.rb', line 19

def display(msg="", new_line=true)
  if new_line
    puts(msg)
  else
    print(msg)
  end
  $stdout.flush
end

#display_header(message = "", new_line = true) ⇒ Object



312
313
314
315
# File 'lib/heroku/helpers.rb', line 312

def display_header(message="", new_line=true)
  return if message.to_s.strip == ""
  display("=== " + message.to_s.split("\n").join("\n=== "), new_line)
end

#display_object(object) ⇒ Object



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/heroku/helpers.rb', line 317

def display_object(object)
  case object
  when Array
    # list of objects
    object.each do |item|
      display_object(item)
    end
  when Hash
    # if all values are arrays, it is a list with headers
    # otherwise it is a single header with pairs of data
    if object.values.all? {|value| value.is_a?(Array)}
      object.keys.sort_by {|key| key.to_s}.each do |key|
        display_header(key)
        display_object(object[key])
        hputs
      end
    end
  else
    hputs(object.to_s)
  end
end

#display_row(row, lengths) ⇒ Object



196
197
198
199
200
201
202
203
# File 'lib/heroku/helpers.rb', line 196

def display_row(row, lengths)
  row_data = []
  row.zip(lengths).each do |column, length|
    format = column.is_a?(Fixnum) ? "%#{length}s" : "%-#{length}s"
    row_data << format % column
  end
  display(row_data.join("  "))
end

#display_table(objects, columns, headers) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/heroku/helpers.rb', line 181

def display_table(objects, columns, headers)
  lengths = []
  columns.each_with_index do |column, index|
    header = headers[index]
    lengths << longest([header].concat(objects.map { |o| o[column].to_s }))
  end
  lines = lengths.map {|length| "-" * length}
  lengths[-1] = 0 # remove padding from last column
  display_row headers, lengths
  display_row lines, lengths
  objects.each do |row|
    display_row columns.map { |column| row[column] }, lengths
  end
end

#error(message, report = false) ⇒ Object



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

def error(message, report=false)
  if Heroku::Helpers.error_with_failure
    display("failed")
    Heroku::Helpers.error_with_failure = false
  end
  $stderr.puts(format_with_bang(message))
  rollbar_id = Rollbar.error(message) if report
  $stderr.puts("Error ID: #{rollbar_id}") if rollbar_id
  exit(1)
end

#error_log(*obj) ⇒ Object



446
447
448
449
450
451
# File 'lib/heroku/helpers.rb', line 446

def error_log(*obj)
  FileUtils.mkdir_p(File.dirname(error_log_path))
  File.open(error_log_path, 'a') do |file|
    file.write(obj.join("\n") + "\n")
  end
end

#error_log_pathObject



453
454
455
# File 'lib/heroku/helpers.rb', line 453

def error_log_path
  File.join(home_directory, '.heroku', 'error.log')
end

#fail(message) ⇒ Object



242
243
244
# File 'lib/heroku/helpers.rb', line 242

def fail(message)
  raise Heroku::Command::CommandFailed, message
end

#format_bytes(amount) ⇒ Object



148
149
150
151
152
153
154
155
# File 'lib/heroku/helpers.rb', line 148

def format_bytes(amount)
  amount = amount.to_i
  return '(empty)' if amount == 0
  return amount if amount < @@kb
  return "#{(amount / @@kb).round}k" if amount < @@mb
  return "#{(amount / @@mb).round}M" if amount < @@gb
  return "#{(amount / @@gb).round}G"
end

#format_date(date) ⇒ Object



78
79
80
81
# File 'lib/heroku/helpers.rb', line 78

def format_date(date)
  date = Time.parse(date).utc if date.is_a?(String)
  date.strftime("%Y-%m-%d %H:%M %Z").gsub('GMT', 'UTC')
end

#format_error(error, message = 'Heroku client internal error.', rollbar_id = nil) ⇒ Object



392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
# File 'lib/heroku/helpers.rb', line 392

def format_error(error, message='Heroku client internal error.', rollbar_id=nil)
  formatted_error = []
  formatted_error << " !    #{message}"
  formatted_error << ' !    Search for help at: https://help.heroku.com'
  formatted_error << ' !    Or report a bug at: https://github.com/heroku/heroku/issues/new'
  formatted_error << ''
  formatted_error << "    Error:       #{error.message} (#{error.class})"
  command = ARGV.map do |arg|
    if arg.include?(' ')
      arg = %{"#{arg}"}
    else
      arg
    end
  end.join(' ')
  formatted_error << "    Command:     heroku #{command}"
  require 'heroku/auth'
  unless Heroku::Auth.host == Heroku::Auth.default_host
    formatted_error << "    Host:        #{Heroku::Auth.host}"
  end
  if http_proxy = ENV['http_proxy'] || ENV['HTTP_PROXY']
    formatted_error << "    HTTP Proxy:  #{http_proxy}"
  end
  if https_proxy = ENV['https_proxy'] || ENV['HTTPS_PROXY']
    formatted_error << "    HTTPS Proxy: #{https_proxy}"
  end
  plugins = Heroku::Plugin.list.sort
  unless plugins.empty?
    formatted_error << "    Plugins:     #{plugins.first}"
    plugins[1..-1].each do |plugin|
      formatted_error << "                 #{plugin}"
    end
    if plugins.length > 1
      formatted_error << ''
      $stderr.puts
    end
  end
  formatted_error << "    Version:     #{Heroku.user_agent}"
  formatted_error << "    Error ID:    #{rollbar_id}" if rollbar_id
  formatted_error << "\n"
  formatted_error << "    More information in #{error_log_path}"
  formatted_error << "\n"
  formatted_error.join("\n")
end

#format_with_bang(message) ⇒ Object



267
268
269
270
# File 'lib/heroku/helpers.rb', line 267

def format_with_bang(message)
  return '' if message.to_s.strip == ""
  " !    " + message.split("\n").join("\n !    ")
end

#get_terminal_environmentObject



236
237
238
239
240
# File 'lib/heroku/helpers.rb', line 236

def get_terminal_environment
  { "TERM" => ENV["TERM"], "COLUMNS" => `tput cols`.strip, "LINES" => `tput lines`.strip }
rescue
  { "TERM" => ENV["TERM"] }
end

#git(args) ⇒ Object



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

def git(args)
  return "" unless has_git?
  flattened_args = [args].flatten.compact.join(" ")
  %x{ git #{flattened_args} 2>&1 }.strip
end

#has_git?Boolean

Returns:

  • (Boolean)


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

def has_git?
  %x{ git --version }
  $?.success?
end

#has_git_remote?(remote) ⇒ Boolean

Returns:

  • (Boolean)


161
162
163
# File 'lib/heroku/helpers.rb', line 161

def has_git_remote?(remote)
  git('remote').split("\n").include?(remote) && $?.success?
end

#has_http_git_entry_in_netrcObject



559
560
561
# File 'lib/heroku/helpers.rb', line 559

def has_http_git_entry_in_netrc
  Auth.netrc && Auth.netrc[Auth.http_git_host]
end

#home_directoryObject



6
7
8
9
# File 'lib/heroku/helpers.rb', line 6

def home_directory
  return Dir.home if defined? Dir.home # Ruby 1.9+
  running_on_windows? ? ENV['USERPROFILE'].gsub("\\","/") : ENV['HOME']
end

#hprint(string = '') ⇒ Object



343
344
345
346
# File 'lib/heroku/helpers.rb', line 343

def hprint(string='')
  Kernel.print(string)
  $stdout.flush
end

#hputs(string = '') ⇒ Object



339
340
341
# File 'lib/heroku/helpers.rb', line 339

def hputs(string='')
  Kernel.puts(string)
end

#json_decode(json) ⇒ Object



211
212
213
214
215
# File 'lib/heroku/helpers.rb', line 211

def json_decode(json)
  MultiJson.load(json)
rescue MultiJson::ParseError
  nil
end

#json_encode(object) ⇒ Object



205
206
207
208
209
# File 'lib/heroku/helpers.rb', line 205

def json_encode(object)
  MultiJson.dump(object)
rescue MultiJson::ParseError
  nil
end

#launchy(message, url) ⇒ Object



352
353
354
355
356
357
358
359
360
# File 'lib/heroku/helpers.rb', line 352

def launchy(message, url)
  action(message) do
    require("launchy")
    launchy = Launchy.open(url)
    if launchy.respond_to?(:join)
      launchy.join
    end
  end
end

#line_formatter(array) ⇒ Object

produces a printf formatter line for an array of items if an individual line item is an array, it will create columns that are lined-up

line_formatter([“foo”, “barbaz”]) # => “%-6s” line_formatter([“foo”, “barbaz”], [“bar”, “qux”]) # => “%-3s %-6s”



369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'lib/heroku/helpers.rb', line 369

def line_formatter(array)
  if array.any? {|item| item.is_a?(Array)}
    cols = []
    array.each do |item|
      if item.is_a?(Array)
        item.each_with_index { |val,idx| cols[idx] = [cols[idx]||0, (val || '').length].max }
      end
    end
    cols.map { |col| "%-#{col}s" }.join("  ")
  else
    "%s"
  end
end

#longest(items) ⇒ Object



177
178
179
# File 'lib/heroku/helpers.rb', line 177

def longest(items)
  items.map { |i| i.to_s.length }.sort.last
end

#org?(email) ⇒ Boolean

Returns:

  • (Boolean)


551
552
553
# File 'lib/heroku/helpers.rb', line 551

def org? email
  email =~ /^.*@#{org_host}$/
end

#org_hostObject



543
544
545
# File 'lib/heroku/helpers.rb', line 543

def org_host
  ENV["HEROKU_ORG_HOST"] || default_org_host
end

#output_with_bang(message = "", new_line = true) ⇒ Object



272
273
274
275
# File 'lib/heroku/helpers.rb', line 272

def output_with_bang(message="", new_line=true)
  return if message.to_s.strip == ""
  display(format_with_bang(message), new_line)
end

#quantify(string, num) ⇒ Object



157
158
159
# File 'lib/heroku/helpers.rb', line 157

def quantify(string, num)
  "%d %s" % [ num, num.to_i == 1 ? string : "#{string}s" ]
end

#redisplay(line, line_break = false) ⇒ Object



28
29
30
# File 'lib/heroku/helpers.rb', line 28

def redisplay(line, line_break = false)
  display("\r\e[0K#{line}", line_break)
end

#retry_on_exception(*exceptions) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
# File 'lib/heroku/helpers.rb', line 95

def retry_on_exception(*exceptions)
  retry_count = 0
  begin
    yield
  rescue *exceptions => ex
    raise ex if retry_count >= 3
    sleep 3
    retry_count += 1
    retry
  end
end

#run_command(command, args = []) ⇒ Object



91
92
93
# File 'lib/heroku/helpers.rb', line 91

def run_command(command, args=[])
  Heroku::Command.run(command, args)
end

#running_on_a_mac?Boolean

Returns:

  • (Boolean)


15
16
17
# File 'lib/heroku/helpers.rb', line 15

def running_on_a_mac?
  RUBY_PLATFORM =~ /-darwin\d/
end

#running_on_windows?Boolean

Returns:

  • (Boolean)


11
12
13
# File 'lib/heroku/helpers.rb', line 11

def running_on_windows?
  RUBY_PLATFORM =~ /mswin32|mingw32/
end

#set_buffer(enable) ⇒ Object



217
218
219
220
221
222
223
224
225
# File 'lib/heroku/helpers.rb', line 217

def set_buffer(enable)
  with_tty do
    if enable
      `stty icanon echo`
    else
      `stty -icanon -echo`
    end
  end
end

#shell(cmd) ⇒ Object



87
88
89
# File 'lib/heroku/helpers.rb', line 87

def shell(cmd)
  FileUtils.cd(Dir.pwd) {|d| return `#{cmd}`}
end

#spinner(ticks) ⇒ Object



348
349
350
# File 'lib/heroku/helpers.rb', line 348

def spinner(ticks)
  %w(/ - \\ |)[ticks % 4]
end

#status(message) ⇒ Object



263
264
265
# File 'lib/heroku/helpers.rb', line 263

def status(message)
  @status = message
end

#stderr_print(*args) ⇒ Object



44
45
46
# File 'lib/heroku/helpers.rb', line 44

def stderr_print(*args)
  $stderr.print(*args)
end

#stderr_puts(*args) ⇒ Object



40
41
42
# File 'lib/heroku/helpers.rb', line 40

def stderr_puts(*args)
  $stderr.puts(*args)
end

#string_distance(first, last) ⇒ Object



489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
# File 'lib/heroku/helpers.rb', line 489

def string_distance(first, last)
  distances = [] # 0x0s
  0.upto(first.length) do |index|
    distances << [index] + [0] * last.length
  end
  distances[0] = 0.upto(last.length).to_a
  1.upto(last.length) do |last_index|
    1.upto(first.length) do |first_index|
      first_char = first[first_index - 1, 1]
      last_char = last[last_index - 1, 1]
      if first_char == last_char
        distances[first_index][last_index] = distances[first_index - 1][last_index - 1] # noop
      else
        distances[first_index][last_index] = [
          distances[first_index - 1][last_index],     # deletion
          distances[first_index][last_index - 1],     # insertion
          distances[first_index - 1][last_index - 1]  # substitution
        ].min + 1 # cost
        if first_index > 1 && last_index > 1
          first_previous_char = first[first_index - 2, 1]
          last_previous_char = last[last_index - 2, 1]
          if first_char == last_previous_char && first_previous_char == last_char
            distances[first_index][last_index] = [
              distances[first_index][last_index],
              distances[first_index - 2][last_index - 2] + 1 # transposition
            ].min
          end
        end
      end
    end
  end
  distances[first.length][last.length]
end

#styled_array(array, options = {}) ⇒ Object



383
384
385
386
387
388
389
390
# File 'lib/heroku/helpers.rb', line 383

def styled_array(array, options={})
  fmt = line_formatter(array)
  array = array.sort unless options[:sort] == false
  array.each do |element|
    display((fmt % element).rstrip)
  end
  display
end

#styled_error(error, message = 'Heroku client internal error.') ⇒ Object



436
437
438
439
440
441
442
443
444
# File 'lib/heroku/helpers.rb', line 436

def styled_error(error, message='Heroku client internal error.')
  if Heroku::Helpers.error_with_failure
    display("failed")
    Heroku::Helpers.error_with_failure = false
  end
  rollbar_id = Rollbar.error(error)
  $stderr.puts(format_error(error, message, rollbar_id))
  error_log(message, error.message, error.backtrace.join("\n"))
end

#styled_hash(hash, keys = nil) ⇒ Object



461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
# File 'lib/heroku/helpers.rb', line 461

def styled_hash(hash, keys=nil)
  max_key_length = hash.keys.map {|key| key.to_s.length}.max + 2
  keys ||= hash.keys.sort {|x,y| x.to_s <=> y.to_s}
  keys.each do |key|
    case value = hash[key]
    when Array
      if value.empty?
        next
      else
        elements = value.sort {|x,y| x.to_s <=> y.to_s}
        display("#{key}: ".ljust(max_key_length), false)
        display(elements[0])
        elements[1..-1].each do |element|
          display("#{' ' * max_key_length}#{element}")
        end
        if elements.length > 1
          display
        end
      end
    when nil
      next
    else
      display("#{key}: ".ljust(max_key_length), false)
      display(value)
    end
  end
end

#styled_header(header) ⇒ Object



457
458
459
# File 'lib/heroku/helpers.rb', line 457

def styled_header(header)
  display("=== #{header}")
end

#suggestion(actual, possibilities) ⇒ Object



523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
# File 'lib/heroku/helpers.rb', line 523

def suggestion(actual, possibilities)
  distances = Hash.new {|hash,key| hash[key] = []}

  possibilities.each do |suggestion|
    distances[string_distance(actual, suggestion)] << suggestion
  end

  minimum_distance = distances.keys.min
  if minimum_distance < 4
    suggestions = distances[minimum_distance].sort
    if suggestions.length == 1
      "Perhaps you meant `#{suggestions.first}`."
    else
      "Perhaps you meant #{suggestions[0...-1].map {|suggestion| "`#{suggestion}`"}.join(', ')} or `#{suggestions.last}`."
    end
  else
    nil
  end
end

#time_ago(since) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/heroku/helpers.rb', line 118

def time_ago(since)
  if since.is_a?(String)
    since = Time.parse(since)
  end

  elapsed = Time.now - since

  message = since.strftime("%Y/%m/%d %H:%M:%S")
  if elapsed <= 60
    message << " (~ #{elapsed.floor}s ago)"
  elsif elapsed <= (60 * 60)
    message << " (~ #{(elapsed / 60).floor}m ago)"
  elsif elapsed <= (60 * 60 * 25)
    message << " (~ #{(elapsed / 60 / 60).floor}h ago)"
  end
  message
end

#truncate(text, length) ⇒ Object



136
137
138
139
140
141
142
143
# File 'lib/heroku/helpers.rb', line 136

def truncate(text, length)
  return "" if text.nil?
  if text.size > length
    text[0, length - 2] + '..'
  else
    text
  end
end

#update_git_remote(remote, url) ⇒ Object



171
172
173
174
175
# File 'lib/heroku/helpers.rb', line 171

def update_git_remote(remote, url)
  return unless has_git_remote? remote
  git "remote set-url #{remote} #{url}"
  display "Git remote #{remote} updated" if $?.success?
end

#warn_if_using_jrubyObject



563
564
565
# File 'lib/heroku/helpers.rb', line 563

def warn_if_using_jruby
  stderr_puts "WARNING: jruby is known to cause issues when used with the toolbelt." if RUBY_PLATFORM == "java"
end

#with_tty(&block) ⇒ Object



227
228
229
230
231
232
233
234
# File 'lib/heroku/helpers.rb', line 227

def with_tty(&block)
  return unless $stdin.isatty
  begin
    yield
  rescue
    # fails on windows
  end
end