qutebrowser/scripts/run_checks.py

284 lines
8.5 KiB
Python
Raw Normal View History

2014-07-31 21:14:05 +02:00
#!/usr/bin/python3
2014-06-19 09:04:37 +02:00
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
2014-02-06 14:01:23 +01:00
# Copyright 2014 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
2014-05-15 08:24:10 +02:00
# pylint: disable=broad-except
2014-04-17 17:44:27 +02:00
""" Run different codecheckers over a codebase.
Runs flake8, pylint, pep257, a CRLF/whitespace/conflict-checker and
pyroma/check-manifest by default.
2014-04-17 17:44:27 +02:00
Module attributes:
status: An OrderedDict for return status values.
option: A dictionary with options.
"""
2014-01-28 15:25:40 +01:00
import sys
import subprocess
2014-01-28 22:44:39 +01:00
import os
import os.path
2014-05-06 14:37:47 +02:00
import unittest
2014-05-06 19:00:35 +02:00
import logging
from collections import OrderedDict
2014-01-28 15:25:40 +01:00
2014-02-10 11:07:21 +01:00
try:
import pep257
except ImportError:
do_check_257 = False
else:
do_check_257 = True
2014-01-29 04:07:27 +01:00
from pkg_resources import load_entry_point, DistributionNotFound
2014-05-06 19:00:35 +02:00
# We need to do this because pyroma is braindead enough to use logging instead
# of print...
logging.basicConfig(level=logging.INFO, format='%(msg)s')
status = OrderedDict()
2014-02-07 10:58:53 +01:00
options = {
2014-05-15 07:29:12 +02:00
'targets': ['qutebrowser', 'scripts'],
2014-02-07 10:58:53 +01:00
'disable': {
2014-02-07 19:44:56 +01:00
'pep257': [
2014-02-10 11:07:21 +01:00
'D102', # Docstring missing, will be handled by others
'D209', # Blank line before closing """ (removed from PEP257)
2014-04-17 15:31:30 +02:00
'D402', # First line should not be function's signature
# (false-positives)
2014-02-07 19:44:56 +01:00
],
2014-02-07 10:58:53 +01:00
},
2014-05-15 08:11:00 +02:00
'exclude': [],
'exclude_pep257': ['test_*', 'ez_setup'],
2014-02-07 10:58:53 +01:00
'other': {
2014-04-16 11:05:58 +02:00
'pylint': ['--output-format=colorized', '--reports=no',
2014-08-06 14:42:05 +02:00
'--rcfile=.pylintrc',
2014-08-06 21:56:10 +02:00
'--load-plugins=pylint_checkers.config,'
'pylint_checkers.crlf,'
'pylint_checkers.modeline,'
'pylint_checkers.settrace'],
2014-05-20 17:53:32 +02:00
'flake8': ['--config=.flake8'],
2014-02-07 10:58:53 +01:00
},
}
2014-01-28 15:25:40 +01:00
if os.name == 'nt':
# pep257 uses cp1252 by default on Windows, which can't handle the unicode
2014-07-07 12:00:51 +02:00
# chars in some files.
options['exclude_pep257'] += ['configdata.py', 'misc.py']
2014-02-10 11:07:21 +01:00
2014-05-15 08:24:10 +02:00
def run(name, target=None, args=None):
2014-04-17 17:44:27 +02:00
"""Run a checker via distutils with optional args.
2014-01-29 04:07:27 +01:00
2014-04-17 17:44:27 +02:00
Arguments:
name: Name of the checker/binary
2014-05-15 07:29:12 +02:00
target: The package to check
2014-04-17 17:44:27 +02:00
args: Option list of arguments to pass
2014-01-29 04:07:27 +01:00
"""
2014-08-06 14:44:00 +02:00
# pylint: disable=too-many-branches
2014-08-06 14:42:05 +02:00
if name == 'pylint':
scriptdir = os.path.abspath(os.path.dirname(__file__))
if 'PYTHONPATH' in os.environ:
old_pythonpath = os.environ['PYTHONPATH']
os.environ['PYTHONPATH'] += os.pathsep + scriptdir
else:
old_pythonpath = None
os.environ['PYTHONPATH'] = scriptdir
2014-05-06 19:00:35 +02:00
sys.argv = [name]
if target is None:
status_key = name
else:
status_key = '{}_{}'.format(name, target)
2014-05-15 07:29:12 +02:00
args.append(target)
2014-01-28 15:25:40 +01:00
if args is not None:
sys.argv += args
2014-05-15 07:29:12 +02:00
print("------ {} ------".format(name))
2014-01-28 15:25:40 +01:00
try:
2014-05-06 19:00:35 +02:00
ep = load_entry_point(name, 'console_scripts', name)
ep()
2014-01-28 15:25:40 +01:00
except SystemExit as e:
2014-05-15 07:29:12 +02:00
status[status_key] = e
except DistributionNotFound:
if args is None:
args = []
try:
2014-05-15 07:29:12 +02:00
status[status_key] = subprocess.call([name] + args)
except FileNotFoundError as e:
print('{}: {}'.format(e.__class__.__name__, e))
2014-05-15 07:29:12 +02:00
status[status_key] = None
2014-01-28 15:25:40 +01:00
except Exception as e:
2014-01-28 15:50:11 +01:00
print('{}: {}'.format(e.__class__.__name__, e))
2014-05-15 07:29:12 +02:00
status[status_key] = None
2014-08-06 14:42:05 +02:00
if name == 'pylint':
if old_pythonpath is not None:
os.environ['PYTHONPATH'] = old_pythonpath
else:
del os.environ['PYTHONPATH']
2014-01-28 15:25:40 +01:00
print()
2014-02-10 11:07:21 +01:00
2014-05-15 07:29:12 +02:00
def check_pep257(target, args=None):
2014-04-17 17:44:27 +02:00
"""Run pep257 checker with args passed."""
2014-05-15 07:29:12 +02:00
sys.argv = ['pep257', target]
2014-02-07 19:44:56 +01:00
if args is not None:
sys.argv += args
2014-05-15 07:29:12 +02:00
print("------ pep257 ------")
2014-02-07 19:44:56 +01:00
try:
2014-05-15 07:29:12 +02:00
status['pep257_' + target] = pep257.main(*pep257.parse_options())
2014-02-07 19:44:56 +01:00
except Exception as e:
print('{}: {}'.format(e.__class__.__name__, e))
2014-05-15 07:29:12 +02:00
status['pep257_' + target] = None
2014-02-07 19:44:56 +01:00
print()
2014-02-10 11:07:21 +01:00
2014-05-06 14:37:47 +02:00
def check_unittest():
2014-05-15 08:24:10 +02:00
"""Run the unittest checker."""
2014-05-15 07:29:12 +02:00
print("==================== unittest ====================")
2014-05-06 14:37:47 +02:00
suite = unittest.TestLoader().discover('.')
result = unittest.TextTestRunner().run(suite)
print()
status['unittest'] = result.wasSuccessful()
2014-05-15 08:24:10 +02:00
2014-05-22 15:19:35 +02:00
def check_git():
"""Check for uncommited git files.."""
print("==================== git ====================")
if not os.path.isdir(".git"):
print("No .git dir, ignoring")
status['git'] = False
print()
return
untracked = []
gitst = subprocess.check_output(['git', 'status', '--porcelain'])
gitst = gitst.decode('UTF-8').strip()
for line in gitst.splitlines():
s, name = line.split(maxsplit=1)
2014-05-22 15:19:35 +02:00
if s == '??':
untracked.append(name)
if untracked:
status['git'] = False
print("Untracked files:")
print('\n'.join(untracked))
else:
status['git'] = True
print()
def check_vcs_conflict(target):
"""Check VCS conflict markers."""
print("------ VCS conflict markers ------")
2014-01-28 22:44:39 +01:00
try:
ok = True
2014-05-15 08:24:10 +02:00
for (dirpath, _dirnames, filenames) in os.walk(target):
for name in (e for e in filenames if e.endswith('.py')):
2014-01-28 22:44:39 +01:00
fn = os.path.join(dirpath, name)
with open(fn, 'r') as f:
for line in f:
if any(line.startswith(c * 7) for c in '<>=|'):
print("Found conflict marker in {}".format(fn))
ok = False
status['vcs_' + target] = ok
2014-01-28 22:44:39 +01:00
except Exception as e:
print('{}: {}'.format(e.__class__.__name__, e))
status['vcs_' + target] = None
2014-01-28 22:44:39 +01:00
print()
2014-02-10 11:07:21 +01:00
2014-02-07 19:39:55 +01:00
def _get_args(checker):
2014-04-17 17:44:27 +02:00
"""Construct the arguments for a given checker.
Return:
A list of commandline arguments.
"""
2014-05-15 08:24:10 +02:00
# pylint: disable=too-many-branches
2014-02-07 19:39:55 +01:00
args = []
if checker == 'pylint':
try:
args += ['--disable=' + ','.join(options['disable']['pylint'])]
2014-04-16 11:05:58 +02:00
except KeyError:
pass
2014-05-15 08:11:00 +02:00
if options['exclude']:
try:
args += ['--ignore=' + ','.join(options['exclude'])]
except KeyError:
pass
2014-04-16 11:05:58 +02:00
try:
2014-02-07 19:39:55 +01:00
args += options['other']['pylint']
except KeyError:
pass
elif checker == 'flake8':
try:
args += ['--ignore=' + ','.join(options['disable']['flake8'])]
2014-04-16 11:05:58 +02:00
except KeyError:
pass
2014-05-15 08:11:00 +02:00
if options['exclude']:
try:
args += ['--exclude=' + ','.join(options['exclude'])]
except KeyError:
pass
2014-04-16 11:05:58 +02:00
try:
2014-02-07 19:39:55 +01:00
args += options['other']['flake8']
except KeyError:
pass
2014-02-07 19:44:56 +01:00
elif checker == 'pep257':
args = []
try:
args += ['--ignore=' + ','.join(options['disable']['pep257'])]
2014-04-16 11:05:58 +02:00
except KeyError:
pass
try:
2014-05-15 08:24:10 +02:00
args += [r'--match=(?!{}).*\.py'.format('|'.join(
options['exclude'] + options['exclude_pep257']))]
2014-04-16 11:05:58 +02:00
except KeyError:
pass
try:
2014-02-07 19:44:56 +01:00
args += options['other']['pep257']
except KeyError:
pass
2014-04-29 08:34:49 +02:00
elif checker == 'pyroma':
args = ['.']
elif checker == 'check-manifest':
args = []
2014-02-07 19:39:55 +01:00
return args
2014-02-07 10:58:53 +01:00
2014-05-15 07:29:12 +02:00
argv = sys.argv[:]
2014-05-06 14:37:47 +02:00
check_unittest()
2014-05-22 15:19:35 +02:00
check_git()
2014-05-15 08:24:10 +02:00
for trg in options['targets']:
print("==================== {} ====================".format(trg))
2014-05-15 07:29:12 +02:00
if do_check_257:
2014-05-15 08:24:10 +02:00
check_pep257(trg, _get_args('pep257'))
for chk in ('pylint', 'flake8'):
2014-05-15 07:29:12 +02:00
# FIXME what the hell is the flake8 exit status?
2014-05-15 08:24:10 +02:00
run(chk, trg, _get_args(chk))
check_vcs_conflict(trg)
2014-01-28 15:25:40 +01:00
if '--setup' in argv:
print("==================== Setup checks ====================")
for chk in ('pyroma', 'check-manifest'):
run(chk, args=_get_args(chk))
2014-04-25 16:53:23 +02:00
print("Exit status values:")
2014-01-28 15:25:40 +01:00
for (k, v) in status.items():
print(' {} - {}'.format(k, v))
2014-01-30 20:49:08 +01:00
if all(val in (True, 0) for val in status):
2014-01-30 20:49:08 +01:00
sys.exit(0)
else:
sys.exit(1)