Skip to content

Commit

Permalink
Extract configuration and lookup methods [ci skip]
Browse files Browse the repository at this point in the history
  • Loading branch information
nobu committed Dec 10, 2023
1 parent c4c3908 commit 0096d6a
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions tool/lib/colorize.rb
Expand Up @@ -7,7 +7,7 @@ class Colorize
def initialize(color = nil, opts = ((_, color = color, nil)[0] if Hash === color))
@colors = @reset = nil
@color = opts && opts[:color] || color
if color or (color == nil && STDOUT.tty? && (ENV["NO_COLOR"] || "").empty?)
if color or (color == nil && coloring?)
if (%w[smso so].any? {|attr| /\A\e\[.*m\z/ =~ IO.popen("tput #{attr}", "r", :err => IO::NULL, &:read)} rescue nil)
@beg = "\e["
colors = (colors = ENV['TEST_COLORS']) ? Hash[colors.scan(/(\w+)=([^:\n]*)/)] : {}
Expand All @@ -33,17 +33,24 @@ def initialize(color = nil, opts = ((_, color = color, nil)[0] if Hash === color
"bold"=>"1", "underline"=>"4", "reverse"=>"7",
}

NO_COLOR = (nc = ENV['NO_COLOR']) && !nc.empty?
def coloring?
STDOUT.tty? && (!(nc = ENV['NO_COLOR']) || nc.empty?)
end

# colorize.decorate(str, name = color_name)
def decorate(str, name = @color)
if !NO_COLOR and @colors and color = (@colors[name] || DEFAULTS[name])
if coloring? and color = resolve_color(name)
"#{@beg}#{color}m#{str}#{@reset}"
else
str
end
end

def resolve_color(name = @color, seen = {})
return unless @colors
@colors[name] || DEFAULTS[name]
end

DEFAULTS.each_key do |name|
define_method(name) {|str|
decorate(str, name)
Expand Down

0 comments on commit 0096d6a

Please sign in to comment.