Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🌈 Escapes HTML content when setting colors. #693

Merged
merged 2 commits into from
Nov 22, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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