Add an argument `is_cli` for Flake8 not running in cli directly

A better solution of 23be44ea50
to fix git hook checks all the staged files.
This commit is contained in:
wanghui 2016-11-22 12:56:26 +08:00
parent 23be44ea50
commit 296193cddc
No known key found for this signature in database
GPG key ID: 9DD1E28DBFC06C26
4 changed files with 38 additions and 17 deletions

View file

@ -247,8 +247,8 @@ class Manager(object):
'' if match else 'not ') '' if match else 'not ')
return match return match
def make_checkers(self, paths=None): def make_checkers(self, paths=None, is_cli=True):
# type: (List[str]) -> NoneType # type: (List[str], bool) -> NoneType
"""Create checkers for each file.""" """Create checkers for each file."""
if paths is None: if paths is None:
paths = self.arguments paths = self.arguments
@ -282,7 +282,11 @@ class Manager(object):
# the event that the argument and the filename are identical. # the event that the argument and the filename are identical.
# If it was specified explicitly, the user intended for it to be # If it was specified explicitly, the user intended for it to be
# checked. # checked.
if argument == filename or should_create_file_checker(filename) # EDIT(cold): Add ``is_cli`` to determine if the current process
# running in cli by using ``flake8 bin/script``. Otherwise
# it should be running by such as git hooks and etc.
if ((is_cli and argument == filename) or
should_create_file_checker(filename))
] ]
LOG.info('Checking %d files', len(self.checkers)) LOG.info('Checking %d files', len(self.checkers))
@ -360,15 +364,18 @@ class Manager(object):
finally: finally:
self._force_cleanup() self._force_cleanup()
def start(self, paths=None): def start(self, paths=None, is_cli=True):
"""Start checking files. """Start checking files.
:param list paths: :param list paths:
Path names to check. This is passed directly to Path names to check. This is passed directly to
:meth:`~Manager.make_checkers`. :meth:`~Manager.make_checkers`.
:param bool is_cli:
If current process running in cli by using `flake8 script.py`
command.
""" """
LOG.info('Making checkers') LOG.info('Making checkers')
self.make_checkers(paths) self.make_checkers(paths, is_cli)
if not self.using_multiprocessing: if not self.using_multiprocessing:
return return

View file

@ -227,7 +227,7 @@ class Application(object):
checker_plugins=self.check_plugins, checker_plugins=self.check_plugins,
) )
def run_checks(self, files=None): def run_checks(self, files=None, is_cli=True):
# type: (Union[List[str], NoneType]) -> NoneType # type: (Union[List[str], NoneType]) -> NoneType
"""Run the actual checks with the FileChecker Manager. """Run the actual checks with the FileChecker Manager.
@ -237,10 +237,14 @@ class Application(object):
:param list files: :param list files:
List of filenames to process List of filenames to process
:param bool is_cli:
If current process running in cli by using `flake8 script.py`
command.
""" """
if self.running_against_diff: if self.running_against_diff:
files = list(sorted(self.parsed_diff.keys())) files = list(sorted(self.parsed_diff.keys()))
self.file_checker_manager.start(files) self.file_checker_manager.start(files, is_cli=is_cli)
self.file_checker_manager.run() self.file_checker_manager.run()
LOG.info('Finished running') LOG.info('Finished running')
self.file_checker_manager.stop() self.file_checker_manager.stop()

View file

@ -5,7 +5,6 @@
""" """
import contextlib import contextlib
import fnmatch
import os import os
import shutil import shutil
import stat import stat
@ -41,11 +40,10 @@ def hook(lazy=False, strict=False):
from flake8.main import application from flake8.main import application
app = application.Application() app = application.Application()
with make_temporary_directory() as tempdir: with make_temporary_directory() as tempdir:
filepaths = [x for x in list(copy_indexed_files_to(tempdir, lazy)) filepaths = list(copy_indexed_files_to(tempdir, lazy))
if fnmatch.fnmatch(x, '*.py')]
app.initialize(['.']) app.initialize(['.'])
app.options.exclude = update_excludes(app.options.exclude, tempdir) app.options.exclude = update_excludes(app.options.exclude, tempdir)
app.run_checks(filepaths) app.run_checks(filepaths, is_cli=False)
app.report_errors() app.report_errors()
if strict: if strict:

View file

@ -30,17 +30,29 @@ def test_find_modified_files(lazy):
@mock.patch("flake8.main.git.copy_indexed_files_to") @mock.patch("flake8.main.git.copy_indexed_files_to")
def test_only_py_files(mock_files): @mock.patch("flake8.checker.os.path.exists", autospec=True)
@mock.patch("flake8.checker.FileChecker._make_processor", autospec=True)
def test_only_py_files(mock_processor, mock_exists, mock_files):
"""Confirm only run checks on Python source file.""" """Confirm only run checks on Python source file."""
class MockProcessor(object):
def __init__(self, filename):
self.filename = filename
self.lines = []
mock_processor.side_effect = lambda self: MockProcessor(self.filename)
mock_exists.return_value = True
mock_files.return_value = [ mock_files.return_value = [
"/tmp/xxx/test.py", "/tmp/xxx/test.py",
"/tmp/xxx/test.html", "/tmp/xxx/test.html",
"/tmp/xxx/test.txt", "/tmp/xxx/test.txt",
] ]
spec = "flake8.main.application.Application.run_checks" def _run_to_test_checker(self):
with mock.patch(spec) as mock_run: new_paths = [x.filename for x in self.checkers]
assert "/tmp/xxx/test.py" in new_paths
assert "/tmp/xxx/test.html" not in new_paths
assert "/tmp/xxx/test.txt" not in new_paths
with mock.patch("flake8.checker.Manager.run", autospec=True) as mock_run:
mock_run.side_effect = _run_to_test_checker
git.hook(lazy=False) git.hook(lazy=False)
mock_run.assert_called_once_with([
"/tmp/xxx/test.py"
])