Bug 1294802 - Improve color handling in mozlint stylish formatter, r?jgraham
This will make specifying terminal colours cleaner and provide fallbacks for terminals
with only 8 colours. It also tweaks the 'grey' color to match an update to the eslint
stylish formatter.
MozReview-Commit-ID: KYhC6SEySC3
--- a/python/mozlint/mozlint/formatters/stylish.py
+++ b/python/mozlint/mozlint/formatters/stylish.py
@@ -27,24 +27,41 @@ class NullTerminal(object):
def __getattr__(self, attr):
return self.NullCallableString()
class StylishFormatter(object):
"""Formatter based on the eslint default."""
+ # Colors later on in the list are fallbacks in case the terminal
+ # doesn't support colors earlier in the list.
+ # See http://www.calmar.ws/vim/256-xterm-24bit-rgb-color-chart.html
+ _colors = {
+ 'grey': [247, 8, 7],
+ 'red': [1],
+ 'yellow': [3],
+ 'brightred': [9, 1],
+ 'brightyellow': [11, 3],
+ }
fmt = " {c1}{lineno}{column} {c2}{level}{normal} {message} {c1}{rule}({linter}){normal}"
fmt_summary = "{t.bold}{c}\u2716 {problem} ({error}, {warning}){t.normal}"
def __init__(self, disable_colors=None):
if disable_colors or not blessings:
self.term = NullTerminal()
else:
self.term = blessings.Terminal()
+ self.num_colors = self.term.number_of_colors
+
+ def color(self, color):
+ for num in self._colors[color]:
+ if num < self.num_colors:
+ return self.term.color(num)
+ return ''
def _reset_max(self):
self.max_lineno = 0
self.max_column = 0
self.max_level = 0
self.max_message = 0
def _update_max(self, err):
@@ -76,30 +93,30 @@ class StylishFormatter(object):
if err.level == 'error':
num_errors += 1
else:
num_warnings += 1
for err in errors:
message.append(self.fmt.format(
normal=self.term.normal,
- c1=self.term.color(8),
- c2=self.term.color(1) if err.level == 'error' else self.term.color(3),
+ c1=self.color('grey'),
+ c2=self.color('red') if err.level == 'error' else self.color('yellow'),
lineno=str(err.lineno).rjust(self.max_lineno),
column=(":" + str(err.column).ljust(self.max_column)) if err.column else "",
level=err.level.ljust(self.max_level),
message=err.message.ljust(self.max_message),
rule='{} '.format(err.rule) if err.rule else '',
linter=err.linter.lower(),
))
message.append('') # newline
# Print a summary
message.append(self.fmt_summary.format(
t=self.term,
- c=self.term.color(9) if num_errors else self.term.color(11),
+ c=self.color('brightred') if num_errors else self.color('brightyellow'),
problem=self._pluralize('problem', num_errors + num_warnings),
error=self._pluralize('error', num_errors),
warning=self._pluralize('warning', num_warnings),
))
return '\n'.join(message)