Skip to content

Commit fa2f208

Browse files
committed
Extract strip_color_codes into Utils module
This helper seems generic enough that it will probably become useful in future.
1 parent c3631c9 commit fa2f208

File tree

3 files changed

+33
-7
lines changed

3 files changed

+33
-7
lines changed

lib/overcommit/hook/pre_commit/html_hint.rb

+1-7
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ module Overcommit::Hook::PreCommit
55
class HtmlHint < Base
66
def run
77
result = execute(command + applicable_files)
8-
output = strip_color_codes(result.stdout.chomp)
8+
output = Overcommit::Utils.strip_color_codes(result.stdout.chomp)
99

1010
message_groups = output.split("\n\n")[0..-2]
1111
message_groups.map do |group|
@@ -17,11 +17,5 @@ def run
1717
)
1818
end.flatten
1919
end
20-
21-
private
22-
23-
def strip_color_codes(output)
24-
output.gsub(/\e\[(\d+)(;\d+)*m/, '')
25-
end
2620
end
2721
end

lib/overcommit/utils.rb

+10
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,16 @@ def git_dir(repo_dir = repo_root)
7272
end
7373
end
7474

75+
# Remove ANSI escape sequences from a string.
76+
#
77+
# This is useful for stripping colorized output from external tools.
78+
#
79+
# @param text [String]
80+
# @return [String]
81+
def strip_color_codes(text)
82+
text.gsub(/\e\[(\d+)(;\d+)*m/, '')
83+
end
84+
7585
# Shamelessly stolen from:
7686
# stackoverflow.com/questions/1509915/converting-camel-case-to-underscore-case-in-ruby
7787
def snake_case(str)

spec/overcommit/utils_spec.rb

+22
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,28 @@
7777
end
7878
end
7979

80+
describe '.strip_color_codes' do
81+
subject { described_class.strip_color_codes(text) }
82+
83+
context 'with an empty string' do
84+
let(:text) { '' }
85+
86+
it { should == '' }
87+
end
88+
89+
context 'with a string with no escape sequences' do
90+
let(:text) { 'A normal string' }
91+
92+
it { should == text }
93+
end
94+
95+
context 'with a string with escape sequences' do
96+
let(:text) { "A \e[31mcolored string\e[39m" }
97+
98+
it { should == 'A colored string' }
99+
end
100+
end
101+
80102
describe '.snake_case' do
81103
it 'converts camel case to underscores' do
82104
described_class.snake_case('HelloWorld').should == 'hello_world'

0 commit comments

Comments
 (0)