Module: Clitopic::Helpers
Constant Summary collapse
- @@kb =
1024- @@mb =
1024 * @@kb
- @@gb =
1024 * @@mb
Class Method Summary collapse
- .error_with_failure ⇒ Object
- .error_with_failure=(new_error_with_failure) ⇒ Object
- .extended(base) ⇒ Object
- .extended_into ⇒ Object
- .included(base) ⇒ Object
- .included_into ⇒ Object
Instance Method Summary collapse
-
#action(message, options = {}) ⇒ Object
DISPLAY HELPERS.
- #ask ⇒ Object
- #confirm(message = "Are you sure you wish to continue? (y/n)") ⇒ Object
- #confirm_command(app_to_confirm = app, message = nil) ⇒ Object
- #create_git_remote(remote, url) ⇒ Object
- #debug(*args) ⇒ Object
- #debugging? ⇒ Boolean
-
#deep_clone(obj) ⇒ Object
cheap deep clone.
- #deprecate(message) ⇒ Object
- #display(msg = "", new_line = true) ⇒ Object
- #display_header(message = "", new_line = true) ⇒ Object
- #display_object(object) ⇒ Object
- #display_row(row, lengths) ⇒ Object
- #display_suggestion(actual, possibilities, allowed_distance = 4) ⇒ Object
- #display_table(objects, columns, headers) ⇒ Object
- #error(message, report = false) ⇒ Object
- #error_log(*obj) ⇒ Object
- #error_log_path ⇒ Object
- #fail(message) ⇒ Object
- #find_default_file ⇒ Object
- #format_bytes(amount) ⇒ Object
- #format_date(date) ⇒ Object
- #format_error(error, message = 'Clitopic client internal error.') ⇒ Object
- #format_with_bang(message) ⇒ Object
- #get_terminal_environment ⇒ Object
- #has_git_remote?(remote) ⇒ Boolean
- #home_directory ⇒ Object
- #hprint(string = '') ⇒ Object
- #hputs(string = '') ⇒ Object
- #in_message(message, options = {}) ⇒ 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_with_bang(message = "", new_line = true) ⇒ Object
- #quantify(string, num) ⇒ Object
- #redisplay(line, line_break = false) ⇒ Object
- #run_command(command, args = []) ⇒ Object
- #set_buffer(enable) ⇒ Object
- #shell(cmd) ⇒ Object
- #spinner(ticks) ⇒ Object
- #status(message) ⇒ Object
- #stderr_print(*args) ⇒ Object
- #stderr_puts(*args) ⇒ Object
- #string_distance(first, last) ⇒ Object
- #styled_array(array, options = {}) ⇒ Object
- #styled_error(error, message = 'Clitopic client internal error.') ⇒ Object
- #styled_hash(hash, keys = nil) ⇒ Object
- #styled_header(header) ⇒ Object
- #suggestion(actual, possibilities, allowed_distance = 4) ⇒ Object
- #time_ago(since) ⇒ Object
- #time_remaining(from, to) ⇒ Object
- #truncate(text, length) ⇒ Object
- #with_tty(&block) ⇒ Object
Class Method Details
.error_with_failure ⇒ Object
287 288 289 |
# File 'lib/clitopic/helpers.rb', line 287 def self.error_with_failure @@error_with_failure ||= false end |
.error_with_failure=(new_error_with_failure) ⇒ Object
291 292 293 |
# File 'lib/clitopic/helpers.rb', line 291 def self.error_with_failure=(new_error_with_failure) @@error_with_failure = new_error_with_failure end |
.extended(base) ⇒ Object
307 308 309 |
# File 'lib/clitopic/helpers.rb', line 307 def self.extended(base) extended_into << base end |
.extended_into ⇒ Object
299 300 301 |
# File 'lib/clitopic/helpers.rb', line 299 def self.extended_into @@extended_into ||= [] end |
.included(base) ⇒ Object
303 304 305 |
# File 'lib/clitopic/helpers.rb', line 303 def self.included(base) included_into << base end |
.included_into ⇒ Object
295 296 297 |
# File 'lib/clitopic/helpers.rb', line 295 def self.included_into @@included_into ||= [] end |
Instance Method Details
#action(message, options = {}) ⇒ Object
DISPLAY HELPERS
244 245 246 247 248 249 250 251 252 253 254 255 256 |
# File 'lib/clitopic/helpers.rb', line 244 def action(, ={}) display("#{in_message(message, options)}... ", false) Clitopic::Helpers.error_with_failure = true ret = yield Clitopic::Helpers.error_with_failure = false display(([:success] || "done"), false) if @status display(", #{@status}", false) @status = nil end display ret end |
#ask ⇒ Object
100 101 102 |
# File 'lib/clitopic/helpers.rb', line 100 def ask $stdin.gets.to_s.strip end |
#confirm(message = "Are you sure you wish to continue? (y/n)") ⇒ Object
69 70 71 72 |
# File 'lib/clitopic/helpers.rb', line 69 def confirm(="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
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
# File 'lib/clitopic/helpers.rb', line 74 def confirm_command(app_to_confirm = app, =nil) if confirmed_app = Clitopic::Commands.[:confirm] unless confirmed_app == app_to_confirm raise(Clitopic::Commands::CommandFailed, "Confirmed app #{confirmed_app} did not match the selected app #{app_to_confirm}.") end return true else display ||= "WARNING: Destructive Action\n" << "\nTo proceed, type \"#{app_to_confirm}\" or re-run this command with --confirm #{app_to_confirm}" output_with_bang() 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
169 170 171 172 173 |
# File 'lib/clitopic/helpers.rb', line 169 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
53 54 55 |
# File 'lib/clitopic/helpers.rb', line 53 def debug(*args) $stderr.puts(*args) if debugging? end |
#debugging? ⇒ Boolean
65 66 67 |
# File 'lib/clitopic/helpers.rb', line 65 def debugging? ENV['CLITOPIC_DEBUG'] end |
#deep_clone(obj) ⇒ Object
cheap deep clone
554 555 556 |
# File 'lib/clitopic/helpers.rb', line 554 def deep_clone(obj) json_decode(json_encode(obj)) end |
#deprecate(message) ⇒ Object
49 50 51 |
# File 'lib/clitopic/helpers.rb', line 49 def deprecate() display "WARNING: #{message}" end |
#display(msg = "", new_line = true) ⇒ Object
36 37 38 39 40 41 42 43 |
# File 'lib/clitopic/helpers.rb', line 36 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
311 312 313 314 |
# File 'lib/clitopic/helpers.rb', line 311 def display_header(="", new_line=true) return if .to_s.strip == "" display("=== " + .to_s.split("\n").join("\n=== "), new_line) end |
#display_object(object) ⇒ Object
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 |
# File 'lib/clitopic/helpers.rb', line 316 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
194 195 196 197 198 199 200 201 |
# File 'lib/clitopic/helpers.rb', line 194 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_suggestion(actual, possibilities, allowed_distance = 4) ⇒ Object
521 522 523 524 525 526 527 528 529 530 |
# File 'lib/clitopic/helpers.rb', line 521 def display_suggestion(actual, possibilities, allowed_distance=4) suggestions = suggestion(actual, possibilities, allowed_distance) if suggestions.length == 1 "Perhaps you meant:\n" + suggestions.first.indent(20) elsif suggestions.length > 1 "Perhaps you meant:\n" + "#{suggestions.map {|suggestion| "- #{suggestion}"}.join("\n").indent(2)}." else nil end end |
#display_table(objects, columns, headers) ⇒ Object
179 180 181 182 183 184 185 186 187 188 189 190 191 192 |
# File 'lib/clitopic/helpers.rb', line 179 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
278 279 280 281 282 283 284 285 |
# File 'lib/clitopic/helpers.rb', line 278 def error(, report=false) if Clitopic::Helpers.error_with_failure display("failed") Clitopic::Helpers.error_with_failure = false end $stderr.puts(format_with_bang()) exit(1) end |
#error_log(*obj) ⇒ Object
433 434 435 436 437 438 |
# File 'lib/clitopic/helpers.rb', line 433 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_path ⇒ Object
451 452 453 |
# File 'lib/clitopic/helpers.rb', line 451 def error_log_path File.join(home_directory, '.clitopic', 'error.log') end |
#fail(message) ⇒ Object
238 239 240 |
# File 'lib/clitopic/helpers.rb', line 238 def fail() raise Clitopic::Commands::CommandFailed, end |
#find_default_file ⇒ Object
440 441 442 443 444 445 446 447 448 449 |
# File 'lib/clitopic/helpers.rb', line 440 def find_default_file file = nil Clitopic.default_files.each do |f| if File.exist?(f) file = f break end end return file end |
#format_bytes(amount) ⇒ Object
152 153 154 155 156 157 158 159 |
# File 'lib/clitopic/helpers.rb', line 152 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
95 96 97 98 |
# File 'lib/clitopic/helpers.rb', line 95 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 = 'Clitopic client internal error.') ⇒ Object
391 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 |
# File 'lib/clitopic/helpers.rb', line 391 def format_error(error, ='Clitopic client internal error.') formatted_error = [] formatted_error << " ! #{message}" formatted_error << " ! Search for help at: #{Clitopic.help_page || "https://github.com/ant31/cli-topic/wiki"}" formatted_error << " ! Or report a bug at: #{Clitopic.issue_report || "https://github.com/ant31/cli-topic/issues/new"} " formatted_error << '' command = ARGV.map do |arg| if arg.include?(' ') arg = %{"#{arg}"} else arg end end.join(' ') formatted_error << " Command: #{command}" 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: #{Clitopic.version}" formatted_error << " Error: #{error.message} (#{error.class})" formatted_error << " Backtrace:\n" + "#{error.backtrace.join("\n")}".indent(17) unless error.backtrace.nil? formatted_error << "\n" formatted_error << " More information in #{error_log_path}" formatted_error << "\n" formatted_error.join("\n") end |
#format_with_bang(message) ⇒ Object
268 269 270 271 |
# File 'lib/clitopic/helpers.rb', line 268 def format_with_bang() return '' if .to_s.strip == "" " ! " + .split("\n").join("\n ! ") end |
#get_terminal_environment ⇒ Object
232 233 234 235 236 |
# File 'lib/clitopic/helpers.rb', line 232 def get_terminal_environment { "TERM" => ENV["TERM"], "COLUMNS" => `tput cols`.strip, "LINES" => `tput lines`.strip } rescue { "TERM" => ENV["TERM"] } end |
#has_git_remote?(remote) ⇒ Boolean
165 166 167 |
# File 'lib/clitopic/helpers.rb', line 165 def has_git_remote?(remote) git('remote').split("\n").include?(remote) && $?.success? end |
#home_directory ⇒ Object
32 33 34 |
# File 'lib/clitopic/helpers.rb', line 32 def home_directory Dir.home end |
#hprint(string = '') ⇒ Object
342 343 344 345 |
# File 'lib/clitopic/helpers.rb', line 342 def hprint(string='') Kernel.print(string) $stdout.flush end |
#hputs(string = '') ⇒ Object
338 339 340 |
# File 'lib/clitopic/helpers.rb', line 338 def hputs(string='') Kernel.puts(string) end |
#in_message(message, options = {}) ⇒ Object
258 259 260 261 262 |
# File 'lib/clitopic/helpers.rb', line 258 def (, ={}) = "#{message} in space #{options[:space]}" if [:space] = "#{message} in organization #{org}" if [:org] end |
#json_decode(json) ⇒ Object
207 208 209 210 211 |
# File 'lib/clitopic/helpers.rb', line 207 def json_decode(json) JSON.parse(json) rescue JSON::ParserError nil end |
#json_encode(object) ⇒ Object
203 204 205 |
# File 'lib/clitopic/helpers.rb', line 203 def json_encode(object) JSON.generate(object) end |
#launchy(message, url) ⇒ Object
351 352 353 354 355 356 357 358 359 |
# File 'lib/clitopic/helpers.rb', line 351 def launchy(, url) action() 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”
368 369 370 371 372 373 374 375 376 377 378 379 380 |
# File 'lib/clitopic/helpers.rb', line 368 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
175 176 177 |
# File 'lib/clitopic/helpers.rb', line 175 def longest(items) items.map { |i| i.to_s.length }.sort.last end |
#output_with_bang(message = "", new_line = true) ⇒ Object
273 274 275 276 |
# File 'lib/clitopic/helpers.rb', line 273 def output_with_bang(="", new_line=true) return if .to_s.strip == "" display(format_with_bang(), new_line) end |
#quantify(string, num) ⇒ Object
161 162 163 |
# File 'lib/clitopic/helpers.rb', line 161 def quantify(string, num) "%d %s" % [ num, num.to_i == 1 ? string : "#{string}s" ] end |
#redisplay(line, line_break = false) ⇒ Object
45 46 47 |
# File 'lib/clitopic/helpers.rb', line 45 def redisplay(line, line_break = false) display("\r\e[0K#{line}", line_break) end |
#run_command(command, args = []) ⇒ Object
108 109 110 |
# File 'lib/clitopic/helpers.rb', line 108 def run_command(command, args=[]) Clitopic::Command.run(command, args) end |
#set_buffer(enable) ⇒ Object
213 214 215 216 217 218 219 220 221 |
# File 'lib/clitopic/helpers.rb', line 213 def set_buffer(enable) with_tty do if enable `stty icanon echo` else `stty -icanon -echo` end end end |
#shell(cmd) ⇒ Object
104 105 106 |
# File 'lib/clitopic/helpers.rb', line 104 def shell(cmd) FileUtils.cd(Dir.pwd) {|d| return `#{cmd}`} end |
#spinner(ticks) ⇒ Object
347 348 349 |
# File 'lib/clitopic/helpers.rb', line 347 def spinner(ticks) %w(/ - \\ |)[ticks % 4] end |
#status(message) ⇒ Object
264 265 266 |
# File 'lib/clitopic/helpers.rb', line 264 def status() @status = end |
#stderr_print(*args) ⇒ Object
61 62 63 |
# File 'lib/clitopic/helpers.rb', line 61 def stderr_print(*args) $stderr.print(*args) end |
#stderr_puts(*args) ⇒ Object
57 58 59 |
# File 'lib/clitopic/helpers.rb', line 57 def stderr_puts(*args) $stderr.puts(*args) end |
#string_distance(first, last) ⇒ Object
487 488 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 |
# File 'lib/clitopic/helpers.rb', line 487 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
382 383 384 385 386 387 388 389 |
# File 'lib/clitopic/helpers.rb', line 382 def styled_array(array, ={}) fmt = line_formatter(array) array = array.sort unless [:sort] == false array.each do |element| display((fmt % element).rstrip) end display end |
#styled_error(error, message = 'Clitopic client internal error.') ⇒ Object
422 423 424 425 426 427 428 429 430 431 |
# File 'lib/clitopic/helpers.rb', line 422 def styled_error(error, ='Clitopic client internal error.') if Clitopic::Helpers.error_with_failure display("failed") Clitopic::Helpers.error_with_failure = false end error_log(, error., error.backtrace.join("\n")) $stderr.puts(format_error(error, )) rescue => e $stderr.puts e, e.backtrace, error, error.backtrace end |
#styled_hash(hash, keys = nil) ⇒ Object
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 485 |
# File 'lib/clitopic/helpers.rb', line 459 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
455 456 457 |
# File 'lib/clitopic/helpers.rb', line 455 def styled_header(header) display("=== #{header}") end |
#suggestion(actual, possibilities, allowed_distance = 4) ⇒ Object
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 |
# File 'lib/clitopic/helpers.rb', line 532 def suggestion(actual, possibilities, allowed_distance=4) distances = Hash.new {|hash,key| hash[key] = []} begin_with = [] possibilities.each do |suggestion| if suggestion.start_with?(actual) distances[0] << suggestion else distances[string_distance(actual, suggestion)] << suggestion end end minimum_distance = distances.keys.min if minimum_distance < allowed_distance suggestions = distances[minimum_distance].sort return suggestions else [] end end |
#time_ago(since) ⇒ Object
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
# File 'lib/clitopic/helpers.rb', line 113 def time_ago(since) if since.is_a?(String) since = Time.parse(since) end elapsed = Time.now - since = since.strftime("%Y/%m/%d %H:%M:%S") if elapsed <= 60 << " (~ #{elapsed.floor}s ago)" elsif elapsed <= (60 * 60) << " (~ #{(elapsed / 60).floor}m ago)" elsif elapsed <= (60 * 60 * 25) << " (~ #{(elapsed / 60 / 60).floor}h ago)" end end |
#time_remaining(from, to) ⇒ Object
131 132 133 134 135 136 137 138 |
# File 'lib/clitopic/helpers.rb', line 131 def time_remaining(from, to) secs = (to - from).to_i mins = secs / 60 hours = mins / 60 return "#{hours}h #{mins % 60}m" if hours > 0 return "#{mins}m #{secs % 60}s" if mins > 0 return "#{secs}s" if secs >= 0 end |
#truncate(text, length) ⇒ Object
140 141 142 143 144 145 146 147 |
# File 'lib/clitopic/helpers.rb', line 140 def truncate(text, length) return "" if text.nil? if text.size > length text[0, length - 2] + '..' else text end end |
#with_tty(&block) ⇒ Object
223 224 225 226 227 228 229 230 |
# File 'lib/clitopic/helpers.rb', line 223 def with_tty(&block) return unless $stdin.isatty begin yield rescue # fails on windows end end |