Skip to content

Instantly share code, notes, and snippets.

@MyrionPhoenixmoon
Created December 10, 2015 21:03
Show Gist options
  • Save MyrionPhoenixmoon/eb7546d58e3f30283000 to your computer and use it in GitHub Desktop.
Save MyrionPhoenixmoon/eb7546d58e3f30283000 to your computer and use it in GitHub Desktop.
Git pre-commit hook to checkstyle python code with flake8 and run all PyUnit tests
#!/usr/bin/env python3
#
# A pre-commit hook to verify PEP8 conformity using flake8
# and to run all available unit tests
import subprocess
import sys
import os
import glob
# Try to read the GIT_DIR envvar, which is set if this is being called as a git pre-commit hook.
try:
path = os.environ['GIT_DIR']
# If it is not set, a KeyError is raised, which is taken as if this is invoked from the command line, using the cwd instead.
# This requires calling this script from the correct directory!
except:
path = os.getcwd()
if (subprocess.call(["flake8", path]) != 0):
print("Found PEP8 non-conformities! Aborting commit...")
sys.exit(1)
for test_file in glob.glob(path + "/tests/*.py"):
if (subprocess.call(["python3", "-m", "unittest", test_file], stdin=None, stdout=None, stderr=subprocess.DEVNULL) != 0):
print("Unit tests failed in " + test_file + "! Aborting commit...")
sys.exit(1)
print("Style check and unit tests successful, committing!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment