Esempio n. 1
0
def register_checks():
    import pycodestyle
    from sentry.lint.absolute_import_check import AbsoluteImportCheck
    from sentry.lint.mock_check import MockCheck

    pycodestyle.register_check(MockCheck, codes=[MockCheck.code])
    pycodestyle.register_check(AbsoluteImportCheck, codes=[AbsoluteImportCheck.code])
Esempio n. 2
0
    def _run_check(self, code, checker, filename=None):
        pycodestyle.register_check(checker)

        lines = textwrap.dedent(code).strip().splitlines(True)

        checker = pycodestyle.Checker(filename=filename, lines=lines)
        checker.check_all()
        checker.report._deferred_print.sort()
        return checker.report._deferred_print
Esempio n. 3
0
def patch_pep8():
    if autopep8_c_i in p8._checks['logical_line']:
        del p8._checks['logical_line'][autopep8_c_i]
        p8.register_check(p8.continued_indentation)
    try:
        yield
    finally:
        del p8._checks['logical_line'][p8.continued_indentation]
        p8.register_check(autopep8_c_i)
Esempio n. 4
0
    def test_register_ast_check(self):
        pycodestyle.register_check(DummyChecker, ['Z701'])

        self.assertTrue(DummyChecker in pycodestyle._checks['tree'])
        codes, args = pycodestyle._checks['tree'][DummyChecker]
        self.assertTrue('Z701' in codes)
        self.assertTrue(args is None)

        options = pycodestyle.StyleGuide().options
        self.assertTrue(any(cls == DummyChecker
                            for name, cls, args in options.ast_checks))
Esempio n. 5
0
    def run_check(self, code):
        pycodestyle.register_check(self.get_checker())

        lines = textwrap.dedent(code).strip().splitlines(True)

        # Load all keystone hacking checks, they are of the form Kddd,
        # where ddd can from range from 000-999
        guide = pycodestyle.StyleGuide(select='K')
        checker = pycodestyle.Checker(lines=lines, options=guide.options)
        checker.check_all()
        checker.report._deferred_print.sort()
        return checker.report._deferred_print
Esempio n. 6
0
    def test_styleguide_unmatched_triple_quotes(self):
        pycodestyle.register_check(DummyChecker, ['Z701'])
        lines = [
            'def foo():\n',
            '    """test docstring""\'\n',
        ]

        pep8style = pycodestyle.StyleGuide()
        pep8style.input_file('stdin', lines=lines)
        stdout = sys.stdout.getvalue()

        expected = 'stdin:2:5: E901 TokenError: EOF in multi-line string'
        self.assertTrue(expected in stdout)
Esempio n. 7
0
    def test_check_unicode(self):
        # Do not crash if lines are Unicode (Python 2.x)
        pycodestyle.register_check(DummyChecker, ['Z701'])
        source = '#\n'
        if hasattr(source, 'decode'):
            source = source.decode('ascii')

        pep8style = pycodestyle.StyleGuide()
        count_errors = pep8style.input_file('stdin', lines=[source])

        self.assertFalse(sys.stdout)
        self.assertFalse(sys.stderr)
        self.assertEqual(count_errors, 0)
Esempio n. 8
0
    def _run_check(self, code, checker, filename=None):
        pycodestyle.register_check(checker)

        lines = textwrap.dedent(code).strip().splitlines(True)

        checker = pycodestyle.Checker(filename=filename, lines=lines)
        # NOTE(sdague): the standard reporter has printing to stdout
        # as a normal part of check_all, which bleeds through to the
        # test output stream in an unhelpful way. This blocks that printing.
        with mock.patch('pycodestyle.StandardReport.get_file_results'):
            checker.check_all()
        checker.report._deferred_print.sort()
        return checker.report._deferred_print
Esempio n. 9
0
    def test_register_physical_check(self):
        def check_dummy(physical_line, line_number):
            if False:
                yield
        pycodestyle.register_check(check_dummy, ['Z001'])

        self.assertTrue(check_dummy in pycodestyle._checks['physical_line'])
        codes, args = pycodestyle._checks['physical_line'][check_dummy]
        self.assertTrue('Z001' in codes)
        self.assertEqual(args, ['physical_line', 'line_number'])

        options = pycodestyle.StyleGuide().options
        self.assertTrue(any(func == check_dummy
                            for name, func, args in options.physical_checks))
Esempio n. 10
0
    def test_register_invalid_check(self):
        class InvalidChecker(DummyChecker):
            def __init__(self, filename):
                pass

        def check_dummy(logical, tokens):
            if False:
                yield
        pycodestyle.register_check(InvalidChecker, ['Z741'])
        pycodestyle.register_check(check_dummy, ['Z441'])

        for checkers in pycodestyle._checks.values():
            self.assertTrue(DummyChecker not in checkers)
            self.assertTrue(check_dummy not in checkers)

        self.assertRaises(TypeError, pycodestyle.register_check)
Esempio n. 11
0
    def add_options(cls, parser):
        # We're looking for local checks, so we need to include the local
        # dir in the search path
        sys.path.append('.')

        local_check = CONF.get_multiple('local-check', default=[])
        for check_path in set(local_check):
            if check_path.strip():
                checker = pbr.util.resolve_name(check_path)
                pycodestyle.register_check(checker)

        local_check_fact = CONF.get('local-check-factory')
        if local_check_fact:
            factory = pbr.util.resolve_name(local_check_fact)
            factory(pycodestyle.register_check)

        sys.path.pop()
Esempio n. 12
0
    def test_check_nullbytes(self):
        pycodestyle.register_check(DummyChecker, ['Z701'])

        pep8style = pycodestyle.StyleGuide()
        count_errors = pep8style.input_file('stdin', lines=['\x00\n'])

        stdout = sys.stdout.getvalue()
        if 'SyntaxError' in stdout:
            # PyPy 2.2 returns a SyntaxError
            expected = "stdin:1:2: E901 SyntaxError"
        elif 'ValueError' in stdout:
            # Python 3.5.
            expected = "stdin:1:1: E901 ValueError"
        else:
            expected = "stdin:1:1: E901 TypeError"
        self.assertTrue(stdout.startswith(expected),
                        msg='Output %r does not start with %r' %
                        (stdout, expected))
        self.assertFalse(sys.stderr)
        self.assertEqual(count_errors, 1)
Esempio n. 13
0
def check_easyconfigs_style(easyconfigs, verbose=False):
    """
    Check the given list of easyconfigs for style
    :param: easyconfigs list of file paths to easyconfigs
    :param: verbose print our statistics and be verbose about the errors and warning
    :return: the number of warnings and errors
    """
    # importing autopep8 changes some pep8 functions.
    # We reload it to be sure to get the real pep8 functions.
    if 'pycodestyle' in sys.modules:
        reload(pycodestyle)
    else:
        reload(pep8)

    # register the extra checks before using pep8:
    # any function in this module starting with `_eb_check_` will be used.
    cands = globals()
    for check_function in sorted([cands[f] for f in cands if callable(cands[f]) and f.startswith(EB_CHECK)]):
        _log.debug("Adding custom style check %s", check_function)
        register_check(check_function)

    styleguide = StyleGuide(quiet=False, config_file=None)
    options = styleguide.options
    # we deviate from standard pep8 and allow 120 chars
    # on a line: the default of 79 is too narrow.
    options.max_line_length = MAX_LINE_LENGTH
    # we ignore some tests
    # note that W291 has been replaced by our custom W299
    options.ignore = (
        'W291',  # replaced by W299
    )
    options.verbose = int(verbose)

    result = styleguide.check_files(easyconfigs)

    if verbose:
        result.print_statistics()

    return result.total_errors
Esempio n. 14
0
    def test_styleguide_continuation_line_outdented(self):
        pycodestyle.register_check(DummyChecker, ['Z701'])
        lines = [
            'def foo():\n',
            '    pass\n',
            '\n',
            '\\\n',
            '\n',
            'def bar():\n',
            '    pass\n',
        ]

        pep8style = pycodestyle.StyleGuide()
        count_errors = pep8style.input_file('stdin', lines=lines)
        self.assertEqual(count_errors, 2)
        stdout = sys.stdout.getvalue()
        expected = (
            'stdin:6:1: '
            'E122 continuation line missing indentation or outdented'
        )
        self.assertTrue(expected in stdout)
        expected = 'stdin:6:1: E302 expected 2 blank lines, found 1'
        self.assertTrue(expected in stdout)
Esempio n. 15
0
def _main():
    """Parse options and run checks on Skylark source."""

    pycodestyle.register_check(whitespace_around_named_parameter_equals)

    style_guide = pycodestyle.StyleGuide(parse_argv=True)
    options = style_guide.options

    ignore = set(options.ignore)
    ignore.add('E251')  # Skylark wants spaces around named parameters
    ignore.add('E711')  # Skylark has no `is`
    ignore.add('E721')  # Skylark has no `isinstance`
    options.ignore = tuple(ignore)

    report = style_guide.check_files()

    if options.statistics:
        report.print_statistics()

    if report.total_errors:
        if options.count:
            sys.stderr.write(str(report.total_errors) + '\n')
        sys.exit(1)
Esempio n. 16
0
def _register_extensions():
    """Register all the extensions."""
    extensions = util.OrderedSet()
    extensions.add(('pycodestyle', pep8.__version__))
    parser_hooks = []
    options_hooks = []
    ignored_hooks = []
    try:
        from pkg_resources import iter_entry_points
    except ImportError:
        pass
    else:
        for entry in iter_entry_points('flake8.extension'):
            # Do not verify that the requirements versions are valid
            checker = _load_entry_point(entry, verify_requirements=False)
            pep8.register_check(checker, codes=[entry.name])
            extensions.add((checker.name, checker.version))
            if hasattr(checker, 'add_options'):
                parser_hooks.append(checker.add_options)
            if hasattr(checker, 'parse_options'):
                options_hooks.append(checker.parse_options)
            if getattr(checker, 'off_by_default', False) is True:
                ignored_hooks.append(entry.name)
    return extensions, parser_hooks, options_hooks, ignored_hooks
Esempio n. 17
0
    def test_register_logical_check(self):
        def check_dummy(logical_line, tokens):
            if False:
                yield
        pycodestyle.register_check(check_dummy, ['Z401'])

        self.assertTrue(check_dummy in pycodestyle._checks['logical_line'])
        codes, args = pycodestyle._checks['logical_line'][check_dummy]
        self.assertTrue('Z401' in codes)
        self.assertEqual(args, ['logical_line', 'tokens'])

        pycodestyle.register_check(check_dummy, [])
        pycodestyle.register_check(check_dummy, ['Z402', 'Z403'])
        codes, args = pycodestyle._checks['logical_line'][check_dummy]
        self.assertEqual(codes, ['Z401', 'Z402', 'Z403'])
        self.assertEqual(args, ['logical_line', 'tokens'])

        options = pycodestyle.StyleGuide().options
        self.assertTrue(any(func == check_dummy
                            for name, func, args in options.logical_checks))
Esempio n. 18
0
    def test_register_logical_check(self):
        def check_dummy(logical_line, tokens):
            if False:
                yield
        pycodestyle.register_check(check_dummy, ['Z401'])

        self.assertTrue(check_dummy in pycodestyle._checks['logical_line'])
        codes, args = pycodestyle._checks['logical_line'][check_dummy]
        self.assertTrue('Z401' in codes)
        self.assertEqual(args, ['logical_line', 'tokens'])

        pycodestyle.register_check(check_dummy, [])
        pycodestyle.register_check(check_dummy, ['Z402', 'Z403'])
        codes, args = pycodestyle._checks['logical_line'][check_dummy]
        self.assertEqual(codes, ['Z401', 'Z402', 'Z403'])
        self.assertEqual(args, ['logical_line', 'tokens'])

        options = pycodestyle.StyleGuide().options
        self.assertTrue(any(func == check_dummy
                            for name, func, args in options.logical_checks))
Esempio n. 19
0
    def test_register_logical_check(self):
        def check_dummy(logical_line, tokens):
            raise NotImplementedError

        pycodestyle.register_check(check_dummy, ['Z401'])

        self.assertTrue(check_dummy in pycodestyle._checks['logical_line'])
        codes, args = pycodestyle._checks['logical_line'][check_dummy]
        self.assertTrue('Z401' in codes)
        self.assertEqual(args, ['logical_line', 'tokens'])

        pycodestyle.register_check(check_dummy, [])
        pycodestyle.register_check(check_dummy, ['Z402', 'Z403'])
        codes, args = pycodestyle._checks['logical_line'][check_dummy]
        self.assertEqual(codes, ['Z401', 'Z402', 'Z403'])
        self.assertEqual(args, ['logical_line', 'tokens'])

        options = pycodestyle.StyleGuide().options
        functions = [func for _, func, _ in options.logical_checks]
        self.assertIn(check_dummy, functions)
Esempio n. 20
0
Module implementing the code style checker.
"""

try:  # Only for Py2
    import Queue as queue
except ImportError:
    import queue

import sys
import multiprocessing

import pycodestyle
from NamingStyleChecker import NamingStyleChecker

# register the name checker
pycodestyle.register_check(NamingStyleChecker, NamingStyleChecker.Codes)

from DocStyleChecker import DocStyleChecker
from MiscellaneousChecker import MiscellaneousChecker
from ComplexityChecker import ComplexityChecker


def initService():
    """
    Initialize the service and return the entry point.
    
    @return the entry point for the background client (function)
    """
    return codeStyleCheck

Esempio n. 21
0
            # This means that we don't have existing config to use.
            # Make sure pycodestyle's code ignores are fully reset to zero before
            # adding prospector-flavoured configuration.
            # pylint: disable=attribute-defined-outside-init
            self.checker.options.select = ()
            self.checker.options.ignore = tuple(
                prospector_config.get_disabled_messages("pycodestyle"))

            if "max-line-length" in prospector_config.tool_options(
                    "pycodestyle"):
                self.checker.options.max_line_length = prospector_config.tool_options(
                    "pycodestyle")["max-line-length"]
        else:
            configured_by = "Configuration found at %s" % external_config

        # if we have a command line --max-line-length argument, that
        # overrules everything
        max_line_length = prospector_config.max_line_length
        if max_line_length is not None:
            self.checker.options.max_line_length = max_line_length

        return configured_by, []

    def run(self, _):
        report = self.checker.check_files()
        return report.get_messages()


# Load pep8ext_naming into pycodestyle's configuration.
register_check(NamingChecker)
Esempio n. 22
0
# -*- coding: utf-8 -*-
Esempio n. 23
0
def register_checks():
    import pycodestyle

    from sentry.lint.sentry_check import SentryCheck

    pycodestyle.register_check(SentryCheck)
Esempio n. 24
0
def register_checks():
    import pycodestyle

    from sentry.lint.sentry_check import SentryCheck

    pycodestyle.register_check(SentryCheck)
Esempio n. 25
0
        if not use_config or external_config is None:
            configured_by = None
            # This means that we don't have existing config to use.
            # Make sure pep8's code ignores are fully reset to zero before
            # adding prospector-flavoured configuration.
            # pylint: disable=attribute-defined-outside-init
            self.checker.options.select = ()
            self.checker.options.ignore = tuple(prospector_config.get_disabled_messages('pep8'))

            if 'max-line-length' in prospector_config.tool_options('pep8'):
                self.checker.options.max_line_length = \
                    prospector_config.tool_options('pep8')['max-line-length']
        else:
            configured_by = "Configuration found at %s" % external_config

        # if we have a command line --max-line-length argument, that
        # overrules everything
        max_line_length = prospector_config.max_line_length
        if max_line_length is not None:
            self.checker.options.max_line_length = max_line_length

        return configured_by, []

    def run(self, _):
        report = self.checker.check_files()
        return report.get_messages()


# Load pep8ext_naming into pep8's configuration.
register_check(NamingChecker)
Esempio n. 26
0
import logging
import pycodestyle
from pylsp import hookimpl, lsp

try:
    from autopep8 import continued_indentation as autopep8_c_i
except ImportError:
    pass
else:
    # Check if autopep8's continued_indentation implementation
    # is overriding pycodestyle's and if so, re-register
    # the check using pycodestyle's implementation as expected
    if autopep8_c_i in pycodestyle._checks['logical_line']:
        del pycodestyle._checks['logical_line'][autopep8_c_i]
        pycodestyle.register_check(pycodestyle.continued_indentation)

log = logging.getLogger(__name__)


@hookimpl
def pylsp_lint(workspace, document):
    config = workspace._config
    settings = config.plugin_settings('pycodestyle',
                                      document_path=document.path)
    log.debug("Got pycodestyle settings: %s", settings)

    opts = {
        'exclude': settings.get('exclude'),
        'filename': settings.get('filename'),
        'hang_closing': settings.get('hangClosing'),