Module: Nimbu::Helpers
Defined Under Namespace
Modules: System
Constant Summary
collapse
- @@kb =
1024
- @@mb =
1024 * @@kb
- @@gb =
1024 * @@mb
Class Method Summary
collapse
Instance Method Summary
collapse
-
#action(message) ⇒ Object
-
#ask ⇒ Object
-
#confirm(message = "Are you sure you wish to continue? (y/n)?") ⇒ Object
-
#confirm_billing ⇒ Object
-
#confirm_command(app_to_confirm = app, message = nil) ⇒ Object
-
#create_git_remote(remote, url) ⇒ Object
-
#deprecate(version) ⇒ Object
-
#display(msg = "", new_line = true) ⇒ Object
-
#display_header(message = "", new_line = true) ⇒ Object
-
#display_object(object) ⇒ Object
-
#display_row(row, lengths) ⇒ Object
-
#display_table(objects, columns, headers) ⇒ Object
-
#error(msg) ⇒ Object
-
#fail(message) ⇒ Object
-
#format_bytes(amount) ⇒ Object
-
#format_date(date) ⇒ Object
-
#format_error(error, message = 'Nimbu client internal error.') ⇒ Object
-
#format_with_bang(message) ⇒ Object
-
#get_terminal_environment ⇒ Object
-
#git(args) ⇒ Object
-
#has_git? ⇒ Boolean
-
#home_directory ⇒ Object
-
#hprint(string = '') ⇒ Object
-
#hputs(string = '') ⇒ Object
-
#json_decode(json) ⇒ Object
-
#json_encode(object) ⇒ Object
-
#launchy(message, url) ⇒ Object
-
#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.
-
#longest(items) ⇒ Object
-
#output(message = "", new_line = true) ⇒ Object
-
#output_with_arrow(message = "", new_line = true) ⇒ Object
-
#output_with_bang(message = "", new_line = true) ⇒ Object
-
#quantify(string, num) ⇒ Object
-
#redisplay(line, line_break = false) ⇒ Object
-
#retry_on_exception(*exceptions) ⇒ Object
-
#run_command(command, args = []) ⇒ Object
-
#running_on_a_mac? ⇒ Boolean
-
#running_on_windows? ⇒ Boolean
-
#set_buffer(enable) ⇒ Object
-
#shell(cmd) ⇒ Object
-
#spinner(ticks) ⇒ Object
-
#status(message) ⇒ Object
-
#string_distance(first, last) ⇒ Object
-
#styled_array(array, options = {}) ⇒ Object
-
#styled_error(error, message = 'Nimbu client internal error.') ⇒ Object
-
#styled_hash(hash, keys = nil) ⇒ Object
-
#styled_header(header) ⇒ Object
-
#suggestion(actual, possibilities) ⇒ Object
-
#time_ago(elapsed) ⇒ Object
-
#truncate(text, length) ⇒ Object
-
#with_tty(&block) ⇒ Object
Methods included from System
browser_launcher, command?, osx?, tmp_dir, which, windows?
Class Method Details
.disable_error_capture ⇒ Object
302
303
304
305
306
307
308
309
310
311
|
# File 'lib/nimbu/command/helpers.rb', line 302
def self.disable_error_capture
included_into.each do |base|
base.send(:alias_method, :error, :error_without_failure)
end
extended_into.each do |base|
class << base
alias_method :error, :error_without_failure
end
end
end
|
.enable_error_capture ⇒ Object
289
290
291
292
293
294
295
296
297
298
299
300
|
# File 'lib/nimbu/command/helpers.rb', line 289
def self.enable_error_capture
included_into.each do |base|
base.send(:alias_method, :error_without_failure, :error)
base.send(:alias_method, :error, :error_with_failure)
end
extended_into.each do |base|
class << base
alias_method :error_without_failure, :error
alias_method :error, :error_with_failure
end
end
end
|
.error_with_failure ⇒ Object
271
272
273
|
# File 'lib/nimbu/helpers.rb', line 271
def self.error_with_failure
@@error_with_failure ||= false
end
|
.error_with_failure=(new_error_with_failure) ⇒ Object
275
276
277
|
# File 'lib/nimbu/helpers.rb', line 275
def self.error_with_failure=(new_error_with_failure)
@@error_with_failure = new_error_with_failure
end
|
.extended(base) ⇒ Object
291
292
293
|
# File 'lib/nimbu/helpers.rb', line 291
def self.extended(base)
extended_into << base
end
|
.extended_into ⇒ Object
283
284
285
|
# File 'lib/nimbu/helpers.rb', line 283
def self.extended_into
@@extended_into ||= []
end
|
.included(base) ⇒ Object
287
288
289
|
# File 'lib/nimbu/helpers.rb', line 287
def self.included(base)
included_into << base
end
|
.included_into ⇒ Object
279
280
281
|
# File 'lib/nimbu/helpers.rb', line 279
def self.included_into
@@included_into ||= []
end
|
Instance Method Details
#action(message) ⇒ Object
234
235
236
237
238
239
240
241
242
243
244
245
246
|
# File 'lib/nimbu/helpers.rb', line 234
def action(message, options={})
display("#{message}... ", false)
Nimbu::Helpers.error_with_failure = true
ret = yield
Nimbu::Helpers.error_with_failure = false
display((options[:success] || "done"), false)
if @status
display(", #{@status}", false)
@status = nil
end
display
ret
end
|
#ask ⇒ Object
79
80
81
|
# File 'lib/nimbu/helpers.rb', line 79
def ask
$stdin.gets.to_s.strip
end
|
#confirm(message = "Are you sure you wish to continue? (y/n)?") ⇒ Object
48
49
50
51
|
# File 'lib/nimbu/helpers.rb', line 48
def confirm(message="Are you sure you wish to continue? (y/n)")
display("#{message} ", false)
['y', 'yes'].include?(ask.downcase)
end
|
#confirm_billing ⇒ Object
38
39
40
41
42
43
44
45
46
|
# File 'lib/nimbu/helpers.rb', line 38
def confirm_billing
display
display "This action will cause your account to be billed at the end of the month"
display "For more information, see https://devcenter.Nimbu.com/articles/usage-and-billing"
if confirm
Nimbu::Auth.client.confirm_billing
true
end
end
|
#confirm_command(app_to_confirm = app, message = nil) ⇒ Object
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
# File 'lib/nimbu/helpers.rb', line 53
def confirm_command(app_to_confirm = app, message=nil)
if confirmed_app = Nimbu::Command.current_options[:confirm]
unless confirmed_app == app_to_confirm
raise(Nimbu::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
156
157
158
159
160
161
|
# File 'lib/nimbu/helpers.rb', line 156
def create_git_remote(remote, url)
return if git('remote').split("\n").include?(remote)
return unless File.exists?(".git")
git "remote add #{remote} #{url}"
display "Git remote #{remote} added"
end
|
#deprecate(version) ⇒ Object
34
35
36
|
# File 'lib/nimbu/helpers.rb', line 34
def deprecate(message)
display "WARNING: #{message}"
end
|
#display(msg = "", new_line = true) ⇒ Object
21
22
23
24
25
26
27
28
|
# File 'lib/nimbu/helpers.rb', line 21
def display(msg="", new_line=true)
if new_line
puts(msg)
else
print(msg)
$stdout.flush
end
end
|
295
296
297
298
|
# File 'lib/nimbu/helpers.rb', line 295
def (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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
|
# File 'lib/nimbu/helpers.rb', line 300
def display_object(object)
case object
when Array
object.each do |item|
display_object(item)
end
when Hash
if object.values.all? {|value| value.is_a?(Array)}
object.keys.sort_by {|key| key.to_s}.each do |key|
(key)
display_object(object[key])
hputs
end
end
else
hputs(object.to_s)
end
end
|
#display_row(row, lengths) ⇒ Object
182
183
184
185
186
187
188
189
|
# File 'lib/nimbu/helpers.rb', line 182
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
|
# File 'lib/nimbu/helpers.rb', line 167
def display_table(objects, columns, )
lengths = []
columns.each_with_index do |column, index|
= [index]
lengths << longest([].concat(objects.map { |o| o[column].to_s }))
end
lines = lengths.map {|length| "-" * length}
lengths[-1] = 0
display_row , lengths
display_row lines, lengths
objects.each do |row|
display_row columns.map { |column| row[column] }, lengths
end
end
|
#error(msg) ⇒ Object
262
263
264
265
266
267
268
269
|
# File 'lib/nimbu/helpers.rb', line 262
def error(message)
if Nimbu::Helpers.error_with_failure
display("failed")
Nimbu::Helpers.error_with_failure = false
end
$stderr.puts(format_with_bang(message))
exit(1)
end
|
#fail(message) ⇒ Object
228
229
230
|
# File 'lib/nimbu/helpers.rb', line 228
def fail(message)
raise Nimbu::Command::CommandFailed, message
end
|
143
144
145
146
147
148
149
150
|
# File 'lib/nimbu/helpers.rb', line 143
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
|
74
75
76
77
|
# File 'lib/nimbu/helpers.rb', line 74
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
|
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
|
# File 'lib/nimbu/helpers.rb', line 375
def format_error(error, message='Nimbu client internal error.')
formatted_error = []
formatted_error << " ! #{message}"
formatted_error << ' ! Search for help at: https://help.nimbu.io'
formatted_error << ' ! Or report a bug at: https://github.com/nimbu/nimbu/issues/new'
formatted_error << ''
formatted_error << " Error: #{error.message} (#{error.class})"
formatted_error << " Backtrace: #{error.backtrace.first}"
error.backtrace[1..-1].each do |line|
formatted_error << " #{line}"
end
if error.backtrace.length > 1
formatted_error << ''
end
command = ARGV.map do |arg|
if arg.include?(' ')
arg = %{"#{arg}"}
else
arg
end
end.join(' ')
formatted_error << " Command: nimbu #{command}"
require 'nimbu/auth'
unless Nimbu::Auth.host == Nimbu::Auth.default_host
formatted_error << " Host: #{Nimbu::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
formatted_error << " Version: #{Nimbu.user_agent}"
formatted_error << "\n"
formatted_error.join("\n")
end
|
252
253
254
255
|
# File 'lib/nimbu/helpers.rb', line 252
def format_with_bang(message)
return '' if message.to_s.strip == ""
" ! " + message.split("\n").join("\n ! ")
end
|
#get_terminal_environment ⇒ Object
222
223
224
225
226
|
# File 'lib/nimbu/helpers.rb', line 222
def get_terminal_environment
{ "TERM" => ENV["TERM"], "COLUMNS" => `tput cols`.strip, "LINES" => `tput lines`.strip }
rescue
{ "TERM" => ENV["TERM"] }
end
|
#git(args) ⇒ Object
108
109
110
111
112
|
# File 'lib/nimbu/helpers.rb', line 108
def git(args)
return "" unless has_git?
flattened_args = [args].flatten.compact.join(" ")
%x{ git #{flattened_args} 2>&1 }.strip
end
|
#has_git? ⇒ Boolean
103
104
105
106
|
# File 'lib/nimbu/helpers.rb', line 103
def has_git?
%x{ git --version }
$?.success?
end
|
#home_directory ⇒ Object
9
10
11
|
# File 'lib/nimbu/helpers.rb', line 9
def home_directory
running_on_windows? ? ENV['USERPROFILE'].gsub("\\","/") : ENV['HOME']
end
|
#hprint(string = '') ⇒ Object
326
327
328
329
|
# File 'lib/nimbu/helpers.rb', line 326
def hprint(string='')
Kernel.print(string)
$stdout.flush
end
|
#hputs(string = '') ⇒ Object
322
323
324
|
# File 'lib/nimbu/helpers.rb', line 322
def hputs(string='')
Kernel.puts(string)
end
|
#json_decode(json) ⇒ Object
197
198
199
200
201
|
# File 'lib/nimbu/helpers.rb', line 197
def json_decode(json)
Nimbu::OkJson.decode(json)
rescue Nimbu::OkJson::Error
nil
end
|
#json_encode(object) ⇒ Object
191
192
193
194
195
|
# File 'lib/nimbu/helpers.rb', line 191
def json_encode(object)
Nimbu::OkJson.encode(object)
rescue Nimbu::OkJson::Error
nil
end
|
#launchy(message, url) ⇒ Object
335
336
337
338
339
340
341
342
343
|
# File 'lib/nimbu/helpers.rb', line 335
def launchy(message, url)
action(message) do
require("launchy")
launchy = Launchy.open(url)
if launchy.respond_to?(:join)
launchy.join
end
end
end
|
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”
352
353
354
355
356
357
358
359
360
361
362
363
364
|
# File 'lib/nimbu/helpers.rb', line 352
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
163
164
165
|
# File 'lib/nimbu/helpers.rb', line 163
def longest(items)
items.map { |i| i.to_s.length }.sort.last
end
|
#output(message = "", new_line = true) ⇒ Object
245
246
247
248
|
# File 'lib/nimbu/command/helpers.rb', line 245
def output(message="", new_line=true)
return if message.to_s.strip == ""
display(" " + message.split("\n").join("\n "), new_line)
end
|
#output_with_arrow(message = "", new_line = true) ⇒ Object
250
251
252
253
|
# File 'lib/nimbu/command/helpers.rb', line 250
def output_with_arrow(message="", new_line=true)
return if message.to_s.strip == ""
display("----> " + message.split("\n").join("\n "), new_line)
end
|
#output_with_bang(message = "", new_line = true) ⇒ Object
257
258
259
260
|
# File 'lib/nimbu/helpers.rb', line 257
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
152
153
154
|
# File 'lib/nimbu/helpers.rb', line 152
def quantify(string, num)
"%d %s" % [ num, num.to_i == 1 ? string : "#{string}s" ]
end
|
#redisplay(line, line_break = false) ⇒ Object
30
31
32
|
# File 'lib/nimbu/helpers.rb', line 30
def redisplay(line, line_break = false)
display("\r\e[0K#{line}", line_break)
end
|
#retry_on_exception(*exceptions) ⇒ Object
91
92
93
94
95
96
97
98
99
100
101
|
# File 'lib/nimbu/helpers.rb', line 91
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
87
88
89
|
# File 'lib/nimbu/helpers.rb', line 87
def run_command(command, args=[])
Nimbu::Command.run(command, args)
end
|
#running_on_a_mac? ⇒ Boolean
17
18
19
|
# File 'lib/nimbu/helpers.rb', line 17
def running_on_a_mac?
RUBY_PLATFORM =~ /-darwin\d/
end
|
#running_on_windows? ⇒ Boolean
13
14
15
|
# File 'lib/nimbu/helpers.rb', line 13
def running_on_windows?
RUBY_PLATFORM =~ /mswin32|mingw32/
end
|
#set_buffer(enable) ⇒ Object
203
204
205
206
207
208
209
210
211
|
# File 'lib/nimbu/helpers.rb', line 203
def set_buffer(enable)
with_tty do
if enable
`stty icanon echo`
else
`stty -icanon -echo`
end
end
end
|
#shell(cmd) ⇒ Object
83
84
85
|
# File 'lib/nimbu/helpers.rb', line 83
def shell(cmd)
FileUtils.cd(Dir.pwd) {|d| return `#{cmd}`}
end
|
#spinner(ticks) ⇒ Object
331
332
333
|
# File 'lib/nimbu/helpers.rb', line 331
def spinner(ticks)
%w(/ - \\ |)[ticks % 4]
end
|
#status(message) ⇒ Object
248
249
250
|
# File 'lib/nimbu/helpers.rb', line 248
def status(message)
@status = message
end
|
#string_distance(first, last) ⇒ Object
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
|
# File 'lib/nimbu/helpers.rb', line 452
def string_distance(first, last)
distances = []
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]
else
distances[first_index][last_index] = [
distances[first_index - 1][last_index],
distances[first_index][last_index - 1],
distances[first_index - 1][last_index - 1]
].min + 1
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
].min
end
end
end
end
end
distances[first.length][last.length]
end
|
#styled_array(array, options = {}) ⇒ Object
366
367
368
369
370
371
372
373
|
# File 'lib/nimbu/helpers.rb', line 366
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 = 'Nimbu client internal error.') ⇒ Object
412
413
414
415
416
417
418
|
# File 'lib/nimbu/helpers.rb', line 412
def styled_error(error, message='Nimbu client internal error.')
if Nimbu::Helpers.error_with_failure
display("failed")
Nimbu::Helpers.error_with_failure = false
end
$stderr.puts(format_error(error, message))
end
|
#styled_hash(hash, keys = nil) ⇒ Object
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
|
# File 'lib/nimbu/helpers.rb', line 424
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
|
420
421
422
|
# File 'lib/nimbu/helpers.rb', line 420
def ()
display("=== #{header}")
end
|
#suggestion(actual, possibilities) ⇒ Object
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
|
# File 'lib/nimbu/helpers.rb', line 486
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(elapsed) ⇒ Object
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
|
# File 'lib/nimbu/helpers.rb', line 114
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
132
133
134
135
136
137
138
|
# File 'lib/nimbu/helpers.rb', line 132
def truncate(text, length)
if text.size > length
text[0, length - 2] + '..'
else
text
end
end
|
#with_tty(&block) ⇒ Object
213
214
215
216
217
218
219
220
|
# File 'lib/nimbu/helpers.rb', line 213
def with_tty(&block)
return unless $stdin.isatty
begin
yield
rescue
end
end
|