From 5b12e61872448658608e8673653f86c36646276c Mon Sep 17 00:00:00 2001 From: Boulea7 <145515129+Boulea7@users.noreply.github.com> Date: Thu, 3 Dec 2026 14:16:28 +0800 Subject: [PATCH] Apply per-file code suppression in flake8-async --- docs/usage.rst | 24 ++++++++++++++ flake8_async/__init__.py | 58 +++++++++++++++++++++++++--------- flake8_async/base.py | 3 +- tests/test_config_and_args.py | 59 +++++++++++++++++++++++++++++++++++ 4 files changed, 129 insertions(+), 15 deletions(-) diff --git a/docs/usage.rst b/docs/usage.rst index 00e092f..849e31e 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -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`` diff --git a/flake8_async/__init__.py b/flake8_async/__init__.py index ab66ef4..305c103 100644 --- a/flake8_async/__init__.py +++ b/flake8_async/__init__.py @@ -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 @@ -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 @@ -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 @@ -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", @@ -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() + }, ) @@ -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: @@ -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 diff --git a/flake8_async/base.py b/flake8_async/base.py index 43f31a3..a6ec547 100644 --- a/flake8_async/base.py +++ b/flake8_async/base.py @@ -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: @@ -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): diff --git a/tests/test_config_and_args.py b/tests/test_config_and_args.py index 5547e49..7a04b11 100644 --- a/tests/test_config_and_args.py +++ b/tests/test_config_and_args.py @@ -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