module RakeScript::Logging

Constants

PROMPT_COLORS
PROMPT_STYLES

RakeScript::Logging helper allows to print useful and colorized output. @see misc.flogisoft.com/bash/tip_colors_and_formatting

RESET_PROMPT

Public Instance Methods

format_text(text, color: :default, background: :default, style: :normal) click to toggle source
# File lib/rake_script/logging.rb, line 38
def format_text(text, color: :default, background: :default, style: :normal)
  fg = PROMPT_COLORS.fetch(color)
  bg = PROMPT_COLORS.fetch(background) + 10
  fmt = PROMPT_STYLES.fetch(style)
  format = "\e[#{fmt};#{fg};#{bg}m"
  "#{format}#{text}#{RESET_PROMPT}"
end
puts_colored(*lines) click to toggle source
# File lib/rake_script/logging.rb, line 46
def puts_colored(*lines)
  options = lines.pop
  raise ArgumentError, 'last argument must be options hash'.freeze unless options.is_a?(Hash)
  raise ArgumentError, 'provide at least one line'.freeze if lines.empty?

  formatted_lines = lines.map { |line| format_text(line, options) }
  puts(*formatted_lines)
end
puts_info(text, color: :blue, style: :bold) click to toggle source
# File lib/rake_script/logging.rb, line 60
def puts_info(text, color: :blue, style: :bold)
  puts_colored(">>> #{text}", color: color, style: style)
end
puts_time(prefix: nil, color: :yellow, style: :bold) click to toggle source
# File lib/rake_script/logging.rb, line 55
def puts_time(prefix: nil, color: :yellow, style: :bold)
  time = Time.now.utc.strftime('%F %T %Z'.freeze)
  puts_colored("#{prefix}[#{time}]", color: color, style: style)
end
with_puts_benchmark(title, show_time: true) { || ... } click to toggle source
# File lib/rake_script/logging.rb, line 64
def with_puts_benchmark(title, show_time: true)
  puts_info title
  puts_time(prefix: "[#{title} begin]") if show_time
  time = Time.now.to_i
  begin
    yield
    took = Time.now.to_i - time
    puts_time(prefix: "[#{title} completed]") if show_time
    puts_colored("[#{title}] took #{took} seconds.", color: :yellow, style: :bold)
  rescue StandardError => e
    took = Time.now.to_i - time
    puts_time(prefix: "[#{title} failed]") if show_time
    puts_colored("[#{title}] failed after #{took} seconds.", color: :yellow, style: :bold)
    raise e
  end
end