Skip to content

Commit cca51c1

Browse files
authored
Merge pull request #693 from pradyumna2905/escape-html-white-setting-color
🌈 Escapes HTML content when setting colors.
2 parents 630bbee + f1d5822 commit cca51c1

File tree

3 files changed

+28
-2
lines changed

3 files changed

+28
-2
lines changed

lib/thor/shell/html.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,13 @@ class HTML < Basic
5151
def set_color(string, *colors)
5252
if colors.all? { |color| color.is_a?(Symbol) || color.is_a?(String) }
5353
html_colors = colors.map { |color| lookup_color(color) }
54-
"<span style=\"#{html_colors.join('; ')};\">#{string}</span>"
54+
"<span style=\"#{html_colors.join('; ')};\">#{Thor::Util.escape_html(string)}</span>"
5555
else
5656
color, bold = colors
5757
html_color = self.class.const_get(color.to_s.upcase) if color.is_a?(Symbol)
5858
styles = [html_color]
5959
styles << BOLD if bold
60-
"<span style=\"#{styles.join('; ')};\">#{string}</span>"
60+
"<span style=\"#{styles.join('; ')};\">#{Thor::Util.escape_html(string)}</span>"
6161
end
6262
end
6363

lib/thor/util.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,22 @@ def ruby_command
263263
def escape_globs(path)
264264
path.to_s.gsub(/[*?{}\[\]]/, '\\\\\\&')
265265
end
266+
267+
# Returns a string that has had any HTML characters escaped.
268+
#
269+
# ==== Examples
270+
#
271+
# Thor::Util.escape_html('<div>') # => "&lt;div&gt;"
272+
#
273+
# ==== Parameters
274+
# String
275+
#
276+
# ==== Returns
277+
# String
278+
#
279+
def escape_html(string)
280+
CGI.escapeHTML(string)
281+
end
266282
end
267283
end
268284
end

spec/shell/html_spec.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,14 @@ def shell
2828
shell.say_status :conflict, "README", :red
2929
end
3030
end
31+
32+
describe "#set_color" do
33+
it "escapes HTML content when unsing the default colors" do
34+
expect(shell.set_color("<htmlcontent>", :blue)).to eq "<span style=\"color: blue;\">&lt;htmlcontent&gt;</span>"
35+
end
36+
37+
it "escapes HTML content when not using the default colors" do
38+
expect(shell.set_color("<htmlcontent>", [:nocolor])).to eq "<span style=\";\">&lt;htmlcontent&gt;</span>"
39+
end
40+
end
3141
end

0 commit comments

Comments
 (0)