2017-06-15 05:39:06 +03:00
|
|
|
# frozen-string-literal: true
|
|
|
|
|
2017-04-21 06:01:12 +03:00
|
|
|
class Colorize
|
2020-08-11 10:17:51 +03:00
|
|
|
# call-seq:
|
|
|
|
# Colorize.new(colorize = nil)
|
|
|
|
# Colorize.new(color: color, colors_file: colors_file)
|
2019-06-04 12:10:09 +03:00
|
|
|
def initialize(color = nil, opts = ((_, color = color, nil)[0] if Hash === color))
|
2017-04-21 06:01:12 +03:00
|
|
|
@colors = @reset = nil
|
2022-12-12 07:17:56 +03:00
|
|
|
@color = opts && opts[:color] || color
|
2022-11-01 04:56:28 +03:00
|
|
|
if color or (color == nil && STDOUT.tty? && (ENV["NO_COLOR"] || "").empty?)
|
2021-07-06 13:06:49 +03:00
|
|
|
if (%w[smso so].any? {|attr| /\A\e\[.*m\z/ =~ IO.popen("tput #{attr}", "r", :err => IO::NULL, &:read)} rescue nil)
|
2017-04-21 06:01:12 +03:00
|
|
|
@beg = "\e["
|
2019-06-04 11:23:57 +03:00
|
|
|
colors = (colors = ENV['TEST_COLORS']) ? Hash[colors.scan(/(\w+)=([^:\n]*)/)] : {}
|
2019-06-04 12:10:09 +03:00
|
|
|
if opts and colors_file = opts[:colors_file]
|
2019-06-04 12:08:21 +03:00
|
|
|
begin
|
|
|
|
File.read(colors_file).scan(/(\w+)=([^:\n]*)/) do |n, c|
|
|
|
|
colors[n] ||= c
|
|
|
|
end
|
|
|
|
rescue Errno::ENOENT
|
2019-06-04 11:06:12 +03:00
|
|
|
end
|
|
|
|
end
|
2019-06-04 11:23:57 +03:00
|
|
|
@colors = colors
|
2017-04-21 06:01:12 +03:00
|
|
|
@reset = "#{@beg}m"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
self
|
|
|
|
end
|
|
|
|
|
2017-06-15 05:39:06 +03:00
|
|
|
DEFAULTS = {
|
2017-10-14 05:17:07 +03:00
|
|
|
"pass"=>"32", "fail"=>"31;1", "skip"=>"33;1",
|
2017-06-15 05:39:06 +03:00
|
|
|
"black"=>"30", "red"=>"31", "green"=>"32", "yellow"=>"33",
|
|
|
|
"blue"=>"34", "magenta"=>"35", "cyan"=>"36", "white"=>"37",
|
2019-08-03 08:56:07 +03:00
|
|
|
"bold"=>"1", "underline"=>"4", "reverse"=>"7",
|
2017-06-15 05:39:06 +03:00
|
|
|
}
|
2017-04-21 06:01:12 +03:00
|
|
|
|
2022-12-26 15:57:27 +03:00
|
|
|
NO_COLOR = (nc = ENV['NO_COLOR']) && !nc.empty?
|
|
|
|
|
2020-08-11 10:17:51 +03:00
|
|
|
# colorize.decorate(str, name = color_name)
|
|
|
|
def decorate(str, name = @color)
|
2022-12-26 15:57:27 +03:00
|
|
|
if !NO_COLOR and @colors and color = (@colors[name] || DEFAULTS[name])
|
2017-04-21 06:01:12 +03:00
|
|
|
"#{@beg}#{color}m#{str}#{@reset}"
|
|
|
|
else
|
|
|
|
str
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2017-06-15 05:39:06 +03:00
|
|
|
DEFAULTS.each_key do |name|
|
|
|
|
define_method(name) {|str|
|
|
|
|
decorate(str, name)
|
|
|
|
}
|
2017-04-21 06:01:12 +03:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
if $0 == __FILE__
|
2020-08-11 10:17:51 +03:00
|
|
|
colorize = Colorize.new(ARGV.shift)
|
|
|
|
ARGV.each {|str| puts colorize.decorate(str)}
|
2017-04-21 06:01:12 +03:00
|
|
|
end
|