diff --git a/lib/thor/shell/color.rb b/lib/thor/shell/color.rb index 6d8fd409..b76dc853 100644 --- a/lib/thor/shell/color.rb +++ b/lib/thor/shell/color.rb @@ -102,7 +102,7 @@ def set_color(string, *colors) protected def can_display_colors? - are_colors_supported? && !are_colors_disabled? + ENV["FORCE_COLOR"] || (are_colors_supported? && !are_colors_disabled?) end def are_colors_supported? diff --git a/spec/shell/color_spec.rb b/spec/shell/color_spec.rb index 3b40c0b3..70b0bab6 100644 --- a/spec/shell/color_spec.rb +++ b/spec/shell/color_spec.rb @@ -30,6 +30,16 @@ def shell shell.ask "Is this green?", :green, limited_to: %w(Yes No Maybe) end + it "sets the color if FORCE_COLOR is set to a non-empty value, and NO_COLOR is set to a non-empty value" do + allow(ENV).to receive(:[]).with("FORCE_COLOR").and_return("set color") + allow(ENV).to receive(:[]).with("NO_COLOR").and_return("non-empty value") + expect(Thor::LineEditor).to receive(:readline).with("\e[32mIs this green? \e[0m", anything).and_return("yes") + shell.ask "Is this green?", :green + + expect(Thor::LineEditor).to receive(:readline).with("\e[32mIs this green? [Yes, No, Maybe] \e[0m", anything).and_return("Yes") + shell.ask "Is this green?", :green, limited_to: %w(Yes No Maybe) + end + it "sets the color when NO_COLOR is ignored because the environment variable is nil" do allow(ENV).to receive(:[]).with("NO_COLOR").and_return(nil) expect(Thor::LineEditor).to receive(:readline).with("\e[32mIs this green? \e[0m", anything).and_return("yes") @@ -77,6 +87,17 @@ def shell expect(out.chomp).to eq("Wow! Now we have colors!") end + it "sets the color if FORCE_COLOR is a non-empty value, and output is not a tty" do + allow(ENV).to receive(:[]).with("FORCE_COLOR").and_return("set color") + + out = capture(:stdout) do + allow($stdout).to receive(:tty?).and_return(false) + shell.say "Wow! Now we have colors!", :green + end + + expect(out.chomp).to eq("\e[32mWow! Now we have colors!\e[0m") + end + it "does not set the color if NO_COLOR is set to any value that is not an empty string" do allow(ENV).to receive(:[]).with("NO_COLOR").and_return("non-empty string value") out = capture(:stdout) do @@ -188,6 +209,18 @@ def shell expect(colorless).to eq("hi!") end + it "sets color when the FORCE_COLOR environment variable is set to a non-empty value, and NO_COLOR environment variable set to a non-empty string" do + allow(ENV).to receive(:[]).with("FORCE_COLOR").and_return("set color") + allow(ENV).to receive(:[]).with("NO_COLOR").and_return("non-empty value") + allow($stdout).to receive(:tty?).and_return(true) + + red = shell.set_color "hi!", :red + expect(red).to eq("\e[31mhi!\e[0m") + + on_red = shell.set_color "hi!", :white, :on_red + expect(on_red).to eq("\e[37m\e[41mhi!\e[0m") + end + it "sets color when the NO_COLOR environment variable is ignored for being nil" do allow(ENV).to receive(:[]).with("NO_COLOR").and_return(nil) allow($stdout).to receive(:tty?).and_return(true)