/
harvest.py
363 lines (303 loc) · 13.6 KB
/
harvest.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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
'''This module holds the base Harvester class and all its subclassess.'''
from builtins import super
import json
import collections
from radon.raw import analyze
from radon.metrics import h_visit, mi_visit, mi_rank
from radon.complexity import (cc_visit, sorted_results, cc_rank,
add_inner_blocks)
from radon.cli.colors import RANKS_COLORS, MI_RANKS, RESET
from radon.cli.tools import (iter_filenames, _open, cc_to_dict, dict_to_xml,
dict_to_codeclimate_issues, cc_to_terminal,
raw_to_dict, strip_ipython)
try:
import nbformat
import io
SUPPORTS_IPYNB = True
except ImportError:
SUPPORTS_IPYNB = False
class Harvester(object):
'''Base class defining the interface of a Harvester object.
A Harvester has the following lifecycle:
1. **Initialization**: `h = Harvester(paths, config)`
2. **Execution**: `r = h.results`. `results` holds an iterable object.
The first time `results` is accessed, `h.run()` is called. This method
should not be subclassed. Instead, the :meth:`gobble` method should be
implemented.
3. **Reporting**: the methods *as_json* and *as_xml* return a string
with the corrisponding format. The method *to_terminal* is a generator
that yields the lines to be printed in the terminal.
This class is meant to be subclasses and cannot be used directly, since
the methods :meth:`gobble`, :meth:`as_xml` and :meth:`to_terminal` are
not implemented.
'''
def __init__(self, paths, config):
'''Initialize the Harvester.
*paths* is a list of paths to analyze.
*config* is a :class:`~radon.cli.Config` object holding the
configuration values specific to the Harvester.
'''
self.paths = paths
self.config = config
self._results = []
def _iter_filenames(self):
'''A wrapper around :func:`~radon.cli.tools.iter_filenames`.'''
return iter_filenames(self.paths, self.config.exclude,
self.config.ignore)
def gobble(self, fobj):
'''Subclasses must implement this method to define behavior.
This method is called for every file to analyze. *fobj* is the file
object. This method should return the results from the analysis,
preferably a dictionary.
'''
raise NotImplementedError
def run(self):
'''Start the analysis. For every file, this method calls the
:meth:`gobble` method. Results are yielded as tuple:
``(filename, analysis_results)``.
'''
for name in self._iter_filenames():
with _open(name) as fobj:
try:
if name.endswith('.ipynb'):
if SUPPORTS_IPYNB and self.config.include_ipynb:
nb = nbformat.read(fobj, as_version=nbformat.NO_CONVERT)
cells = [cell.source for cell in nb.cells if cell.cell_type == 'code']
# Whole document
doc = "\n".join(cells)
yield (name, self.gobble(io.StringIO(strip_ipython(doc))))
if self.config.ipynb_cells:
# Individual cells
cellid = 0
for source in cells:
yield ("{0}:[{1}]".format(name, cellid), self.gobble(io.StringIO(strip_ipython(source))))
cellid += 1
else:
yield (name, self.gobble(fobj))
except Exception as e:
yield (name, {'error': str(e)})
@property
def results(self):
'''This property holds the results of the analysis.
The first time it is accessed, an iterator is returned. Its
elements are cached into a list as it is iterated over. Therefore, if
`results` is accessed multiple times after the first one, a list will
be returned.
'''
def caching_iterator(it, r):
'''An iterator that caches another iterator.'''
for t in it:
yield t
r.append(t)
if self._results:
return self._results
return caching_iterator(self.run(), self._results)
def as_json(self):
'''Format the results as JSON.'''
return json.dumps(dict(self.results))
def as_xml(self):
'''Format the results as XML.'''
raise NotImplementedError
def as_codeclimate_issues(self):
'''Format the results as Code Climate issues.'''
raise NotImplementedError
def to_terminal(self):
'''Yields tuples representing lines to be printed to a terminal.
The tuples have the following format: ``(line, args, kwargs)``.
The line is then formatted with `line.format(*args, **kwargs)`.
'''
raise NotImplementedError
class CCHarvester(Harvester):
'''A class that analyzes Python modules' Cyclomatic Complexity.'''
def gobble(self, fobj):
'''Analyze the content of the file object.'''
r = cc_visit(fobj.read(), no_assert=self.config.no_assert)
if self.config.show_closures:
r = add_inner_blocks(r)
return sorted_results(r, order=self.config.order)
def _to_dicts(self):
'''Format the results as a dictionary of dictionaries.'''
result = {}
for key, data in self.results:
if 'error' in data:
result[key] = data
continue
values = [v for v in map(cc_to_dict, data)
if self.config.min <= v['rank'] <= self.config.max]
if values:
result[key] = values
return result
def as_json(self):
'''Format the results as JSON.'''
return json.dumps(self._to_dicts())
def as_xml(self):
'''Format the results as XML. This is meant to be compatible with
Jenkin's CCM plugin. Therefore not all the fields are kept.
'''
return dict_to_xml(self._to_dicts())
def as_codeclimate_issues(self):
'''Format the result as Code Climate issues.'''
return dict_to_codeclimate_issues(self._to_dicts(), self.config.min)
def to_terminal(self):
'''Yield lines to be printed in a terminal.'''
average_cc = .0
analyzed = 0
for name, blocks in self.results:
if 'error' in blocks:
yield name, (blocks['error'],), {'error': True}
continue
res, cc, n = cc_to_terminal(blocks, self.config.show_complexity,
self.config.min, self.config.max,
self.config.total_average)
average_cc += cc
analyzed += n
if res:
yield name, (), {}
yield res, (), {'indent': 1}
if (self.config.average or self.config.total_average) and analyzed:
cc = average_cc / analyzed
ranked_cc = cc_rank(cc)
yield ('\n{0} blocks (classes, functions, methods) analyzed.',
(analyzed,), {})
yield ('Average complexity: {0}{1} ({2}){3}',
(RANKS_COLORS[ranked_cc], ranked_cc, cc, RESET), {})
class RawHarvester(Harvester):
'''A class that analyzes Python modules' raw metrics.'''
headers = ['LOC', 'LLOC', 'SLOC', 'Comments', 'Single comments', 'Multi',
'Blank']
def gobble(self, fobj):
'''Analyze the content of the file object.'''
return raw_to_dict(analyze(fobj.read()))
def as_xml(self):
'''Placeholder method. Currently not implemented.'''
raise NotImplementedError('RawHarvester: cannot export results as XML')
def to_terminal(self):
'''Yield lines to be printed to a terminal.'''
sum_metrics = collections.defaultdict(int)
for path, mod in self.results:
if 'error' in mod:
yield path, (mod['error'],), {'error': True}
continue
yield path, (), {}
for header in self.headers:
value = mod[header.lower().replace(' ', '_')]
yield '{0}: {1}', (header, value), {'indent': 1}
sum_metrics[header] += value
loc, comments = mod['loc'], mod['comments']
yield '- Comment Stats', (), {'indent': 1}
yield ('(C % L): {0:.0%}', (comments / (float(loc) or 1),),
{'indent': 2})
yield ('(C % S): {0:.0%}', (comments / (float(mod['sloc']) or 1),),
{'indent': 2})
yield ('(C + M % L): {0:.0%}',
((comments + mod['multi']) / (float(loc) or 1),),
{'indent': 2})
if self.config.summary:
_get = lambda k, v=0: sum_metrics.get(k, v)
comments = float(_get('Comments'))
yield '** Total **', (), {}
for header in self.headers:
yield '{0}: {1}', (header, sum_metrics[header]), {'indent': 1}
yield '- Comment Stats', (), {'indent': 1}
yield (
'(C % L): {0:.0%}',
(comments / (_get('LOC', 1) or 1),),
{'indent': 2},
)
yield (
'(C % S): {0:.0%}',
(comments / (_get('SLOC', 1) or 1),),
{'indent': 2},
)
yield (
'(C + M % L): {0:.0%}',
(float(_get('Comments', 0) + _get('Multi')) /
(_get('LOC', 1) or 1),),
{'indent': 2},
)
class MIHarvester(Harvester):
'''A class that analyzes Python modules' Maintainability Index.'''
def gobble(self, fobj):
'''Analyze the content of the file object.'''
mi = mi_visit(fobj.read(), self.config.multi)
rank = mi_rank(mi)
return {'mi': mi, 'rank': rank}
@property
def filtered_results(self):
'''Filter results with respect with their rank.'''
for key, value in self.results:
if ('error' in value or
self.config.min <= value['rank'] <= self.config.max):
yield (key, value)
def _sort(self, results):
if self.config.sort:
return sorted(results, key=lambda el: el[1]['mi'])
return results
def as_json(self):
'''Format the results as JSON.'''
return json.dumps(dict(self.filtered_results))
def as_xml(self):
'''Placeholder method. Currently not implemented.'''
raise NotImplementedError('Cannot export results as XML')
def to_terminal(self):
'''Yield lines to be printed to a terminal.'''
for name, mi in self._sort(self.filtered_results):
if 'error' in mi:
yield name, (mi['error'],), {'error': True}
continue
rank = mi['rank']
color = MI_RANKS[rank]
to_show = ''
if self.config.show:
to_show = ' ({0:.2f})'.format(mi['mi'])
yield '{0} - {1}{2}{3}{4}', (name, color, rank, to_show, RESET), {}
class HCHarvester(Harvester):
"""Computes the Halstead Complexity of Python modules."""
def __init__(self, paths, config):
super().__init__(paths, config)
self.by_function = config.by_function
def gobble(self, fobj):
"""Analyze the content of the file object."""
code = fobj.read()
return h_visit(code)
def as_json(self):
"""Format the results as JSON."""
result_dict = self._to_dicts()
return json.dumps(result_dict)
def to_terminal(self):
"""Yield lines to be printed to the terminal."""
if self.by_function:
for name, res in self.results:
yield "{}:".format(name), (), {}
for (name, report) in res.functions:
yield "{}:".format(name), (), {"indent": 1}
for msg in hal_report_to_terminal(report, 1):
yield msg
else:
for name, res in self.results:
yield "{}:".format(name), (), {}
for msg in hal_report_to_terminal(res.total, 0):
yield msg
def _to_dicts(self):
'''Format the results as a dictionary of dictionaries.'''
result = {}
for filename, results in self.results:
if 'error' in results:
result[filename] = results
else:
result[filename] = results._asdict()
return result
def hal_report_to_terminal(report, base_indent=0):
"""Yield lines from the HalsteadReport to print to the terminal."""
yield "h1: {}".format(report.h1), (), {"indent": 1 + base_indent}
yield "h2: {}".format(report.h2), (), {"indent": 1 + base_indent}
yield "N1: {}".format(report.N1), (), {"indent": 1 + base_indent}
yield "N2: {}".format(report.N2), (), {"indent": 1 + base_indent}
yield "vocabulary: {}".format(report.vocabulary), (), {"indent": 1 + base_indent}
yield "length: {}".format(report.length), (), {"indent": 1 + base_indent}
yield "calculated_length: {}".format(report.calculated_length), (), {"indent": 1 + base_indent}
yield "volume: {}".format(report.volume), (), {"indent": 1 + base_indent}
yield "difficulty: {}".format(report.difficulty), (), {"indent": 1 + base_indent}
yield "effort: {}".format(report.effort), (), {"indent": 1 + base_indent}
yield "time: {}".format(report.time), (), {"indent": 1 + base_indent}
yield "bugs: {}".format(report.bugs), (), {"indent": 1 + base_indent}