Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def from_msg(cls, msg):
return cls(
msg.symbol, msg.line, msg.obj or '', msg.msg.replace("\r\n", "\n"),
msg.confidence.name
if msg.confidence != interfaces.UNDEFINED else interfaces.HIGH.name)
This is the main checker controlling the other ones and the reports
generation. It is itself both a raw checker and an astroid checker in order
to:
* handle message activation / deactivation at the module level
* handle some basic but necessary stats'data (number of classes, methods...)
IDE plugin developers: you may have to call
`astroid.builder.MANAGER.astroid_cache.clear()` across runs if you want
to ensure the latest code version is actually checked.
This class needs to support pickling for parallel linting to work. The exception
is reporter member; see check_parallel function for more details.
"""
__implements__ = (interfaces.ITokenChecker,)
name = MAIN_CHECKER_NAME
priority = 0
level = 0
msgs = MSGS
@staticmethod
def make_options():
return (
(
"ignore",
{
"type": "csv",
"metavar": "[,...]",
"dest": "black_list",
"default": ("CVS",),
from pylint import checkers, interfaces
from pylint.checkers import utils
def _is_constant_zero(node):
return isinstance(node, astroid.Const) and node.value == 0
class CompareToZeroChecker(checkers.BaseChecker):
"""Checks for comparisons to zero.
Most of the times you should use the fact that integers with a value of 0 are false.
An exception to this rule is when 0 is allowed in the program and has a
different meaning than None!
"""
__implements__ = (interfaces.IAstroidChecker,)
# configuration section name
name = "compare-to-zero"
msgs = {
"C2001": (
"Avoid comparisons to zero",
"compare-to-zero",
"Used when Pylint detects comparison to a 0 constant.",
)
}
priority = -2
options = ()
@utils.check_messages("compare-to-zero")
def visit_compare(self, node):
if not utils.inherit_from_std_ex(cls) and utils.has_known_bases(cls):
if cls.newstyle:
self._checker.add_message("raising-non-exception", node=self._node)
def visit_tuple(self, _):
self._checker.add_message("raising-bad-type", node=self._node, args="tuple")
def visit_default(self, node):
name = getattr(node, "name", node.__class__.__name__)
self._checker.add_message("raising-bad-type", node=self._node, args=name)
class ExceptionsChecker(checkers.BaseChecker):
"""Exception related checks."""
__implements__ = interfaces.IAstroidChecker
name = "exceptions"
msgs = MSGS
priority = -4
options = (
(
"overgeneral-exceptions",
{
"default": OVERGENERAL_EXCEPTIONS,
"type": "csv",
"metavar": "",
"help": "Exceptions that will emit a warning "
'when being caught. Defaults to "%s".'
% (", ".join(OVERGENERAL_EXCEPTIONS),),
},
),
definition in the AST.
"""
args_list = [args.name for args in node.args.args]
if 'self' in args_list and args_list[0] != 'self':
self.add_message('function-args-order-self', node=node)
elif 'cls' in args_list and args_list[0] != 'cls':
self.add_message('function-args-order-cls', node=node)
class RestrictedImportChecker(checkers.BaseChecker):
"""Custom pylint checker which checks layers importing modules
from their respective restricted layers.
"""
__implements__ = interfaces.IAstroidChecker
name = 'invalid-import'
priority = -1
msgs = {
'C0009': (
'Importing %s layer in %s layer is prohibited.',
'invalid-import',
'Storage layer and domain layer must not import'
'domain layer and controller layer respectively.'),
}
def visit_import(self, node):
"""Visits every import statement in the file.
Args:
node: astroid.node_classes.Import. Node for a import statement
in the AST.
def _do_check(self, files_or_modules):
walker = utils.PyLintASTWalker(self)
_checkers = self.prepare_checkers()
tokencheckers = [c for c in _checkers
if interfaces.implements(c, interfaces.ITokenChecker)
and c is not self]
rawcheckers = [c for c in _checkers
if interfaces.implements(c, interfaces.IRawChecker)]
# notify global begin
for checker in _checkers:
checker.open()
if interfaces.implements(checker, interfaces.IAstroidChecker):
walker.add_checker(checker)
# build ast and check modules or packages
for descr in self.expand_files(files_or_modules):
modname, filepath, is_arg = descr['name'], descr['path'], descr['isarg']
if not self.should_analyze_file(modname, filepath, is_argument=is_arg):
continue
self.set_current_module(modname, filepath)
# get the module representation
try:
value = next(astroid.unpack_infer(expr))
except astroid.InferenceError:
return
self._check_raise_value(node, value)
def _check_raise_value(self, node, expr):
if isinstance(expr, astroid.Const):
value = expr.value
if isinstance(value, str):
self.add_message('raising-string', node=node)
return True
class Python3TokenChecker(checkers.BaseTokenChecker):
__implements__ = interfaces.ITokenChecker
name = 'python3'
enabled = False
msgs = {
'E1606': ('Use of long suffix',
'long-suffix',
'Used when "l" or "L" is used to mark a long integer. '
'This will not work in Python 3, since `int` and `long` '
'types have merged.',
{'maxversion': (3, 0)}),
'E1607': ('Use of the <> operator',
'old-ne-operator',
'Used when the deprecated "<>" operator is used instead '
'of "!=". This is removed in Python 3.',
{'maxversion': (3, 0),
'old_names': [('W0331', 'old-ne-operator')]}),
This is the main checker controlling the other ones and the reports
generation. It is itself both a raw checker and an astroid checker in order
to:
* handle message activation / deactivation at the module level
* handle some basic but necessary stats'data (number of classes, methods...)
IDE plugin developers: you may have to call
`astroid.builder.MANAGER.astroid_cache.clear()` across runs if you want
to ensure the latest code version is actually checked.
This class needs to support pickling for parallel linting to work. The exception
is reporter member; see check_parallel function for more details.
"""
__implements__ = (interfaces.ITokenChecker,)
name = MAIN_CHECKER_NAME
priority = 0
level = 0
msgs = MSGS
@staticmethod
def make_options():
return (
(
"ignore",
{
"type": "csv",
"metavar": "[,...]",
"dest": "black_list",
"default": ("CVS",),
# Copyright (c) 2018 Alexander Todorov
# Licensed under the GPL 2.0: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
import astroid
from pylint import interfaces
from pylint import checkers
from pylint.checkers import utils
class RawSQLChecker(checkers.BaseChecker):
__implements__ = (interfaces.IAstroidChecker,)
name = 'raw-sql-checker'
msgs = {'E4431': ('Avoid using raw SQL',
'avoid-raw-sql',
'Avoid raw SQL, use Django ORM queries instead')}
@utils.check_messages('avoid-raw-sql')
def visit_attribute(self, node):
# looking for .extra(select={}) patterns
if node.attrname == 'extra' and isinstance(node.parent, astroid.Call):
for keyword in node.parent.keywords:
if keyword.arg in ['select', 'where', 'params',
'tables', 'order_by', 'select_params']:
self.add_message('avoid-raw-sql', node=node)
break
return 'migrations' in node.path[0] and not node.path[0].endswith('__init__.py')
class NewDbFieldWithDefaultChecker(checkers.BaseChecker):
"""
Looks for migrations which add new model fields and these fields have a
default value. According to Django docs this may have performance penalties
especially on large tables:
https://docs.djangoproject.com/en/2.0/topics/migrations/#postgresql
The prefered way is to add a new DB column with null=True because it will
be created instantly and then possibly populate the table with the
desired default values.
"""
__implements__ = (interfaces.IAstroidChecker,)
# configuration section name
name = 'new-db-field-with-default'
msgs = {'W%s98' % BASE_ID: ("%s AddField with default value",
'new-db-field-with-default',
'Used when Pylint detects migrations adding new '
'fields with a default value.')}
_migration_modules = []
_possible_offences = {}
def visit_module(self, node):
if _is_migrations_module(node):
self._migration_modules.append(node)
def visit_call(self, node):