From f3ef60fa68f028ff844197cb4f0fbc9a194a53f4 Mon Sep 17 00:00:00 2001 From: kpcyrd Date: Mon, 30 Jun 2014 19:39:34 +0200 Subject: [PATCH 1/3] Don't use colors unless writing onto tty --- lib/colored.rb | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/colored.rb b/lib/colored.rb index c107d73..9e636a5 100644 --- a/lib/colored.rb +++ b/lib/colored.rb @@ -76,15 +76,21 @@ def colors end def extra(extra_name) + return "" unless is_tty extra_name = extra_name.to_s "\e[#{EXTRAS[extra_name]}m" if EXTRAS[extra_name] end def color(color_name) + return unless is_tty background = color_name.to_s =~ /on_/ color_name = color_name.to_s.sub('on_', '') return unless color_name && COLORS[color_name] - "\e[#{COLORS[color_name] + (background ? 10 : 0)}m" + "\e[#{COLORS[color_name] + (background ? 10 : 0)}m" + end + + def is_tty() + $stdout.tty? end end unless Object.const_defined? :Colored From f3893bf155b09c9d4804ae9025f41e758e1bcbba Mon Sep 17 00:00:00 2001 From: kpcyrd Date: Mon, 30 Jun 2014 19:45:05 +0200 Subject: [PATCH 2/3] Allow enforcement of colors/no colors --- lib/colored.rb | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/colored.rb b/lib/colored.rb index 9e636a5..eb1ca16 100644 --- a/lib/colored.rb +++ b/lib/colored.rb @@ -32,6 +32,8 @@ module Colored 'underline' => 4, 'reversed' => 7 } + + @@enforced_colors = nil COLORS.each do |color, value| define_method(color) do @@ -90,7 +92,12 @@ def color(color_name) end def is_tty() - $stdout.tty? + return $stdout.tty? unless not @@enforced_colors.nil? + @@enforced_colors + end + + def enforce_colors(x) + @@enforced_colors = x end end unless Object.const_defined? :Colored From 1e9fcd7aae15789b98d6d771588a0ee5c6aed75f Mon Sep 17 00:00:00 2001 From: kpcyrd Date: Mon, 30 Jun 2014 19:23:08 +0200 Subject: [PATCH 3/3] Disable tty check during tests --- test/colored_test.rb | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/test/colored_test.rb b/test/colored_test.rb index 3b77990..59b1b7d 100644 --- a/test/colored_test.rb +++ b/test/colored_test.rb @@ -1,6 +1,8 @@ require 'test/unit' require File.dirname(__FILE__) + '/../lib/colored' +Colored.enforce_colors(true) + class TestColor < Test::Unit::TestCase def test_one_color assert_equal "\e[31mred\e[0m", "red".red @@ -41,4 +43,10 @@ def test_eol_with_with_two_colors def test_eol_with_modifiers_stack_with_colors assert_equal "\e[36m\e[4m\e[1m\e[2Kcyan underlined bold\e[0m\e[0m\e[0m", "cyan underlined bold".bold.underline.cyan.to_eol end + + def test_colors_on_tty_only + Colored.enforce_colors(false) + assert_equal "red", "red".red + Colored.enforce_colors(true) + end end