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