violation.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. """Contains the Violation error class used internally."""
  2. from __future__ import annotations
  3. import functools
  4. import linecache
  5. import logging
  6. from typing import Match
  7. from typing import NamedTuple
  8. from flake8 import defaults
  9. from flake8 import utils
  10. LOG = logging.getLogger(__name__)
  11. @functools.lru_cache(maxsize=512)
  12. def _find_noqa(physical_line: str) -> Match[str] | None:
  13. return defaults.NOQA_INLINE_REGEXP.search(physical_line)
  14. class Violation(NamedTuple):
  15. """Class representing a violation reported by Flake8."""
  16. code: str
  17. filename: str
  18. line_number: int
  19. column_number: int
  20. text: str
  21. physical_line: str | None
  22. def is_inline_ignored(self, disable_noqa: bool) -> bool:
  23. """Determine if a comment has been added to ignore this line.
  24. :param disable_noqa:
  25. Whether or not users have provided ``--disable-noqa``.
  26. :returns:
  27. True if error is ignored in-line, False otherwise.
  28. """
  29. physical_line = self.physical_line
  30. # TODO(sigmavirus24): Determine how to handle stdin with linecache
  31. if disable_noqa:
  32. return False
  33. if physical_line is None:
  34. physical_line = linecache.getline(self.filename, self.line_number)
  35. noqa_match = _find_noqa(physical_line)
  36. if noqa_match is None:
  37. LOG.debug("%r is not inline ignored", self)
  38. return False
  39. codes_str = noqa_match.groupdict()["codes"]
  40. if codes_str is None:
  41. LOG.debug("%r is ignored by a blanket ``# noqa``", self)
  42. return True
  43. codes = set(utils.parse_comma_separated_list(codes_str))
  44. if self.code in codes or self.code.startswith(tuple(codes)):
  45. LOG.debug(
  46. "%r is ignored specifically inline with ``# noqa: %s``",
  47. self,
  48. codes_str,
  49. )
  50. return True
  51. LOG.debug(
  52. "%r is not ignored inline with ``# noqa: %s``", self, codes_str
  53. )
  54. return False