Skip to content

Commit

Permalink
Merge pull request #693 from pradyumna2905/escape-html-white-setting-…
Browse files Browse the repository at this point in the history
…color

🌈 Escapes HTML content when setting colors.
  • Loading branch information
rafaelfranca authored Nov 22, 2019
2 parents 630bbee + f1d5822 commit cca51c1
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/thor/shell/html.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,13 @@ class HTML < Basic
def set_color(string, *colors)
if colors.all? { |color| color.is_a?(Symbol) || color.is_a?(String) }
html_colors = colors.map { |color| lookup_color(color) }
"<span style=\"#{html_colors.join('; ')};\">#{string}</span>"
"<span style=\"#{html_colors.join('; ')};\">#{Thor::Util.escape_html(string)}</span>"
else
color, bold = colors
html_color = self.class.const_get(color.to_s.upcase) if color.is_a?(Symbol)
styles = [html_color]
styles << BOLD if bold
"<span style=\"#{styles.join('; ')};\">#{string}</span>"
"<span style=\"#{styles.join('; ')};\">#{Thor::Util.escape_html(string)}</span>"
end
end

Expand Down
16 changes: 16 additions & 0 deletions lib/thor/util.rb
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,22 @@ def ruby_command
def escape_globs(path)
path.to_s.gsub(/[*?{}\[\]]/, '\\\\\\&')
end

# Returns a string that has had any HTML characters escaped.
#
# ==== Examples
#
# Thor::Util.escape_html('<div>') # => "&lt;div&gt;"
#
# ==== Parameters
# String
#
# ==== Returns
# String
#
def escape_html(string)
CGI.escapeHTML(string)
end
end
end
end
10 changes: 10 additions & 0 deletions spec/shell/html_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,14 @@ def shell
shell.say_status :conflict, "README", :red
end
end

describe "#set_color" do
it "escapes HTML content when unsing the default colors" do
expect(shell.set_color("<htmlcontent>", :blue)).to eq "<span style=\"color: blue;\">&lt;htmlcontent&gt;</span>"
end

it "escapes HTML content when not using the default colors" do
expect(shell.set_color("<htmlcontent>", [:nocolor])).to eq "<span style=\";\">&lt;htmlcontent&gt;</span>"
end
end
end

0 comments on commit cca51c1

Please sign in to comment.