-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflake8_if_checker.py
231 lines (184 loc) · 6.83 KB
/
flake8_if_checker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import ast
import collections
import enum
from optparse import OptionConflictError
try:
# pylint:disable=unused-import
from argparse import Namespace
from flake8.options.manager import OptionManager
from typing import Dict, Iterator, List, Optional, Tuple, Union
# pylint:enable=unused-import
IfCheckerReportItem = Tuple[int, int, str, type] # pylint:disable=invalid-name
except ImportError: # pragma: no cover
pass
DEFAULT_MAX_IF_CONDITIONS = 2
Result = collections.namedtuple("Result", "type kind line col condition_count")
class IfCheckerErrors(enum.Enum):
IF01 = "IF01 Too many conditions ({condition_count}) in {type} {kind}"
class IfKind(enum.Enum):
IfExp = "Expression"
If = "Statement"
class IfType(enum.Enum):
IF = "IF"
ELIF = "ELIF"
class AstVisitor(object):
def __init__(self):
# type: () -> None
self._result_store = {} # type: Dict[Tuple[str, int, int], Result]
@property
def results(self):
# type: () -> Tuple[Result]
return tuple( # type:ignore
sorted(
self._result_store.values(),
key=lambda result: (result.line, result.col, result.kind),
)
)
def lookup(self, tree):
# type: (ast.Module) -> None
assert hasattr(tree, "body"), "tree must have `body` property"
self._visit_node(tree)
def _get_type(self, node):
# type: (ast.AST) -> str
return type(node).__name__
def _visit_node(self, node):
# type: (ast.AST) -> None
self.__visit_subtree(node, "body")
self.__visit_subtree(node, "orelse")
self.__visit_subtree(node, "test")
self.__visit_subtree(node, "value")
self.__visit_subtree(node, "values")
# Visiting: If statements & expression
if isinstance(node, (ast.If, ast.IfExp)):
self.__visit_if(node)
def __count_if(self, node):
# type: (ast.stmt) -> int
counter = 0
values = getattr(node, "values", [])
if isinstance(values, collections.Iterable):
for node_value in values:
node_type = self._get_type(node_value)
if node_type == "BoolOp":
counter += self.__count_if(node_value)
else:
counter += 1
return counter
def __visit_if(self, node):
# type: (Union[ast.If, ast.IfExp]) -> None
node_type = self._get_type(node)
node_line = node.lineno
node_col = node.col_offset
node_kind = IfKind[node_type].value
result_key = (node_kind, node_line, node_col)
node_test = getattr(node, "test")
test_values = getattr(node_test, "values", [])
if not test_values:
counter = 1
else:
counter = self.__count_if(node_test)
self._result_store[result_key] = Result(
type=None,
kind=node_kind,
line=node_line,
col=node_col,
condition_count=counter,
)
def __visit_subtree(self, node, subtree_name):
# type: (ast.AST, str) -> None
subtree = getattr(node, subtree_name, [])
if isinstance(subtree, collections.Iterable):
for subtree_item in subtree:
self._visit_node(subtree_item)
elif isinstance(subtree, ast.AST):
self._visit_node(subtree)
class IfChecker(object):
name = "flake8_if_checker"
version = "0.3.0"
IF_LEN = len("if ")
ELIF_LEN = len("elif ")
def __init__(self, tree, lines, options):
# type: (ast.Module, List[str], Namespace) -> None
self.tree = tree
self.lines = lines
self.options = options
@classmethod
def add_options(cls, parser): # pragma: no cover
# type: (OptionManager) -> None
flag = "--max-if-conditions"
kwargs = {
"default": DEFAULT_MAX_IF_CONDITIONS,
"metavar": "n",
"parse_from_config": "True",
"type": "int",
}
config_opts = getattr(parser, "config_options", None)
if isinstance(config_opts, list):
# Flake8 2.x
kwargs.pop("parse_from_config")
if flag[2:] not in parser.config_options:
parser.config_options.append(flag[2:])
try:
parser.add_option(flag, **kwargs)
except OptionConflictError:
pass
def run(self):
# type: () -> Iterator[IfCheckerReportItem]
tree = ast.fix_missing_locations(self.tree)
visitor = AstVisitor()
visitor.lookup(tree)
for result in visitor.results:
fixed_result = self._fix_result_item(result)
if self._has_if01_error(fixed_result):
yield self._format_report(
IfCheckerErrors.IF01, fixed_result # type:ignore
)
def _fix_result_item(self, result):
# type: (Result) -> Optional[Result]
# Add default IF type
kwargs = result._asdict()
try:
_type, _col = self._find_type_and_column( # type:ignore
self.lines[kwargs["line"] - 1], kwargs["col"]
)
except TypeError: # pragma: no cover
return None
kwargs["type"] = _type.value
kwargs["col"] = _col
return Result(**kwargs)
def _find_type_and_column(self, code_line, column): # noqa:C901
# type: (str, int) -> Optional[Tuple[IfType, int]]
def _find_result(value):
# type: (str) -> Optional[Tuple[IfType, int]]
if value.strip().startswith("elif"):
return IfType.ELIF, value.index("elif")
if value.strip().startswith("if"):
return IfType.IF, value.index("if")
if "if " in value and " else " in value:
return IfType.IF, value.index("if")
return None # pragma: no cover
if column == 0:
_maybe_result = _find_result(code_line)
if _maybe_result:
return _maybe_result
for substr_from in (column - self.ELIF_LEN, column - self.IF_LEN):
if substr_from < 0:
continue
_maybe_result = _find_result(code_line[substr_from:])
if _maybe_result:
_type, _col = _maybe_result
return _type, _col + substr_from
return None # pragma: no cover
def _has_if01_error(self, result):
# type: (Optional[Result]) -> bool
return (
result
and result.condition_count > self.options.max_if_conditions # type:ignore
)
def _format_report(self, error, result):
# type: (IfCheckerErrors, Result) -> IfCheckerReportItem
return (
result.line,
result.col,
error.value.format(**result._asdict()),
type(self),
)