adding new stuff

This commit is contained in:
ViktorBarzin 2017-07-09 00:22:01 +03:00
parent f84d7183aa
commit 9ef8a96f9a
1580 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,19 @@
"""Custom module loader."""
class Linter(object):
"""Abstract class for linter plugin."""
@staticmethod
def allow(path):
"""Check path is relevant for linter.
:return bool:
"""
return path.endswith('.py')
@staticmethod
def run(path, **meta):
"""Method 'run' should be defined."""
raise NotImplementedError(__doc__)

View file

@ -0,0 +1,39 @@
"""Load extensions."""
LINTERS = {}
try:
from pylama.lint.pylama_mccabe import Linter
LINTERS['mccabe'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pep257 import Linter
LINTERS['pep257'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pep8 import Linter
LINTERS['pep8'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pyflakes import Linter
LINTERS['pyflakes'] = Linter()
except ImportError:
pass
from pkg_resources import iter_entry_points
for entry in iter_entry_points('pylama.linter'):
if entry.name not in LINTERS:
try:
LINTERS[entry.name] = entry.load()()
except ImportError:
pass
# pylama:ignore=E0611

View file

@ -0,0 +1,29 @@
"""Code complexity checking."""
from mccabe import McCabeChecker
from pylama.lint import Linter as Abstract
import ast
class Linter(Abstract):
"""Run complexity checking."""
@staticmethod
def run(path, code=None, params=None, **meta):
"""MCCabe code checking.
:return list: List of errors.
"""
try:
tree = compile(code, path, "exec", ast.PyCF_ONLY_AST)
except SyntaxError as exc:
return [{'lnum': exc.lineno, 'text': 'Invalid syntax: %s' % exc.text.strip()}]
McCabeChecker.max_complexity = int(params.get('complexity', 10))
return [
{'lnum': lineno, 'offset': offset, 'text': text, 'type': McCabeChecker._code}
for lineno, offset, text, _ in McCabeChecker(tree, path).run()
]
# pylama:ignore=W0212

View file

@ -0,0 +1,21 @@
"""PEP257 support."""
from pep257 import PEP257Checker
from pylama.lint import Linter as Abstract
class Linter(Abstract):
"""Check PEP257 errors."""
@staticmethod
def run(path, code=None, **meta):
"""PEP257 code checking.
:return list: List of errors.
"""
return [
{'lnum': e.line, 'text': e.message, 'type': 'D'}
for e in PEP257Checker().check_source(code, path)
]

View file

@ -0,0 +1,66 @@
"""PEP8 support."""
from pep8 import BaseReport, StyleGuide, get_parser
from pylama.lint import Linter as Abstract
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
class Linter(Abstract):
"""PEP8 runner."""
@staticmethod
def run(path, code=None, params=None, **meta):
"""Check code with PEP8.
:return list: List of errors.
"""
parser = get_parser()
for option in parser.option_list:
if option.dest and option.dest in params:
value = params[option.dest]
if not isinstance(value, str):
continue
params[option.dest] = option.convert_value(option, params[option.dest])
P8Style = StyleGuide(reporter=_PEP8Report, **params)
buf = StringIO(code)
return P8Style.input_file(path, lines=buf.readlines())
class _PEP8Report(BaseReport):
def __init__(self, *args, **kwargs):
super(_PEP8Report, self).__init__(*args, **kwargs)
self.errors = []
def init_file(self, filename, lines, expected, line_offset):
"""Prepare storage for errors."""
super(_PEP8Report, self).init_file(
filename, lines, expected, line_offset)
self.errors = []
def error(self, line_number, offset, text, check):
"""Save errors."""
code = super(_PEP8Report, self).error(
line_number, offset, text, check)
if code:
self.errors.append(dict(
text=text,
type=code.replace('E', 'C'),
col=offset + 1,
lnum=line_number,
))
def get_file_results(self):
"""Get errors.
:return list: List of errors.
"""
return self.errors

View file

@ -0,0 +1,49 @@
"""Pyflakes support."""
from pyflakes import checker
from pylama.lint import Linter as Abstract
checker.messages.UnusedImport.message = "W0611 %r imported but unused"
checker.messages.RedefinedWhileUnused.message = "W0404 redefinition of unused %r from line %r"
checker.messages.RedefinedInListComp.message = "W0621 list comprehension redefines %r from line %r"
checker.messages.ImportShadowedByLoopVar.message = "W0621 import %r from line %r shadowed by loop variable"
checker.messages.ImportStarUsed.message = "W0401 'from %s import *' used; unable to detect undefined names"
checker.messages.UndefinedName.message = "E0602 undefined name %r"
checker.messages.DoctestSyntaxError.message = "W0511 syntax error in doctest"
checker.messages.UndefinedExport.message = "E0603 undefined name %r in __all__"
checker.messages.UndefinedLocal.message = "E0602 local variable %r (defined in enclosing scope on line %r) referenced before assignment"
checker.messages.DuplicateArgument.message = "E1122 duplicate argument %r in function definition"
checker.messages.LateFutureImport.message = "W0410 future import(s) %r after other statements"
checker.messages.UnusedVariable.message = "W0612 local variable %r is assigned to but never used"
checker.messages.ReturnWithArgsInsideGenerator.message = "E0106 'return' with argument inside generator"
checker.messages.ReturnOutsideFunction.message = "E0104 'return' outside function"
class Linter(Abstract):
"""Pyflakes runner."""
@staticmethod
def run(path, code=None, params=None, **meta):
"""Check code with pyflakes.
:return list: List of errors.
"""
import _ast
builtins = params.get("builtins", "")
if builtins:
builtins = builtins.split(",")
tree = compile(code, path, "exec", _ast.PyCF_ONLY_AST)
w = checker.Checker(tree, path, builtins=builtins)
w.messages = sorted(w.messages, key=lambda m: m.lineno)
return [
{'lnum': m.lineno, 'text': m.message % m.message_args}
for m in sorted(w.messages, key=lambda m: m.lineno)
]
# pylama:ignore=E501,C0301

View file

@ -0,0 +1,12 @@
""" Description. """
# Module information
# ==================
__version__ = "2.1.1"
__project__ = "pylama_pylint"
__author__ = "horneds <horneds@gmail.com>"
__license__ = "BSD"
from .main import Linter # noqa

View file

@ -0,0 +1,111 @@
""" Pylint support. """
from os import path as op, environ
import logging
from pylama.lint import Linter as BaseLinter
CURDIR = op.abspath(op.dirname(__file__))
from astroid import MANAGER
from pylint.lint import Run
from pylint.reporters import BaseReporter
HOME_RCFILE = op.abspath(op.join(environ.get('HOME', ''), '.pylintrc'))
LAMA_RCFILE = op.abspath(op.join(CURDIR, 'pylint.rc'))
logger = logging.getLogger('pylama')
class Linter(BaseLinter):
""" Check code with pylint. """
@staticmethod
def run(path, code, params=None, ignore=None, select=None, **meta):
""" Pylint code checking.
:return list: List of errors.
"""
logger.debug('Start pylint')
MANAGER.astroid_cache.clear()
class Reporter(BaseReporter):
def __init__(self):
self.errors = []
super(Reporter, self).__init__()
def _display(self, layout):
pass
def add_message(self, msg_id, location, msg):
_, _, line, col = location[1:]
self.errors.append(dict(
lnum=line,
col=col,
text="%s %s" % (msg_id, msg),
type=msg_id[0]
))
params = _Params(ignore=ignore, select=select, params=params)
logger.debug(params)
runner = Run(
[path] + params.to_attrs(), reporter=Reporter(), exit=False)
return runner.linter.reporter.errors
class _Params(object):
""" Store pylint params. """
def __init__(self, select=None, ignore=None, params=None):
params = dict(params.items())
rcfile = params.get('rcfile', LAMA_RCFILE)
enable = params.get('enable', None)
disable = params.get('disable', None)
if op.exists(HOME_RCFILE):
rcfile = HOME_RCFILE
if select:
enable = select | set(enable.split(",") if enable else [])
if ignore:
disable = ignore | set(disable.split(",") if disable else [])
params.update(dict(
report=params.get('report', False), rcfile=rcfile,
enable=enable, disable=disable))
self.params = dict(
(name.replace('_', '-'), self.prepare_value(value))
for name, value in params.items() if value is not None)
@staticmethod
def prepare_value(value):
""" Prepare value to pylint. """
if isinstance(value, (list, tuple, set)):
return ",".join(value)
if isinstance(value, bool):
return "y" if value else "n"
return str(value)
def to_attrs(self):
""" Convert to argument list. """
return ["--%s=%s" % item for item in self.params.items()]
def __str__(self):
return " ".join(self.to_attrs())
def __repr__(self):
return "<Pylint %s>" % self
# pylama:ignore=W0403

View file

@ -0,0 +1,23 @@
[MESSAGES CONTROL]
# Disable the message(s) with the given id(s).
# http://pylint-messages.wikidot.com/all-codes
#
# C0103: Invalid name "%s" (should match %s)
# E1101: %s %r has no %r member
# R0901: Too many ancestors (%s/%s)
# R0902: Too many instance attributes (%s/%s)
# R0903: Too few public methods (%s/%s)
# R0904: Too many public methods (%s/%s)
# R0913: Too many arguments (%s/%s)
# R0915: Too many statements (%s/%s)
# W0141: Used builtin function %r
# W0142: Used * or ** magic
# W0221: Arguments number differs from %s method
# W0232: Class has no __init__ method
# W0613: Unused argument %r
# W0631: Using possibly undefined loop variable %r
#
disable = C0103,E1101,R0901,R0902,R0903,R0904,R0913,R0915,W0141,W0142,W0221,W0232,W0613,W0631
[TYPECHECK]
generated-members = REQUEST,acl_users,aq_parent,objects,DoesNotExist,_meta,status_code,content,context