Created
March 25, 2017 17:26
-
-
Save dmerejkowsky/8aa70f5f6b7f04165f8e041ee9e3b177 to your computer and use it in GitHub Desktop.
Running mccabe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" Tiny wrapper for mccabe module. | |
Iterate over all the python sources, and print results in | |
an easily parseable format | |
If you are already using pyflakes or prospector, you won't need this :) | |
Dependencies: mmcabe, path.py | |
""" | |
import ast | |
import sys | |
import textwrap | |
import mccabe | |
import path | |
def ignore(py_source): | |
parts = py_source.splitall() | |
# Ignore 'hidden' files | |
if any(x.startswith(".") for x in parts): | |
return True | |
return False | |
def yield_sources(): | |
top = path.Path(".") | |
for py_source in top.walkfiles("*.py"): | |
py_source = py_source.relpath(top) | |
if not ignore(py_source): | |
yield py_source | |
def process(py_source, max_complexity): | |
code = py_source.text() | |
tree = compile(code, py_source, "exec", ast.PyCF_ONLY_AST) | |
visitor = mccabe.PathGraphingAstVisitor() | |
visitor.preorder(tree, visitor) | |
for graph in visitor.graphs.values(): | |
if graph.complexity() > max_complexity: | |
text = textwrap.dedent("""\ | |
{}:{}:{} {} {}""") | |
text = text.format(py_source, graph.lineno, graph.column, graph.entity, | |
graph.complexity()) | |
print(text) | |
def main(): | |
max_complexity = int(sys.argv[1]) | |
print("Looking for code with complexity above", max_complexity) | |
for py_source in yield_sources(): | |
process(py_source, max_complexity) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
prospector uses 15 as the default threshold if you are wondering ...