Skip to content

Instantly share code, notes, and snippets.

@taikedz
Last active September 3, 2021 09:04
Show Gist options
  • Save taikedz/0502279a247d87467f3bbb19aa9ea5fe to your computer and use it in GitHub Desktop.
Save taikedz/0502279a247d87467f3bbb19aa9ea5fe to your computer and use it in GitHub Desktop.
Wrap lizard's CSV complexity output in a usable object, and give usage example
import sys
from collections import namedtuple
# A friendlier named object for working with each output line
Analysis = namedtuple("Analysis", [
"NLOC", # Count of number of active LOC (excl whitespace)
"CCN", # Cyclomatic Complexity Number
"token", # token count: how many syntactic tokens ("if", "[", "5", etc) are used in the functions
"PARAM", # number of parameters to the function
"length", # total number of file lines
"blob", # string detailing file, function, and line numbers
"file",
"function",
"signature",
"line_start",
"line_end",
])
results = []
def parse_analysis(lizard_csv_lines):
""" Given an iterable of the lines of lizard CSV output, parse each to an Analysis object.
"""
for line in lizard_csv_lines:
line = line.strip()
line_parts = eval("["+line+"]")
results.append(Analysis(*line_parts ))
return results
def sorted_results(results, keyname="CCN"):
""" Given a list of Analysis objects, sort according to the named key.
Typically this would be "CCN" for the cyclomatic complexity, or "NLOC" for the number of lins of code
"""
results = results[:]
results.sort(key=lambda a: a.__getattribute__(keyname))
return results
def filter_upper_threshold(results, keyname="CCN", value=20):
return [res for res in results if res.__getattribute__(keyname) >= value]
def main():
""" An example implementation of how to use the functions herein.
"""
max_complexity=20
results = parse_analysis(sys.stdin)
results = filter_upper_threshold(results, keyname="NLOC", value=max_complexity)
for res in results:
print(f"CCN={res.CCN} --> NLOC={res.NLOC} : {res.file} : {res.line_start} : {res.signature}")
res_count = len(results)
assert res_count == 0, f"Found {res_count} items of complexity higher than {max_complexity}"
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment