Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# Copyright (c) 2018 Sushobhit <31987769+sushobhit27@users.noreply.github.com>
# Copyright (c) 2018 Ville Skyttä
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
import astroid
from pylint.checkers import BaseChecker
from pylint.checkers.utils import check_messages, is_none, node_type
from pylint.interfaces import IAstroidChecker
BUILTINS = "builtins"
class MultipleTypesChecker(BaseChecker):
"""Checks for variable type redefinitions (NoneType excepted)
At a function, method, class or module scope
This rule could be improved:
- Currently, if an attribute is set to different types in 2 methods of a
same class, it won't be detected (see functional test)
- One could improve the support for inference on assignment with tuples,
ifexpr, etc. Also it would be great to have support for inference on
str.split()
"""
__implements__ = IAstroidChecker
name = "multiple_types"
"""Make sure the module name is sane"""
# Catch various typos.
name = node.name.rsplit('.', 2)[-1]
if name.rsplit('_', 2)[-1] in ('unittests',):
self.add_message('R9203')
def _check_trailing_lines(self, _node, stream):
"""Reject trailing lines"""
st = os.fstat(stream.fileno())
if st.st_size > 1:
stream.seek(st.st_size - 2)
if not stream.read().strip('\n'):
self.add_message('R9210')
class ChromiteLoggingChecker(BaseChecker):
"""Make sure we enforce rules on importing logging."""
__implements__ = IAstroidChecker
# pylint: disable=class-missing-docstring,multiple-statements
class _MessageR9301(object): pass
# pylint: enable=class-missing-docstring,multiple-statements
name = 'chromite_logging_checker'
priority = -1
MSG_ARGS = 'offset:%(offset)i: {%(line)s}'
msgs = {
'R9301': ('logging is deprecated. Use "from chromite.lib import '
'cros_logging as logging" to import chromite/lib/cros_logging',
('cros-logging-import'), _MessageR9301),
}
lhs = found_node[0].parent.targets[0]
if lhs.name == name: # this name is defined in this very statement
found_node = None
if (
found_node
and isinstance(parent_node, astroid.For)
and parent_node.iter == node
and parent_node.target in found_node
):
found_node = None
return found_node
# pylint: disable=too-many-public-methods
class VariablesChecker(BaseChecker):
"""checks for
* unused variables / imports
* undefined variables
* redefinition of variable from builtins or from an outer scope
* use of variable before assignment
* __all__ consistency
* self/cls assignment
"""
__implements__ = IAstroidChecker
name = "variables"
msgs = MSGS
priority = -1
options = (
(
def __init__(self, linter=None):
BaseChecker.__init__(self, linter)
self._to_consume = None
self._checking_mod_attr = None
modname = '.' * node.level + node.modname
for (name, _) in node.names:
if name == 'constants':
continue
try:
imported_module.import_module(name, True)
except astroid.AstroidImportError:
self.add_message(
'import-only-modules',
node=node,
args=(name, modname),
)
class BackslashContinuationChecker(checkers.BaseChecker):
"""Custom pylint checker which checks that backslash is not used
for continuation.
"""
__implements__ = interfaces.IRawChecker
name = 'backslash-continuation'
priority = -1
msgs = {
'C0004': (
(
'Backslash should not be used to break continuation lines. '
'Use braces to break long lines.'),
'backslash-continuation',
'Use braces to break long lines instead of backslash.'
),
}
def __init__(self, linter=None):
BaseChecker.__init__(self, linter)
self._accessed = []
self._first_attrs = []
self._meth_could_be_func = None
"""return True if the object is a method redefined via decorator.
For example:
@property
def x(self): return self._x
@x.setter
def x(self, value): self._x = value
"""
if node.decorators:
for decorator in node.decorators.nodes:
if (isinstance(decorator, astng.Getattr) and
getattr(decorator.expr, 'name', None) == node.name):
return True
return False
class _BasicChecker(BaseChecker):
__implements__ = IASTNGChecker
name = 'basic'
class BasicErrorChecker(_BasicChecker):
msgs = {
'E0100': ('__init__ method is a generator',
'init-is-generator',
'Used when the special class method __init__ is turned into a '
'generator by a yield in its body.'),
'E0101': ('Explicit return in __init__',
'return-in-init',
'Used when the special class method __init__ has an explicit \
return value.'),
'E0102': ('%s already defined line %s',
'function-redefined',
'Used when a function / class / method is redefined.'),
# 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.
#
# This program 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 this program. If not, see .
from pylint.interfaces import IAstroidChecker
from pylint.checkers import BaseChecker
class SizeChecker(BaseChecker):
__implements__ = IAstroidChecker
name = 'django_size_checker'
msgs = {
'W8001': (
'%r is actually a directory; consider splitting application',
'models-as-directory',
'Models as directory',
),
}
def leave_module(self, node):
for candidate in ('views', 'models'):
if not node.name.endswith('.%s' % candidate):
continue
from pylint.interfaces import IAstroidChecker
from .common import BASE_ID, check_visitors
FILENAME = os.environ.get("PYLINT_RECORD_FILES", "")
def register_checkers(linter):
"""Register checkers."""
if FILENAME:
linter.register_checker(ModuleTracingChecker(linter))
@check_visitors
class ModuleTracingChecker(BaseChecker):
"""
Not really a checker, it doesn't generate any messages. There's probably
a better way to hook into pylint to do this.
"""
__implements__ = (IAstroidChecker,)
name = "module-tracing-checker"
msgs = {("E%d00" % BASE_ID): ("bogus", "bogus", "bogus")}
def visit_module(self, node):
"""Called for each module being examined."""
with open(FILENAME, "a") as f:
f.write(node.file)
f.write("\n")
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
"""Pylint plugin for checking in Sphinx, Google, or Numpy style docstrings
"""
from __future__ import print_function, division, absolute_import
import astroid
from pylint.interfaces import IAstroidChecker
from pylint.checkers import BaseChecker
from pylint.checkers import utils as checker_utils
import pylint.extensions._check_docs_utils as utils
class DocstringParameterChecker(BaseChecker):
"""Checker for Sphinx, Google, or Numpy style docstrings
* Check that all function, method and constructor parameters are mentioned
in the params and types part of the docstring. Constructor parameters
can be documented in either the class docstring or ``__init__`` docstring,
but not both.
* Check that there are no naming inconsistencies between the signature and
the documentation, i.e. also report documented parameters that are missing
in the signature. This is important to find cases where parameters are
renamed only in the code, not in the documentation.
* Check that all explicitly raised exceptions in a function are documented
in the function docstring. Caught exceptions are ignored.
Activate this checker by adding the line::
load-plugins=pylint.extensions.docparams