Skip to content

TTY detection #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion lib/colored.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ module Colored
'underline' => 4,
'reversed' => 7
}

@@enforced_colors = nil

COLORS.each do |color, value|
define_method(color) do
Expand Down Expand Up @@ -76,15 +78,26 @@ 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()
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

Expand Down
8 changes: 8 additions & 0 deletions test/colored_test.rb
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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