/
flake8_holvi.py
318 lines (282 loc) · 12.4 KB
/
flake8_holvi.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# coding: utf-8
import ast
import pycodestyle
__version__ = '0.1.2'
python2_modules_map = {
# Python 2 module - six.moves counterpart
'__builtin__': 'builtins',
'BaseHTTPServer': 'BaseHTTPServer',
'ConfigParser': 'configparser',
'HTMLParser': 'html_parser',
'Queue': 'queue',
'SimpleHTTPServer': 'SimpleHTTPServer',
'cPickle': 'cPickle',
'cStringIO': 'cStringIO',
'cookielib': 'http_cookiejar',
'cookie': 'http_cookies',
'htmlentitydefs': 'html_entities',
'httplib': 'http_client',
'urlparse': 'urllib.parse',
}
python2_unittest_assertions = {
# Python 2 assertion - six counterpart
'assertItemsEqual': 'assertCountEqual',
'assertRaisesRegexp': 'assertRaisesRegex',
'assertRegexpMatches': 'assertRegex',
}
# TODO: make this configurable via CLI or flake8 config.
potential_implicit_relative_imports = {
'exceptions',
'models',
'serializers',
'signals',
'tasks',
'views',
# Holvi-specific modules:
'api',
'constants',
'providers',
}
def _detect_unicode_decode_error(value, encoding=None):
try:
if encoding:
unicode(value, encoding)
else:
unicode(value)
except UnicodeDecodeError:
return True
else:
return False
class HolviVisitor(ast.NodeVisitor):
messages = {
'warnings': {
'HLVW001': 'First argument of unicode() may contain non-ASCII characters. '
'We recommend passing encoding explicitly.',
'HLVW002': 'trying to decode str with ASCII encoding may not work',
},
'errors': {
'HLVE001': 'Import print_function __future__ import and use print().',
'HLVE002': 'unicode() is renamed to str() in Python 3. Use six.text_type() instead.',
'HLVE003': 'str() is renamed to bytes() in Python 3. Use six.binary_type() instead.',
'HLVE004': 'First argument of unicode() contains non-ASCII characters and it '
'will raise UnicodeDecodeError. Pass encoding explicitly.',
'HLVE005': 'First argument of unicode() contains non-ASCII characters and trying to '
'decode it to unicode with ASCII encoding will raise UnicodeDecodeError.',
'HLVE006': 'Do not use %%-formatting inside %s.%s().',
'HLVE007': 'Do not use str.format() inside %s.%s().',
'HLVE008': '%r must be passed to the lambda to avoid late binding issue in Python.',
'HLVE009': 'Replace Python 2-only import %r with six.moves.%s.',
'HLVE010': 'Replace Python 2-only unittest assertion %r with six.%s.',
'HLVE011': 'Replace implicit relative import %r with %r.',
'HLVE012': '%r cannot be found in lambda\'s default argument(s).',
}
}
def __init__(self, ignore_warnings=False):
self.ignore_warnings = ignore_warnings
self.violations = []
self.violation_codes = []
self._inside_for_node = None
def visit_Print(self, node):
self.report_error(node, 'HLVE001')
def visit_Call(self, node):
func = getattr(node, 'func', None)
func_name = getattr(func, 'id', None)
func_value = getattr(func, 'value', None)
# unicode(...)
if func and func_name == 'unicode':
self.report_error(node, 'HLVE002')
value = getattr(node.args[0], 's', None)
# unicode('non-ascıı')
if len(node.args) == 1 and isinstance(value, str):
if _detect_unicode_decode_error(value):
self.report_error(node, 'HLVE004')
else:
self.report_warning(node, 'HLVW001')
# unicode('ı', 'ascii')
elif len(node.args) == 2 and isinstance(value, str) and node.args[1].s == 'ascii':
if _detect_unicode_decode_error(value, 'ascii'):
self.report_error(node, 'HLVE005')
else:
self.report_warning(node, 'HLVW002')
# TODO: Detect unicode(..., encoding='...') too.
# str(...)
elif func and func_name == 'str':
self.report_error(node, 'HLVE003')
# TODO: str(u"aaaı")
# logging.debug('%s' % 'a')
# logger.error('%s' % 'a')
# logging.debug('{}'.format('a'))
# logger.warning('{}'.format('a'))
elif func and getattr(func_value, 'id', None) in ('logger', 'logging'):
logging_methods = ('debug', 'info', 'warning', 'error', 'critical', 'exception')
if getattr(func, 'attr', None) in logging_methods:
# %-format
if len(node.args) and isinstance(node.args[0], ast.BinOp):
self.report_error(node, 'HLVE006', args=(func_value.id, func.attr))
# str.format()
elif (
len(node.args) and isinstance(node.args[0], ast.Call)
and getattr(node.args[0].func, 'attr', None) == 'format'
):
self.report_error(node, 'HLVE007', args=(func_value.id, func.attr))
# Traverse all child nodes.
self.generic_visit(node)
def visit_For(self, node):
self._inside_for_node = node
self.generic_visit(node)
self._inside_for_node = None
def visit_Lambda(self, node):
if self._inside_for_node is not None:
if isinstance(node.body, ast.Call) and isinstance(node.body.func, ast.Attribute):
# Get the name of control variable from 'for <control_variable> in ...'.
if 'id' not in self._inside_for_node.target._fields: # pragma: no cover
# TODO: We don't support 'for i, j in ...' yet.
return
control_variable = self._inside_for_node.target.id
# Default arguments passed to lambda: 'lambda foo=foo: ...'
defaults = node.args.defaults
for arg in node.body.args:
# Check if arg is ast.List, ast.Tuple, or ast.Set.
if 'elts' in arg._fields:
elts = arg.elts
for e in elts:
# Look for ast.Attribute nodes.
if 'value' in e._fields and e.value.id == control_variable:
if len(defaults) == 0:
# control variable isn't passed to lambda.
self.report_error(node, 'HLVE008', args=(control_variable,))
elif len(defaults) > 0:
# There is a default argument passed, let's check it's used at all.
found = False
for d in defaults:
# TODO: check Attribute node for lambda foo=bar.baz: ...
# We only look for Name nodes now.
if 'id' in d._fields and d.id == control_variable:
found = True
break
if not found:
self.report_error(node, 'HLVE012', args=(control_variable,))
# Look for ast.Name nodes.
elif 'id' in e._fields and e.id == control_variable:
if len(defaults) == 0:
# Control variable isn't passed to lambda.
self.report_error(node, 'HLVE008', args=(control_variable,))
elif len(defaults) > 1: # pragma: no cover
assert False, 'implement this for ast.Tuple etc.'
# Check if arg is ast.Attribute.
elif 'value' in arg._fields:
if arg.value.id == control_variable:
if len(defaults) == 0:
# Control variable isn't passed to lambda.
self.report_error(node, 'HLVE008', args=(control_variable,))
elif len(defaults) > 1: # pragma: no cover
assert False, 'implement this for ast.Attribute'
# Check if arg is ast.Name.
elif 'id' in arg._fields:
if arg.id == control_variable:
if len(defaults) == 0:
# Control variable isn't passed to lambda.
self.report_error(node, 'HLVE008', args=(control_variable,))
elif len(defaults) > 1: # pragma: no cover
assert False, 'implement this for ast.Name'
self.generic_visit(node)
def visit_Attribute(self, node):
method_name = node.attr
if (
isinstance(node.value, ast.Name) and
node.value.id == 'self' and
method_name in python2_unittest_assertions
):
self.report_error(
node,
'HLVE010',
args=(method_name, python2_unittest_assertions[method_name]),
)
self.generic_visit(node)
def visit_Import(self, node):
for name in node.names:
mod_name = name.name
if mod_name in python2_modules_map:
self.report_error(
node,
'HLVE009',
args=(mod_name, python2_modules_map[mod_name]),
)
self.generic_visit(node)
def visit_ImportFrom(self, node):
mod_name = node.module
if mod_name in python2_modules_map:
self.report_error(
node,
'HLVE009',
args=(mod_name, python2_modules_map[mod_name]),
)
# Ignore explicit relative imports.
elif node.level == 0 and mod_name in potential_implicit_relative_imports:
self.report_error(
node,
'HLVE011',
args=(mod_name, '.%s' % mod_name),
)
self.generic_visit(node)
def report_error(self, node, code, args=None):
message = self.messages['errors'].get(code)
self._report_message(node, code, message, args)
def report_warning(self, node, code, args=None):
if self.ignore_warnings:
return
message = self.messages['warnings'].get(code)
self._report_message(node, code, message, args)
@staticmethod
def _format_message(code, message, args=None):
if args:
message = message % args
if message:
message = '%s %s' % (code, message)
return message
def _report_message(self, node, code, message, args=None):
message = self._format_message(code, message, args)
self.violations.append((
node.lineno,
node.col_offset,
message,
type(self),
))
self.violation_codes.append(code)
class HolviChecker(object):
name = 'flake8-holvi'
version = __version__
def __init__(self, tree, filename, lines):
self.tree = tree
self.filename = filename
self.lines = lines
# Default settings.
self.ignore_warnings = False
@classmethod
def add_options(cls, parser):
parser.add_option(
'--ignore-warnings',
action='store_true',
parse_from_config=True,
default=False,
help='Do not report checks added as warnings.'
)
@classmethod
def parse_options(cls, options):
cls.ignore_warnings = options.ignore_warnings
def load_file(self):
if self.filename in ('stdin', '-', None):
self.filename = 'stdin'
self.lines = pycodestyle.stdin_get_value().splitlines(True)
else:
self.lines = pycodestyle.readlines(self.filename)
def run(self):
if not self.tree and not self.lines:
self.load_file()
self.tree = ast.parse(''.join(self.lines))
visitor = HolviVisitor(self.ignore_warnings)
visitor.visit(self.tree)
for lineno, col_offset, message, rtype in visitor.violations:
if pycodestyle.noqa(self.lines[lineno - 1]):
continue
yield lineno, col_offset, message, rtype