Skip to content

Commit 21e6568

Browse files
committed
Respect the use of ENV['NO_COLOR']
Respect the declaration of the of the NO_COLOR environment variable as a sign that color output should be suppressed in he tool. This informal standard is described at https://no-color.org
1 parent 1a2d64d commit 21e6568

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

lib/thor/shell/color.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,11 @@ def set_color(string, *colors)
9797
protected
9898

9999
def can_display_colors?
100-
stdout.tty?
100+
stdout.tty? && !are_colors_disabled?
101+
end
102+
103+
def are_colors_disabled?
104+
!ENV['NO_COLOR'].nil?
101105
end
102106

103107
# Overwrite show_diff to show diff with colors if Diff::LCS is

spec/shell/color_spec.rb

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,15 @@ def shell
1919
shell.ask "Is this green?", :green, :limited_to => %w(Yes No Maybe)
2020
end
2121

22+
it "does not set the color if specified and NO_COLOR is set" do
23+
allow(ENV).to receive(:[]).with("NO_COLOR").and_return("")
24+
expect(Thor::LineEditor).to receive(:readline).with("Is this green? ", anything).and_return("yes")
25+
shell.ask "Is this green?", :green
26+
27+
expect(Thor::LineEditor).to receive(:readline).with("Is this green? [Yes, No, Maybe] ", anything).and_return("Yes")
28+
shell.ask "Is this green?", :green, :limited_to => %w(Yes No Maybe)
29+
end
30+
2231
it "handles an Array of colors" do
2332
expect(Thor::LineEditor).to receive(:readline).with("\e[32m\e[47m\e[1mIs this green on white? \e[0m", anything).and_return("yes")
2433
shell.ask "Is this green on white?", [:green, :on_white, :bold]
@@ -48,6 +57,15 @@ def shell
4857
expect(out.chomp).to eq("Wow! Now we have colors!")
4958
end
5059

60+
it "does not set the color if NO_COLOR is set" do
61+
allow(ENV).to receive(:[]).with("NO_COLOR").and_return("")
62+
out = capture(:stdout) do
63+
shell.say "Wow! Now we have colors!", :green
64+
end
65+
66+
expect(out.chomp).to eq("Wow! Now we have colors!")
67+
end
68+
5169
it "does not use a new line even with colors" do
5270
out = capture(:stdout) do
5371
shell.say "Wow! Now we have colors! ", :green
@@ -118,6 +136,13 @@ def shell
118136
colorless = shell.set_color "hi!", :white
119137
expect(colorless).to eq("hi!")
120138
end
139+
140+
it "does nothing when the terminal has the NO_COLOR environment variable set" do
141+
allow(ENV).to receive(:[]).with("NO_COLOR").and_return("")
142+
allow($stdout).to receive(:tty?).and_return(true)
143+
colorless = shell.set_color "hi!", :white
144+
expect(colorless).to eq("hi!")
145+
end
121146
end
122147

123148
describe "#file_collision" do

0 commit comments

Comments
 (0)