forked from terryyin/lizard
/
lizard.py
executable file
·808 lines (687 loc) · 29.1 KB
/
lizard.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
#!/usr/bin/env python
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# author: terry@odd-e.com
# Website: www.lizard.ws
#
"""
lizard is an extensible Cyclomatic Complexity Analyzer for many programming
languages including C/C++ (doesn't require all the header files).
For more information visit http://www.lizard.ws
"""
from __future__ import print_function, division
import sys
import itertools
import re
import os
from fnmatch import fnmatch
import hashlib
if sys.version[0] == '2':
from future_builtins import map, filter # pylint: disable=W0622, F0401
try:
from lizard_languages import languages, get_reader_for, CLikeReader
except ImportError:
sys.stderr.write("Cannot find the lizard_languages module.")
sys.exit(2)
try:
from lizard_ext import print_xml
from lizard_ext import html_output
except ImportError:
pass
VERSION = "1.12.0"
DEFAULT_CCN_THRESHOLD, DEFAULT_WHITELIST, \
DEFAULT_MAX_FUNC_LENGTH = 15, "whitelizard.txt", 1000
def analyze(paths, exclude_pattern=None, threads=1, exts=None, lans=None):
'''
returns an iterator of file information that contains function
statistics.
'''
exclude_pattern = exclude_pattern or []
extensions = exts or []
files = get_all_source_files(paths, exclude_pattern, lans)
file_analyzer = FileAnalyzer(extensions)
return map_files_to_analyzer(files, file_analyzer, threads)
def _extension_arg(parser):
parser.add_argument("-E", "--extension",
help='''User the extensions. The available extensions
are: -Ecpre: it will ignore code in the #else branch.
-Ewordcount: count word frequencies and generate tag
cloud. -Efans: count the fan in and fan out of
functions. -Eoutside: include the global code as one
function. -EIgnoreAssert: to ignore all code in
assert''',
action="append",
dest="extensions",
default=[])
def arg_parser(prog=None):
from argparse import ArgumentParser, Action, ArgumentError
class DictAction(Action): # pylint: disable=R0903
def __init__(self, option_strings, dest, nargs=None, **kwargs):
super(DictAction, self).__init__(option_strings, dest, **kwargs)
def __call__(self, parser, namespace, value, option_string=None):
if not re.match(r"\s*\w+\s*=\s*\d+", value):
raise ArgumentError(self, "should be like nloc=20")
k, val = value.split("=", 2)
getattr(namespace, self.dest)[k.strip()] = int(val.strip())
parser = ArgumentParser(prog=prog)
parser.add_argument('paths', nargs='*', default=['.'],
help='list of the filename/paths.')
parser.add_argument('--version', action='version', version=VERSION)
parser.add_argument("-l", "--languages",
help='''List the programming languages you want to
analyze. if left empty, it'll search for all languages
it knows. `lizard -l cpp -l java`searches for C++ and
Java code. The available languages are:
''' + ', '.join(x.language_names[0] for x in languages()),
action="append",
dest="languages",
default=[])
parser.add_argument("-V", "--verbose",
help="Output in verbose mode (long function name)",
action="store_true",
dest="verbose",
default=False)
parser.add_argument("-C", "--CCN",
help='''Threshold for cyclomatic complexity number
warning. The default value is %d.
Functions with CCN bigger than it will generate warning
''' % DEFAULT_CCN_THRESHOLD,
type=int,
dest="CCN",
default=DEFAULT_CCN_THRESHOLD)
parser.add_argument("-L", "--length",
help='''Threshold for maximum function length
warning. The default value is %d.
Functions length bigger than it will generate warning
''' % DEFAULT_MAX_FUNC_LENGTH,
type=int,
dest="length",
default=DEFAULT_MAX_FUNC_LENGTH)
parser.add_argument("-a", "--arguments",
help="Limit for number of parameters",
type=int, dest="arguments", default=100)
parser.add_argument("-w", "--warnings_only",
help='''Show warnings only, using clang/gcc's warning
format for printing warnings.
http://clang.llvm.org/docs/UsersManual.html#cmdoption-fdiagnostics-format
''',
action="store_const",
const=print_clang_style_warning,
dest="printer")
parser.add_argument("-i", "--ignore_warnings",
help='''If the number of warnings is equal or less
than the number,
the tool will exit normally, otherwise it will generate
error. Useful in makefile for legacy code.''',
type=int,
dest="number",
default=0)
parser.add_argument("-x", "--exclude",
help='''Exclude files that match this pattern. * matches
everything,
? matches any single character, "./folder/*" exclude
everything in the folder recursively. Multiple patterns
can be specified. Don't forget to add "" around the
pattern.''',
action="append",
dest="exclude",
default=[])
parser.add_argument("-t", "--working_threads",
help='''number of working threads. The default
value is 1. Using a bigger
number can fully utilize the CPU and often faster.''',
type=int,
dest="working_threads",
default=1)
parser.add_argument("-X", "--xml",
help='''Generate XML in cppncss style instead of the
tabular output. Useful to generate report in Jenkins
server''',
action="store_const",
const=print_xml,
dest="printer")
parser.add_argument("-H", "--html",
help='''Output HTML report''',
action="store_const",
const=html_output,
dest="printer")
parser.add_argument("-m", "--modified",
help="Calculate modified cyclomatic complexity number",
action="append_const",
const="modified",
dest="extensions",
default=[])
_extension_arg(parser)
parser.add_argument("-s", "--sort",
help='''Sort the warning with field. The field can be
nloc, cyclomatic_complexity, token_count,
p#arameter_count, etc. Or an customized field.''',
action="append",
dest="sorting",
default=[])
parser.add_argument("-T", "--Threshold",
help='''Set the limit for a field. The field can be
nloc, cyclomatic_complexity, token_count,
parameter_count, etc. Or an customized file. Lizard
will report warning if a function exceed the limit''',
action=DictAction,
dest="thresholds",
default={})
parser.add_argument("-W", "--whitelist",
help='''The path and file name to the whitelist file.
It's './whitelizard.txt' by default.
Find more information in README.''',
type=str,
dest="whitelist",
default=DEFAULT_WHITELIST)
parser.usage = '''lizard [options] [PATH or FILE] [PATH] ...'''
parser.description = __doc__
return parser
class FunctionInfo(object): # pylint: disable=R0902
def __init__(self, name, filename, start_line=0, ccn=1):
self.cyclomatic_complexity = ccn
self.nloc = 1
self.token_count = 1 # the first token
self.name = name
self.long_name = name
self.start_line = start_line
self.end_line = start_line
self.parameters = []
self.filename = filename
self.indent = -1
self.length = 0
self.fan_in = 0
self.fan_out = 0
location = property(lambda self:
" %(name)s@%(start_line)s-%(end_line)s@%(filename)s"
% self.__dict__)
parameter_count = property(lambda self: len(self.parameters))
def add_to_function_name(self, app):
self.name += app
self.long_name += app
def add_to_long_name(self, app):
self.long_name += app
def add_parameter(self, token):
self.add_to_long_name(" " + token)
if not self.parameters or token == ",":
self.parameters.append(token)
else:
self.parameters[-1] = token
class FileInformation(object): # pylint: disable=R0903
def __init__(self, filename, nloc, function_list=None):
self.filename = filename
self.nloc = nloc
self.function_list = function_list or []
self.token_count = 0
average_nloc = property(lambda self: self.functions_average("nloc"))
average_token_count = property(
lambda self: self.functions_average("token_count"))
average_cyclomatic_complexity = property(
lambda self: self.functions_average("cyclomatic_complexity"))
CCN = property(
lambda self:
sum(fun.cyclomatic_complexity for fun in self.function_list))
ND = property( # pylint: disable=C0103
lambda self:
sum(fun.max_nesting_depth for fun in self.function_list))
def functions_average(self, att):
summary = sum(getattr(fun, att) for fun in self.function_list)
return summary / len(self.function_list) if self.function_list else 0
class NestingStack(object):
def __init__(self):
self.nesting_stack = []
def with_namespace(self, name):
return '::'.join([x for x in self.nesting_stack if x] + [name])
def add_nesting(self, token):
self.nesting_stack.append(token)
def pop_nesting(self):
if self.nesting_stack:
self.nesting_stack.pop()
def current_nesting_level(self):
len(self.nesting_stack)
class FileInfoBuilder(object):
'''
The builder is also referred as "context" in the code,
because each language readers use this builder to build
source file and function information and the builder keep
the context information that's needed for the building.
'''
def __init__(self, filename):
self.fileinfo = FileInformation(filename, 0)
self.current_line = 0
self.forgive = False
self.newline = True
self.global_pseudo_function = FunctionInfo('*global*', filename, 0)
self.current_function = self.global_pseudo_function
self._nesting_stack = NestingStack()
def __getattr__(self, attr):
# delegating to _nesting_stack
return getattr(self._nesting_stack, attr)
def add_nloc(self, count):
self.fileinfo.nloc += count
self.current_function.nloc += count
self.current_function.end_line = self.current_line
self.current_function.length = \
self.current_line - self.current_function.start_line + 1
self.newline = count > 0
def start_new_function(self, name):
self.current_function = FunctionInfo(
self.with_namespace(name),
self.fileinfo.filename,
self.current_line)
def add_condition(self, inc=1):
self.current_function.cyclomatic_complexity += inc
def reset_complexity(self):
self.current_function.cyclomatic_complexity = 1
def add_to_long_function_name(self, app):
self.current_function.add_to_long_name(app)
def add_to_function_name(self, app):
self.current_function.add_to_function_name(app)
def parameter(self, token):
self.current_function.add_parameter(token)
def end_of_function(self):
if not self.forgive:
self.fileinfo.function_list.append(self.current_function)
self.forgive = False
self.current_function = self.global_pseudo_function
def preprocessing(tokens, reader):
if hasattr(reader, "preprocess"):
return reader.preprocess(tokens)
else:
return (t for t in tokens if not t.isspace() or t == '\n')
def comment_counter(tokens, reader):
for token in tokens:
comment = reader.get_comment_from_token(token)
if comment is not None:
for _ in comment.splitlines()[1:]:
yield '\n'
if comment.strip().startswith("#lizard forgive"):
reader.context.forgive = True
else:
yield token
def line_counter(tokens, reader):
context = reader.context
context.current_line = 1
newline = 1
for token in tokens:
if token != "\n":
count = token.count('\n')
context.current_line += count
context.add_nloc(count + newline)
newline = 0
yield token
else:
context.current_line += 1
newline = 1
def token_counter(tokens, reader):
context = reader.context
for token in tokens:
context.fileinfo.token_count += 1
context.current_function.token_count += 1
yield token
def condition_counter(tokens, reader):
conditions = reader.conditions
for token in tokens:
if token in conditions:
reader.context.add_condition()
yield token
class FileAnalyzer(object): # pylint: disable=R0903
def __init__(self, extensions):
self.processors = extensions
def __call__(self, filename):
try:
return self.analyze_source_code(
filename, open(filename, 'rU').read())
except UnicodeDecodeError:
sys.stderr.write("Error: doesn't support none utf encoding '%s'\n"
% filename)
except IOError:
sys.stderr.write("Error: Fail to read source file '%s'\n"
% filename)
except IndexError:
sys.stderr.write("Error: Fail to parse file '%s'\n"
% filename)
raise
def analyze_source_code(self, filename, code):
context = FileInfoBuilder(filename)
reader = (get_reader_for(filename) or CLikeReader)(context)
tokens = reader.generate_tokens(code)
for processor in self.processors:
tokens = processor(tokens, reader)
for _ in reader(tokens, reader):
pass
return context.fileinfo
def warning_filter(option, module_infos):
for file_info in module_infos:
if file_info:
for fun in file_info.function_list:
if any(getattr(fun, attr) > limit for attr, limit in
option.thresholds.items()):
yield fun
def whitelist_filter(warnings, script=None, whitelist=None):
def _get_whitelist_item(script):
white = {}
pieces = script.replace('::', '##').split(':')
if len(pieces) > 1:
white['file_name'] = pieces[0]
script = pieces[1]
white['function_names'] = (
[x.strip().replace('##', '::') for x in script.split(',')])
return white
def _in_list(warning):
return any(_match_whitelist_item(white, warning)
for white in whitelist)
def _match_whitelist_item(white, warning):
return (warning.name in white['function_names'] and
warning.filename == white.get('file_name', warning.filename))
def get_whitelist(whitelist):
if os.path.isfile(whitelist):
return open(whitelist, mode='r').read()
elif whitelist != DEFAULT_WHITELIST:
print("WARNING: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print("WARNING: the whitelist \""+whitelist+"\" doesn't exist.")
return ''
if not script:
script = get_whitelist(whitelist)
whitelist = [
_get_whitelist_item(line.split('#')[0])
for line in script.splitlines()]
for warning in warnings:
if not _in_list(warning):
yield warning
class OutputScheme(object):
def __init__(self, ext):
self.extensions = ext
self.items = [
{
'caption': " NLOC ", 'value': "nloc",
'avg_caption': ' Avg.NLOC '},
{
'caption': " CCN ", 'value': "cyclomatic_complexity",
'avg_caption': ' AvgCCN '},
{
'caption': " token ", 'value': "token_count",
'avg_caption': ' Avg.token '},
{'caption': " PARAM ", 'value': "parameter_count"},
{'caption': " length ", 'value': "length"},
] + [
{
'caption': caption,
'value': part,
'avg_caption': average
}
for caption, part, average in self._ext_member_info()]
self.items.append({'caption': " location ", 'value': 'location'})
@staticmethod
def is_string_instance(ext):
try:
stringtype = basestring
except NameError: # Not compatible with python 3
stringtype = str
return isinstance(ext.FUNCTION_INFO_PART, stringtype)
def _ext_member_info(self):
for ext in self.extensions:
if hasattr(ext, "FUNCTION_CAPTION"):
if OutputScheme.is_string_instance(ext):
yield (ext.FUNCTION_CAPTION,
ext.FUNCTION_INFO_PART,
getattr(ext, "AVERAGE_CAPTION", None))
else:
for i in range(len(ext.FUNCTION_CAPTION)):
yield (ext.FUNCTION_CAPTION[i],
ext.FUNCTION_INFO_PART[i],
getattr(ext, "AVERAGE_CAPTION", [None]*10)[i])
def captions(self):
return "".join(item['caption'] for item in self.items)
def function_info_head(self):
captions = self.captions()
return "\n".join(("=" * len(captions), captions, "-" * len(captions)))
def function_info(self, fun):
return ''.join(
str(getattr(fun, item['value'])).rjust(len(item['caption']))
for item in self.items)
def average_captions(self):
return "".join([
e['avg_caption'] for e in self.items
if e.get("avg_caption", None)])
def average_formatter(self):
return "".join([
"{{module.average_{ext[value]}:{size}.1f}}"
.format(ext=e, size=len(e['avg_caption']))
for e in self.items
if e.get("avg_caption", None)])
def clang_warning_format(self):
return (
"{f.filename}:{f.start_line}: warning: {f.name} has " +
", ".join([
"{{f.{ext[value]}}} {caption}"
.format(ext=e, caption=e['caption'].strip())
for e in self.items[:-1]
]))
def print_warnings(option, scheme, warnings):
warning_count = 0
warning_nloc = 0
warn_str = "!!!! Warnings ({0}) !!!!".format(
' or '.join("{0} > {1}".format(
k, val) for k, val in option.thresholds.items()))
print("\n" + "=" * len(warn_str) + "\n" + warn_str)
print(scheme.function_info_head())
for warning in warnings:
warning_count += 1
warning_nloc += warning.nloc
print(scheme.function_info(warning))
return warning_count, warning_nloc
def print_total(warning_count, warning_nloc, saved_result, scheme):
file_infos = list(file_info for file_info in saved_result if file_info)
all_fun = list(itertools.chain(*(file_info.function_list
for file_info in file_infos)))
cnt = len(all_fun) or 1
nloc_in_functions = sum([f.nloc for f in all_fun]) or 1
all_in_one = FileInformation(
"",
sum([f.nloc for f in file_infos]),
all_fun)
print("=" * 90)
print("Total nloc " + scheme.average_captions() + " Fun Cnt Warning"
" cnt Fun Rt nloc Rt")
print("-" * 90)
print((
"{module.nloc:10d}" +
scheme.average_formatter() +
"{function_count:9d}{warning_count:13d}" +
"{function_rate:10.2f}{nloc_rate:8.2f}").format(
module=all_in_one,
function_count=cnt,
warning_count=warning_count,
function_rate=(warning_count/cnt),
nloc_rate=(warning_nloc/nloc_in_functions)))
def print_and_save_modules(all_modules, extensions, scheme):
all_functions = []
print(scheme.function_info_head())
for module_info in all_modules:
for extension in extensions:
if hasattr(extension, 'reduce'):
extension.reduce(module_info)
if hasattr(extension, 'fans'):
extension.fans(module_info)
if module_info:
all_functions.append(module_info)
for fun in module_info.function_list:
print(scheme.function_info(fun))
print("--------------------------------------------------------------")
print("%d file analyzed." % (len(all_functions)))
print("==============================================================")
print("NLOC " + scheme.average_captions() + " function_cnt file")
print("--------------------------------------------------------------")
for module_info in all_functions:
print((
"{module.nloc:7d}" +
scheme.average_formatter() +
"{function_count:10d}" +
" {module.filename}").format(
module=module_info,
function_count=len(module_info.function_list)))
return all_functions
def get_warnings(code_infos, option):
warnings = whitelist_filter(warning_filter(option, code_infos),
whitelist=option.whitelist)
if isinstance(option.sorting, list) and len(option.sorting) > 0:
warnings = sorted(warnings, reverse=True, key=lambda x: getattr(
x, option.sorting[0]))
return warnings
def print_result(result, option, scheme):
result = print_and_save_modules(result, option.extensions, scheme)
warnings = get_warnings(result, option)
warning_count, warning_nloc = print_warnings(option, scheme, warnings)
print_total(warning_count, warning_nloc, result, scheme)
for extension in option.extensions:
if hasattr(extension, 'print_result'):
extension.print_result()
return warning_count
def print_clang_style_warning(code_infos, option, scheme):
count = 0
for warning in get_warnings(code_infos, option):
print(scheme.clang_warning_format().format(f=warning))
count += 1
return count
def get_map_method(working_threads):
try:
if working_threads == 1:
raise ImportError
import multiprocessing
pool = multiprocessing.Pool(processes=working_threads)
return pool.imap_unordered
except ImportError:
return map
def map_files_to_analyzer(files, file_analyzer, working_threads):
mapmethod = get_map_method(working_threads)
return mapmethod(file_analyzer, files)
def md5_hash_file(full_path_name):
''' return md5 hash of a file '''
try:
with open(full_path_name, mode='r') as source_file:
if sys.version_info[0] == 3:
code_md5 = hashlib.md5(source_file.read().encode('utf-8'))
else:
code_md5 = hashlib.md5(source_file.read())
return code_md5.hexdigest()
except IOError:
return None
except UnicodeDecodeError:
return None
def get_all_source_files(paths, exclude_patterns, lans):
'''
Function counts md5 hash for the given file and checks if it isn't a
duplicate using set of hashes for previous files '''
hash_set = set()
def _support(reader):
return not lans or set(lans).intersection(
reader.language_names)
def _validate_file(pathname):
return (
pathname in paths or (
get_reader_for(pathname) and
_support(get_reader_for(pathname)) and
all(not fnmatch(pathname, p) for p in exclude_patterns) and
_not_duplicate(pathname)))
def _not_duplicate(full_path_name):
fhash = md5_hash_file(full_path_name)
if not fhash or fhash not in hash_set:
hash_set.add(fhash)
return True
def all_listed_files(paths):
for path in paths:
if os.path.isfile(path):
yield path
else:
for root, _, files in os.walk(path, topdown=False):
for filename in files:
yield os.path.join(root, filename)
return filter(_validate_file, all_listed_files(paths))
def parse_args(argv):
def extend_parser(parser_to_extend):
from argparse import ArgumentParser, Action, ArgumentError
parser = ArgumentParser(add_help=False)
_extension_arg(parser)
opt, _ = parser.parse_known_args(args=argv[1:])
extensions = get_extensions(opt.extensions)
for ext in extensions:
if hasattr(ext, "set_args"):
ext.set_args(parser_to_extend) # pylint: disable=E1101
return parser_to_extend
parser = extend_parser(arg_parser(argv[0]))
opt = parser.parse_args(args=argv[1:])
opt.extensions = get_extensions(opt.extensions)
values = [item['value'] for item in OutputScheme(opt.extensions).items]
no_fields = (set(opt.sorting) | set(opt.thresholds.keys())) - set(values)
if no_fields:
error_message = "Wrong field name '%s'.\n" % ", ".join(no_fields)
error_message += "Candidates are: " + ', '.join(values) + "\n"
sys.stderr.write(error_message)
sys.exit(2)
if "cyclomatic_complexity" not in opt.thresholds:
opt.thresholds["cyclomatic_complexity"] = opt.CCN
if "max_nesting_depth" not in opt.thresholds and hasattr(opt, "ND"):
opt.thresholds["max_nesting_depth"] = opt.ND
if "length" not in opt.thresholds:
opt.thresholds["length"] = opt.length
if "parameter_count" not in opt.thresholds:
opt.thresholds["parameter_count"] = opt.arguments
return opt
def patch_extension(ext):
def _patch(name):
setattr(FileInformation, "average_" + name,
property(lambda self: self.functions_average(name)))
if hasattr(ext, "AVERAGE_CAPTION"):
if OutputScheme.is_string_instance(ext):
_patch(ext.FUNCTION_INFO_PART)
else:
for name in ext.FUNCTION_INFO_PART:
_patch(name)
return ext
def get_extensions(extension_names):
from importlib import import_module as im
def expand_extensions(existing):
for name in extension_names:
ext = patch_extension(
im('lizard_ext.lizard' + name.lower())
.LizardExtension()
if isinstance(name, str) else name)
existing.insert(
len(existing) if not hasattr(ext, "ordering_index") else
ext.ordering_index,
ext)
return existing
return expand_extensions([
preprocessing,
comment_counter,
line_counter,
token_counter,
condition_counter,
])
analyze_file = FileAnalyzer(get_extensions([])) # pylint: disable=C0103
def lizard_main(argv):
options = parse_args(argv)
printer = options.printer or print_result
result = analyze(
options.paths,
options.exclude,
options.working_threads,
options.extensions,
options.languages)
warning_count = printer(result, options, OutputScheme(options.extensions))
if options.number < warning_count:
sys.exit(1)
if __name__ == "__main__":
lizard_main(sys.argv)