Exemple #1
0
def test_enable_local_plugin_from_config():
    """App can load a local plugin from config file."""
    app = application.Application()
    app.initialize(['flake8', '--config', LOCAL_PLUGIN_CONFIG])

    assert app.check_plugins['XE'].plugin is ExtensionTestPlugin
    assert app.formatting_plugins['XR'].plugin is ReportTestPlugin
Exemple #2
0
def check_file(path, flake8ignore, maxlength, maxcomplexity, showshource,
               statistics):
    """Run flake8 over a single file, and return the number of failures."""
    args = []
    if maxlength:
        args += ['--max-line-length', maxlength]
    if maxcomplexity:
        args += ['--max-complexity', maxcomplexity]
    if showshource:
        args += ['--show-source']
    if statistics:
        args += ['--statistics']
    app = application.Application()
    app.parse_preliminary_options_and_args(args)
    app.make_config_finder()
    app.find_plugins()
    app.register_plugin_options()
    app.parse_configuration_and_cli(args)
    if flake8ignore:
        app.options.ignore = flake8ignore
    app.make_formatter()  # fix this
    app.make_notifier()
    app.make_guide()
    app.make_file_checker_manager()
    app.run_checks([str(path)])
    app.formatter.start()
    app.report_errors()
    # app.report_statistics()
    # app.report_benchmarks()
    app.formatter.stop()
    return app.result_count
Exemple #3
0
def get_style_guide(**kwargs):
    r"""Provision a StyleGuide for use.

    :param \*\*kwargs:
        Keyword arguments that provide some options for the StyleGuide.
    :returns:
        An initialized StyleGuide
    :rtype:
        :class:`StyleGuide`
    """
    application = app.Application()
    application.parse_preliminary_options_and_args([])
    flake8.configure_logging(application.prelim_opts.verbose,
                             application.prelim_opts.output_file)
    application.make_config_finder()
    application.find_plugins()
    application.register_plugin_options()
    application.parse_configuration_and_cli([])
    # We basically want application.initialize to be called but with these
    # options set instead before we make our formatter, notifier, internal
    # style guide and file checker manager.
    options = application.options
    for key, value in kwargs.items():
        try:
            getattr(options, key)
            setattr(options, key, value)
        except AttributeError:
            LOG.error('Could not update option "%s"', key)
    application.make_formatter()
    application.make_guide()
    application.make_file_checker_manager()
    return StyleGuide(application)
Exemple #4
0
def test_enable_local_plugin_at_non_installed_path():
    """Can add a paths option in local-plugins config section for finding."""
    app = application.Application()
    app.initialize(["flake8", "--config", LOCAL_PLUGIN_PATH_CONFIG])

    assert app.check_plugins is not None
    assert app.check_plugins["XE"].plugin.name == "ExtensionTestPlugin2"
Exemple #5
0
    def run(self):
        from flake8.main import application

        logging.getLogger().setLevel(logging.ERROR)
        flake8 = application.Application()
        flake8.run(self.targets())
        flake8.exit()
Exemple #6
0
def hook(ui, repo, **kwargs):
    """Execute Flake8 on the repository provided by Mercurial.

    To understand the parameters read more of the Mercurial documentation
    around Hooks: https://www.mercurial-scm.org/wiki/Hook.

    We avoid using the ``ui`` attribute because it can cause issues with
    the GPL license tha Mercurial is under. We don't import it, but we
    avoid using it all the same.
    """
    from flake8.main import application

    hgrc = find_hgrc(create_if_missing=False)
    if hgrc is None:
        print("Cannot locate your root mercurial repository.")
        raise SystemExit(True)

    hgconfig = configparser_for(hgrc)
    strict = hgconfig.get("flake8", "strict", fallback=True)

    filenames = list(get_filenames_from(repo, kwargs))

    app = application.Application()
    app.initialize(filenames)
    app.options._running_from_vcs = True
    app.run_checks()
    app.report()

    if strict:
        return app.result_count
    return 0
def run_flake8(src_name: str, evs: dict):
    errors_found = False
    flake_parms, max_errors = parse_evs(evs)

    # Делаем так, чтобы flake8 налогировал нам в переменную
    old_stdout = sys.stdout
    log_capture_string = io.StringIO()
    sys.stdout = log_capture_string
    # Запускаем flake
    app = application.Application()
    app.initialize(flake_parms)
    app.run_checks([src_name])
    app.report_errors()
    # Вытягиваем данные
    sys.stdout = old_stdout
    stdout_data = log_capture_string.getvalue()
    log_capture_string.close()
    if stdout_data:
        stdout_data = '\n' + stdout_data
        tot_errors = stdout_data.count('\n' + LINE_STARTER)
        if tot_errors > max_errors:
            ps = -1
            for __ in range(max_errors):
                ps = stdout_data.find('\n' + LINE_STARTER, ps + 1)
            stdout_data = stdout_data[:ps]
            rem = tot_errors - max_errors
            tail = 'ий' if 5 <= rem % 100 <= 20 else 'ия' if 1 < rem % 10 < 5 else 'ие'
            add = '\n' + '=' * 50 + \
                  '\nТам ещё {} замечан{} к стилю.\n'.format(rem, tail) + \
                  'Используйте автоформатирование кода: Ctrl+Alt+L в PyCharm или сервис https://black.now.sh'
            stdout_data += add
        errors_found = True
    else:
        stdout_data = ' '
    return errors_found, stdout_data[1:]
Exemple #8
0
def lint2(app_configs, **kwargs):
    application = app.Application()

    application.parse_preliminary_options_and_args([])
    application.make_config_finder()

    application.find_plugins()
    application.register_plugin_options()

    application.parse_configuration_and_cli([])

    options = application.options
    if hasattr(settings, 'LINT2'):
        for key, value in settings.LINT2.items():
            setattr(options, key, value)

    setattr(options, 'exclude', ['*migrations*', 'manage.py', '.git', 'settings.py'])

    application.make_formatter(flake8.formatting.default.Nothing)
    application.make_notifier()
    application.make_guide()
    application.make_file_checker_manager()

    application.run_checks()
    application.report_errors()

    errors = []
    for checker in application.file_checker_manager.checkers:
        for err in checker.results:
            errors.append(Warning(
                f'{checker.filename}:{err[1]}:{err[2]}:{err[3]}',
                id=err[0],
            ))
    return errors
Exemple #9
0
def hook(lazy=False, strict=False):
    """Execute Flake8 on the files in git's index.

    Determine which files are about to be committed and run Flake8 over them
    to check for violations.

    :param bool lazy:
        Find files not added to the index prior to committing. This is useful
        if you frequently use ``git commit -a`` for example. This defaults to
        False since it will otherwise include files not in the index.
    :param bool strict:
        If True, return the total number of errors/violations found by Flake8.
        This will cause the hook to fail.
    :returns:
        Total number of errors found during the run.
    :rtype:
        int
    """
    # NOTE(sigmavirus24): Delay import of application until we need it.
    from flake8.main import application
    app = application.Application()
    with make_temporary_directory() as tempdir:
        filepaths = list(copy_indexed_files_to(tempdir, lazy))
        app.initialize(filepaths)
        app.run_checks()

    app.report_errors()
    if strict:
        return app.result_count
    return 0
Exemple #10
0
def _flake8_annotations(path, options):
    import os

    _tmp = os.environ.get('TMPDIR', os.environ.get('TMP'))
    _output_file = os.path.join(_tmp, 'blackmamba.flake8.txt')

    annotations = []

    for o in options:
        try:
            from flake8.main import application

            if os.path.exists(_output_file):
                os.remove(_output_file)

            o = list(o)
            o.insert(0, path)
            o.extend([
                '-j',
                '0',  # Disable subprocess
                '--output-file={}'.format(_output_file)
            ])
            app = application.Application()
            app.run(o)
            del app

            annotations.extend(_parse_flake8_output(path, _output_file))
        except Exception as e:
            log.error('flake8 failed: {}'.format(str(e)))

    if os.path.exists(_output_file):
        os.remove(_output_file)

    return annotations
Exemple #11
0
def hook(config, tree_delta, future_tree):
    """Execute Flake8 on the files in git's index.

    Determine which files are about to be committed and run Flake8 over
    them to check for violations.

    :param bool strict:
        If True, return the total number of errors/violations found by
        Flake8. This will cause the hook to fail.
    :returns:
        Total number of errors found during the run.
    :rtype:
        int
    """
    try:
        from flake8.main import application
    except ImportError as e:
        raise DependencyNotPresent('flake8', e)
    import tempfile

    strict = config.get("flake8.strict")

    app = application.Application()
    with tempfile.TemporaryDirectory() as tempdir:
        filepaths = list(
            _copy_files_to(future_tree, tempdir, _delta_files(tree_delta)))
        app.initialize([tempdir])
        app.options._running_from_vcs = True
        app.run_checks(filepaths)
        _update_paths(app.file_checker_manager, tempdir)
        app.report_errors()

    if strict:
        if app.result_count:
            raise Flake8Errors(app.result_count)
def check_flake8(paths):
    """
    Run flake8 on other files
    """
    app = application.Application()
    app.run(paths)
    app.exit()
Exemple #13
0
def test_local_plugin_can_add_option():
    """A local plugin can add a CLI option."""
    app = application.Application()
    app.initialize(
        ['flake8', '--config', LOCAL_PLUGIN_CONFIG, '--anopt', 'foo'])

    assert app.options.anopt == 'foo'
Exemple #14
0
def test_local_plugin_can_add_option():
    """A local plugin can add a CLI option."""
    app = application.Application()
    app.initialize(
        ["flake8", "--config", LOCAL_PLUGIN_CONFIG, "--anopt", "foo"])

    assert app.options is not None
    assert app.options.anopt == "foo"
Exemple #15
0
def mocked_application():
    """Create an application with a mocked OptionManager."""
    with mock.patch('flake8.options.manager.OptionManager') as optionmanager:
        optmgr = optionmanager.return_value = mock.Mock()
        optmgr.parse_known_args.return_value = (options(), [])
        application = app.Application()

    return application
 def initialize_options(self):
     """Override this method to initialize our application."""
     self.flake8 = app.Application()
     self.flake8.initialize([])
     options = self.flake8.option_manager.options
     for option in options:
         if option.parse_from_config:
             setattr(self, option.config_name, UNSET)
Exemple #17
0
def test_enable_local_plugin_from_config():
    """App can load a local plugin from config file."""
    app = application.Application()
    app.initialize(["flake8", "--config", LOCAL_PLUGIN_CONFIG])

    assert app.check_plugins is not None
    assert app.check_plugins["XE"].plugin is ExtensionTestPlugin
    assert app.formatting_plugins is not None
    assert app.formatting_plugins["XR"].plugin is ReportTestPlugin
Exemple #18
0
 def test_default_option(self):
     """By default a config file (.isort.cfg) is expected"""
     file_path = self._given_a_file_in_test_dir(
         'from sys import pid\n'
         'import threading\n',
         isort_config='force_single_line=True'
     )
     with OutputCapture():
         app = application.Application()
         app.run([file_path, ])
         self.assertTrue(Flake8Isort.config_file)
Exemple #19
0
 def test_config_file(self):
     """Check that one can force to not look for a config file"""
     file_path = self._given_a_file_in_test_dir(
         'from sys import pid\n'
         'import threading\n',
         isort_config='force_single_line=True'
     )
     with OutputCapture():
         app = application.Application()
         app.run(['--no-isort-config', file_path, ])
         self.assertFalse(Flake8Isort.config_file)
Exemple #20
0
    def test_new_formatting_no_problem(self):
        file_path = self._given_a_file_in_test_dir('\n'.join([
            'print("hello {0:s}".format("world"))\n',
        ]))
        app = application.Application()
        with OutputCapture() as output:
            app.run([file_path, ])

        self.assertEqual(
            output.captured,
            ''
        )
Exemple #21
0
def test_exit_does_not_raise(result_count, catastrophic, exit_zero):
    """Verify Application.exit doesn't raise SystemExit."""
    with mock.patch('flake8.options.manager.OptionManager') as optionmanager:
        optmgr = optionmanager.return_value = mock.Mock()
        optmgr.parse_known_args.return_value = (options(), [])
        application = app.Application()

    application.result_count = result_count
    application.catastrophic_failure = catastrophic
    application.options = options(exit_zero=exit_zero)

    assert application.exit() is None
Exemple #22
0
    def test_no_old_formatter(self):
        file_path = self._given_a_file_in_test_dir(
            'b = 3\n'
        )
        app = application.Application()
        with OutputCapture() as output:
            app.run([file_path, ])

        self.assertEqual(
            output.captured,
            ''
        )
Exemple #23
0
def test_tokenization_error_but_not_syntax_error(tmpdir, capsys):
    """Test that flake8 does not crash on tokenization errors."""
    with tmpdir.as_cwd():
        # this is a crash in the tokenizer, but not in the ast
        tmpdir.join('t.py').write("b'foo' \\\n")

        app = application.Application()
        app.run(['t.py'])

    out, err = capsys.readouterr()
    assert out == 't.py:1:1: E902 TokenError: EOF in multi-line statement\n'
    assert err == ''
Exemple #24
0
    def test_multiline_formatter(self):
        file_path = self._given_a_file_in_test_dir('\n'.join([
            'print("hello %s"',
            '% (\'world\'))',
        ]))
        app = application.Application()
        with OutputCapture() as output:
            app.run([file_path, ])

        self.assertIn(
            '1:7: S001 found module formatter',
            output.captured
        )
Exemple #25
0
def main(argv=None):
    # type: (Optional[List[str]]) -> None
    """Execute the main bit of the application.

    This handles the creation of an instance of :class:`Application`, runs it,
    and then exits the application.

    :param list argv:
        The arguments to be passed to the application for parsing.
    """
    app = application.Application()
    app.run(argv)
    app.exit()
Exemple #26
0
def main(argv=None):
    # type: (Union[NoneType, List[str]]) -> NoneType
    """Main entry-point for the flake8 command-line tool.

    This handles the creation of an instance of :class:`Application`, runs it,
    and then exits the application.

    :param list argv:
        The arguments to be passed to the application for parsing.
    """
    app = application.Application()
    app.run(argv)
    app.exit()
Exemple #27
0
def lint():
    # cli options at http://flake8.pycqa.org/en/latest/user/options.html
    # error code definitions at https://pep8.readthedocs.io/en/latest/intro.html
    print('Running linter...')  # NOQA: T001
    app = application.Application()
    app.run([
        '--exclude=.git,__pycache__,node_modules,static,svelte,views',
        '--ignore=E128,E261,W503',
        '--max-line-length=120',
        '.',
    ])
    print('Linting complete.')  # NOQA: T001
    # app.exit() # could just call this but it exits early whereas we might want to do other things
    return app.result_count < 1 and not app.catastrophic_failure
Exemple #28
0
def test_extend_exclude(tmpdir, capsys):
    """Ensure that `flake8 --extend-exclude` works."""
    for d in ['project', 'vendor', 'legacy', '.git', '.tox', '.hg']:
        tmpdir.mkdir(d).join('t.py').write('import os\nimport sys\n')

    with tmpdir.as_cwd():
        application.Application().run(['--extend-exclude=vendor,legacy'])

    out, err = capsys.readouterr()
    expected_out = '''\
./project/t.py:1:1: F401 'os' imported but unused
./project/t.py:2:1: F401 'sys' imported but unused
'''
    assert out == expected_out.replace('/', os.sep)
    assert err == ''
Exemple #29
0
def test_statistics_option(tmpdir, capsys):
    """Ensure that `flake8 --statistics` works."""
    with tmpdir.as_cwd():
        tmpdir.join('t.py').write('import os\nimport sys\n')

        app = application.Application()
        app.run(['--statistics', 't.py'])

    out, err = capsys.readouterr()
    assert out == '''\
t.py:1:1: F401 'os' imported but unused
t.py:2:1: F401 'sys' imported but unused
2     F401 'os' imported but unused
'''
    assert err == ''
Exemple #30
0
def _call_flake8(argv: Optional[List[str]] = None) -> None:
    """Execute the main bit of the application.

    This handles the creation of an instance of the class `Application`, runs it,
    and then exits the application.

    Args:
        argv (Optional[List[str]]): The arguments to be passed to the application for
            parsing.
    """
    if argv is None:
        argv = sys.argv[1:]

    app = application.Application()
    app.run(argv)
    app.exit()