Skip to content

Instantly share code, notes, and snippets.

@harshil93r
Created August 23, 2018 15:16
Show Gist options
  • Save harshil93r/cdee0a73443ad9bf2395e16d8fcb4c74 to your computer and use it in GitHub Desktop.
Save harshil93r/cdee0a73443ad9bf2395e16d8fcb4c74 to your computer and use it in GitHub Desktop.
Pre commit hook Python
#!/usr/bin/env python
#-*- mode: python -*-
all_okay = True
from subprocess import Popen, PIPE
import sys
from termcolor import colored
syntax_checker = "pyflakes"
def run(command):
p = Popen(command.split(), stdout=PIPE, stderr=PIPE)
p.wait()
return p.returncode, p.stdout.read().strip(), p.stderr.read()
_, files_modified, _= run("git diff-index --name-only HEAD")
for fname in files_modified.split():
fname = fname.decode('utf-8')
if fname.endswith(".py"):
print(colored("\n\nChecking syntax on %s: ... "%(fname,),"blue"))
exit_code, _, errors = run("%s %s"%(syntax_checker, fname))
if exit_code != 0:
all_okay = False
for err in _.decode('utf-8').split(r'\n'):
print(colored(err, 'red'))
print("\rChecking syntax on %s: FAILED! \n"%(fname))
else:
print(colored("\rChecking syntax on %s: OK!"%(fname),'green'))
if not all_okay:
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment