Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,30 @@ Example

disable=ASYNC91,ASYNC117

``per-file-disable``
--------------------

Disable error codes and their autofixes for matching files. A pattern can
match a basename, an absolute path, or a path relative to the current working
directory. Each mapping uses ``pattern->CODE,CODE`` and accepts code prefixes
like ``disable``. Codes from every matching mapping are combined.

In a Flake8 configuration file, put each mapping on a separate line.

.. code-block:: ini

[flake8]
per-file-disable =
tests/*.py->ASYNC100,ASYNC115
example.py->ASYNC2

In standalone mode, quote the option value so the shell passes the pattern
and arrow through to ``flake8-async``.

.. code-block:: sh

flake8-async --per-file-disable='tests/*.py->ASYNC100,ASYNC115'

.. _autofix:

``autofix``
Expand Down
58 changes: 44 additions & 14 deletions flake8_async/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
import tokenize
import warnings
from argparse import ArgumentParser, ArgumentTypeError, Namespace
from dataclasses import replace
from fnmatch import fnmatch
from pathlib import Path
from typing import TYPE_CHECKING

import libcst as cst
Expand Down Expand Up @@ -124,8 +127,27 @@ class Plugin:

@property
def options(self) -> Options:
assert self._options is not None
return self._options
options = self._options
assert options is not None
if self.filename is None or not options.per_file_disable:
return options

basename = Path(self.filename).name
# Match the input path without following symlinks.
path = os.path.abspath(self.filename) # noqa: PTH100
disabled_codes: set[str] = set()
for pattern, codes in options.per_file_disable.items():
absolute_pattern = os.path.abspath(pattern) # noqa: PTH100
if fnmatch(basename, pattern) or fnmatch(path, absolute_pattern):
disabled_codes.update(codes)

if not disabled_codes:
return options
return replace(
options,
enabled_codes=options.enabled_codes - disabled_codes,
autofix_codes=options.autofix_codes - disabled_codes,
)

def __init__(
self, tree: ast.AST, lines: Sequence[str], filename: str | None = None
Expand Down Expand Up @@ -159,18 +181,19 @@ def from_source(
return plugin

def run(self) -> Iterable[Error]:
options = self.options
# when run as a flake8 plugin, flake8 handles suppressing errors from `noqa`.
# it's therefore important we don't suppress any errors for compatibility with
# flake8-noqa
if not self.standalone:
self.options.disable_noqa = True
options.disable_noqa = True

cst_runner = Flake8AsyncRunner_cst(self.options, self.module)
cst_runner = Flake8AsyncRunner_cst(options, self.module)
# any noqa'd errors are suppressed upon being generated
yield from cst_runner.run()

problems_ast = Flake8AsyncRunner.run(self._tree, self.options)
if self.options.disable_noqa:
problems_ast = Flake8AsyncRunner.run(self._tree, options)
if options.disable_noqa:
yield from problems_ast
return

Expand Down Expand Up @@ -244,7 +267,10 @@ def add_options(option_manager: OptionManager | ArgumentParser):
type=parse_per_file_disable,
default={},
required=False,
help=("..."),
help=(
"Disable codes for matching filenames. "
'Use one "glob->CODE,CODE" mapping per line.'
),
)
add_argument(
"--autofix",
Expand Down Expand Up @@ -425,6 +451,10 @@ def get_matching_codes(
anyio=options.anyio,
asyncio=options.asyncio,
disable_noqa=options.disable_noqa,
per_file_disable={
pattern: set(get_matching_codes(codes, all_codes))
for pattern, codes in options.per_file_disable.items()
},
)


Expand Down Expand Up @@ -458,14 +488,10 @@ def parse_async200_dict(raw_value: str) -> dict[str, str]:
return res


# not run if flake8 is installed
# TODO: this is not tested at all atm, I'm not even sure if it works
def parse_per_file_disable( # pragma: no cover
raw_value: str,
) -> dict[str, tuple[str, ...]]:
def parse_per_file_disable(raw_value: str) -> dict[str, tuple[str, ...]]:
res: dict[str, tuple[str, ...]] = {}
splitter = "->"
values = [s.strip() for s in raw_value.split(" \t\n") if s.strip()]
values = [s.strip() for s in raw_value.splitlines() if s.strip()]
for value in values:
split_values = list(map(str.strip, value.split(splitter)))
if len(split_values) != 2:
Expand All @@ -475,5 +501,9 @@ def parse_per_file_disable( # pragma: no cover
f"Invalid number ({len(split_values)-1}) of splitter "
f"tokens {splitter!r} in {value!r}"
)
res[split_values[0]] = tuple(split_values[1].split(","))
pattern, code_list = split_values
codes = tuple(comma_separated_list(code_list))
if not pattern or not codes:
raise ArgumentTypeError(f"Expected a file pattern and codes in {value!r}")
res[pattern] = res.get(pattern, ()) + codes
return res
3 changes: 2 additions & 1 deletion flake8_async/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from __future__ import annotations

from dataclasses import dataclass
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, NamedTuple

if TYPE_CHECKING:
Expand Down Expand Up @@ -36,6 +36,7 @@ class Options:
anyio: bool
asyncio: bool
disable_noqa: bool
per_file_disable: dict[str, set[str]] = field(default_factory=dict[str, set[str]])


class Statement(NamedTuple):
Expand Down
59 changes: 59 additions & 0 deletions tests/test_config_and_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,65 @@ def test_run_100_autofix(
assert_autofixed(tmp_path)


def test_run_flake8_async_per_file_disable(tmp_path: Path):
write_examplepy(tmp_path)
(tmp_path / "generated files").mkdir()
skipped = ["generated files/sample.py", "vendor.py"]
content = EXAMPLE_PY_TEXT + "trio.sleep(0)\n"
for name in skipped:
tmp_path.joinpath(name).write_text(content)

res = subprocess.run(
[
"flake8-async",
"--enable=ASYNC100,ASYNC115",
"--autofix=ASYNC100",
"--per-file-disable=generated files/*.py->ASYNC100\n"
"vendor.py->async10\nvendor.py->ASYNC115",
*skipped,
"./example.py",
],
cwd=tmp_path,
capture_output=True,
check=False,
text=True,
)
assert res.returncode == 1
assert not res.stderr
warnings = res.stdout.splitlines()
assert len(warnings) == 2
assert warnings[0].startswith("generated files/sample.py:4:1: ASYNC115 ")
assert warnings[1] == EXAMPLE_PY_ERROR.rstrip()
for name in skipped:
assert tmp_path.joinpath(name).read_text() == content
assert_autofixed(tmp_path)


@pytest.mark.skipif(flake8 is None, reason="flake8 is not installed")
@pytest.mark.parametrize(
"setting",
[
"per-file-ignores=ignored.py:ASYNC100",
"per-file-disable=\n ignored.py->ASYNC100",
],
)
def test_flake8_plugin_per_file_disable(tmp_path: Path, setting: str):
write_examplepy(tmp_path)
tmp_path.joinpath("ignored.py").write_text(EXAMPLE_PY_TEXT)
tmp_path.joinpath(".flake8").write_text(f"[flake8]\nselect=ASYNC100\n{setting}\n")

res = subprocess.run(
["flake8", "--config=.flake8", "./ignored.py", "./example.py"],
cwd=tmp_path,
capture_output=True,
check=False,
text=True,
)
assert res.returncode == 1
assert not res.stderr
assert res.stdout == EXAMPLE_PY_ERROR


def test_114_raises_on_invalid_parameter(capsys: pytest.CaptureFixture[str]):
plugin = Plugin(ast.AST(), [])
# argparse will reraise ArgumentTypeError as SystemExit
Expand Down
Loading