Better color support check.

Not all systems have `isatty` attribute on `sys.stdout` so check for
existance of attribute before checking value. Also don't use color in
Windows unless environ indicates support. Apparently, Windows can indicate
support by either the presence of `ANSICON` environ variable or if the
`TERM` environ variable is set to `ANSI`. Fixes #79.

No additional tests added, as the relevant tests use fcntl, which is a
Unix only lib. In fact, the tests won't even run in Windows.
This commit is contained in:
Waylan Limberg 2017-10-26 16:03:14 -04:00 committed by Adrien Vergé
parent d422274563
commit e43768f203

View File

@ -16,9 +16,9 @@
from __future__ import print_function
import os.path
import os
import sys
import platform
import argparse
from yamllint import APP_DESCRIPTION, APP_NAME, APP_VERSION
@ -38,6 +38,15 @@ def find_files_recursively(items):
yield item
def supports_color():
supported_platform = not (platform.system() == 'Windows' and not
('ANSICON' in os.environ or
('TERM' in os.environ and
os.environ['TERM'] == 'ANSI')))
return (supported_platform and
hasattr(sys.stdout, 'isatty') and sys.stdout.isatty())
class Format(object):
@staticmethod
def parsable(problem, filename):
@ -134,7 +143,7 @@ def run(argv=None):
for problem in linter.run(f, conf, filepath):
if args.format == 'parsable':
print(Format.parsable(problem, file))
elif sys.stdout.isatty():
elif supports_color():
if first:
print('\033[4m%s\033[0m' % file)
first = False