Skip to content
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

Shell escaping escapes #4

Open
wants to merge 1 commit 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
24 changes: 22 additions & 2 deletions lib/term/ansicolor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,21 +53,41 @@ def self.coloring=(val)
end
self.coloring = true

# Returns true, if the shell escaping function of this module is switched on.
def self.escaped?
@escaped
end

# Turns shell escaping on or off globally
def self.escaped=(val)
@escaped = val
end
self.escaped = false


ATTRIBUTES.each do |c, v|
eval %Q{
def #{c}(string = nil)
result = ''
result << "\e[#{v}m" if Term::ANSIColor.coloring?
if Term::ANSIColor.coloring?
result << '\\[' if Term::ANSIColor.escaped?
result << "\e[#{v}m"
result << '\\]' if Term::ANSIColor.escaped?
end
if block_given?
result << yield
elsif string
result << string
elsif respond_to?(:to_str)
result << to_str
else
result << '\\]' if Term::ANSIColor.escaped?
return result #only switch on
end
result << "\e[0m" if Term::ANSIColor.coloring?
if Term::ANSIColor.coloring?
result << "\e[0m"
result << '\\]' if Term::ANSIColor.escaped?
end
result
end
}
Expand Down
11 changes: 10 additions & 1 deletion tests/ansicolor_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ def setup
@string = "red"
@string_red = "\e[31mred\e[0m"
@string_red_on_green = "\e[42m\e[31mred\e[0m\e[0m"
@string_red_escaped = "\\[\e[31m\\]red\e[0m\\]"
end

attr_reader :string, :string_red, :string_red_on_green
attr_reader :string, :string_red, :string_red_on_green, :string_red_escaped

def test_red
assert_equal string_red, string.red
Expand All @@ -30,6 +31,7 @@ def test_red
assert_equal string_red, red { string }
end


def test_red_on_green
assert_equal string_red_on_green, string.red.on_green
assert_equal string_red_on_green, Color.on_green(Color.red(string))
Expand Down Expand Up @@ -63,4 +65,11 @@ def test_attributes
assert_equal foo, uncolored { foo }
end
end

def test_red_escaped
Term::ANSIColor.escaped = true
assert_equal string_red_escaped, "red".red
Term::ANSIColor.escaped = false
end

end