Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def lint_mccabe(filename, tree, threshold=7):
"""
Lint file with mccabe complexity check.
"""
mccabe.McCabeChecker.max_complexity = threshold
checker = mccabe.McCabeChecker(tree, filename)
return ((err[0], err[1], err[2]) for err in checker.run())
# lint with import order
if settings.get('import_order', False):
order_style = settings.get('import_order_style')
import_linter = ImportOrderLinter(tree, None, lines, order_style)
for error in import_linter.run():
warnings.append(error[0:3])
# check complexity
try:
complexity = int(settings.get('complexity', -1))
except (TypeError, ValueError):
complexity = -1
if complexity > -1:
mccabe.McCabeChecker.max_complexity = complexity
checker = mccabe.McCabeChecker(tree, None)
for error in checker.run():
warnings.append(error[0:3])
return sorted(warnings, key=lambda e: '{0:09d}{1:09d}'.format(e[0], e[1]))
def run(path, code=None, params=None, **meta):
"""MCCabe code checking.
:return list: List of errors.
"""
tree = compile(code, path, "exec", ast.PyCF_ONLY_AST)
McCabeChecker.max_complexity = int(params.get('complexity', 10))
return [
{'lnum': lineno, 'offset': offset, 'text': text, 'type': McCabeChecker._code}
for lineno, offset, text, _ in McCabeChecker(tree, path).run()
]
def get_code_complexity(code, threshold=7, filename='stdin'):
"""
This is a monkey-patch for flake8.pyflakes.check.
Return array of errors instead of print them into STDERR.
"""
try:
tree = compile(code, filename, "exec", ast.PyCF_ONLY_AST)
except SyntaxError:
# return [(value.lineno, value.offset, value.args[0])]
# be silent when error, or else syntax errors are reported twice
return []
complexity = []
McCabeChecker.max_complexity = threshold
for lineno, offset, text, check in McCabeChecker(tree, filename).run():
complexity.append((lineno, offset, text))
return complexity