Skip to content

Instantly share code, notes, and snippets.

@inesusvet
Last active October 9, 2020 08:59
Show Gist options
  • Save inesusvet/f17f0f1595069742bc756907131b3a62 to your computer and use it in GitHub Desktop.
Save inesusvet/f17f0f1595069742bc756907131b3a62 to your computer and use it in GitHub Desktop.
Pre-commit hook for Cyclomatic Complexity check
from __future__ import print_function
"""
Pre-commit hook for Cyclomatic Complexity check
Works well with radon==2.2.0
"""
__author__ = 'Ivan Styazhkin <ivan@nesusvet.com>'
import subprocess
GIT_CHANGES_CMD = 'git diff --name-only --cached --diff-filter=ACM'.split()
GIT_HASH_CMD = 'git ls-files --stage'.split()
WARNING_LEVEL = 'C'
RADON_CMD = ('radon cc -s -n %s' % WARNING_LEVEL).split()
def get_lines(stdout_text):
"""Assumes your console uses utf-8"""
return stdout_text.strip().decode('utf-8').split('\n')
def get_python_changes():
"""Returns python filenames which are staged"""
python_changes = get_lines(subprocess.check_output(GIT_CHANGES_CMD))
return [s for s in python_changes if s.endswith('.py')]
def main():
filename_list = get_python_changes()
if not filename_list:
return
pipe = subprocess.Popen(
RADON_CMD + filename_list,
stdout=subprocess.PIPE,
)
out, _ = pipe.communicate()
if not out:
print('\033[92mCheck radon: OK\033[0m')
return
print('\033[91mCheck %d files with radon failed\033[0m' %
len(filename_list)
)
print(out)
return 1
if __name__ == '__main__':
exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment