Skip to content

Commit 5ddf60a

Browse files
committed
Adjust colorization behavior to allow forced enabling of color
We want to be able to force colorized output through the presence of the OVERCOMMIT_COLOR variable even if the output stream is not a TTY. While here, I changed the implementation to set an instance variable instead of checking the environment variable each time, as it is more performant and the value of this environment variable won't change during the course of the hook run.
1 parent dc011fd commit 5ddf60a

File tree

2 files changed

+33
-17
lines changed

2 files changed

+33
-17
lines changed

lib/overcommit/logger.rb

+7-5
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@ def self.silent
1111
# @param out [IO]
1212
def initialize(out)
1313
@out = out
14+
@colorize =
15+
if ENV.key?('OVERCOMMIT_COLOR')
16+
!%w[0 false no].include?(ENV['OVERCOMMIT_COLOR'])
17+
else
18+
@out.tty?
19+
end
1420
end
1521

1622
# Write output without a trailing newline.
@@ -78,11 +84,7 @@ def bold_warning(*args)
7884
# @param partial [true,false] whether to omit a newline
7985
def color(code, str, partial = false)
8086
send(partial ? :partial : :log,
81-
colorize? ? "\033[#{code}m#{str}\033[0m" : str)
82-
end
83-
84-
def colorize?
85-
@out.tty? && ENV.fetch('OVERCOMMIT_COLOR', '1') != '0'
87+
@colorize ? "\033[#{code}m#{str}\033[0m" : str)
8688
end
8789
end
8890
end

spec/overcommit/logger_spec.rb

+26-12
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,19 @@
6868
subject
6969
output.should end_with "[0m\n"
7070
end
71+
72+
context 'and colorization is disabled' do
73+
around do |example|
74+
Overcommit::Utils.with_environment 'OVERCOMMIT_COLOR' => '0' do
75+
example.run
76+
end
77+
end
78+
79+
it 'omits the color escape sequence' do
80+
subject
81+
output.should_not include "\033"
82+
end
83+
end
7184
end
7285

7386
context 'when the output stream is not a TTY' do
@@ -79,22 +92,23 @@
7992
subject
8093
output.should_not include "\033"
8194
end
82-
end
8395

84-
context 'when colorization is disabled' do
85-
before do
86-
io.stub(:tty?).and_return(true)
87-
end
96+
context 'and colorization is enabled' do
97+
around do |example|
98+
Overcommit::Utils.with_environment 'OVERCOMMIT_COLOR' => '1' do
99+
example.run
100+
end
101+
end
88102

89-
around do |example|
90-
Overcommit::Utils.with_environment 'OVERCOMMIT_COLOR' => '0' do
91-
example.run
103+
it 'includes the color escape sequence' do
104+
subject
105+
output.should include "\033[#{color_code}m"
92106
end
93-
end
94107

95-
it 'omits the color escape sequence' do
96-
subject
97-
output.should_not include "\033"
108+
it 'ends with the color reset sequence' do
109+
subject
110+
output.should end_with "[0m\n"
111+
end
98112
end
99113
end
100114
end

0 commit comments

Comments
 (0)