Skip to content

Instantly share code, notes, and snippets.

@smerritt
Created September 17, 2013 21:46
Show Gist options
  • Save smerritt/6601107 to your computer and use it in GitHub Desktop.
Save smerritt/6601107 to your computer and use it in GitHub Desktop.
Pre-commit hooks for python development
#!/usr/bin/env python
#
# flake8-checks the staged versions of any changed python files
import os.path
import subprocess
import tempfile
import shutil
import atexit
tempdir = tempfile.mkdtemp()
atexit.register(lambda: shutil.rmtree(tempdir))
diff = subprocess.Popen(['git', 'diff', '--cached', '--name-only',
'--diff-filter=ACM'],
stdout=subprocess.PIPE)
all_changed_files = diff.communicate()[0].split("\n")
changed_py_files = [filename for filename in all_changed_files
if filename.endswith(".py")]
subprocess.check_call(
['git', 'checkout-index', '--prefix=%s/' % tempdir, '-f'] +
changed_py_files)
flake8_exit_status = subprocess.call(
['flake8'] +
[os.path.join(tempdir, fname) for fname in changed_py_files])
# errors already printed, if any; just propagate the error status up
exit(flake8_exit_status)
#!/usr/bin/env python
#
# Syntax checks the staged versions of any changed .json files.
#
# Exists because I suck at editing JSON by hand. Seriously, it's 2013; why
# can't I have trailing commas?
import sys
import os.path
import subprocess
import tempfile
import json
import shutil
import atexit
tempdir = tempfile.mkdtemp()
atexit.register(lambda: shutil.rmtree(tempdir))
diff = subprocess.Popen(['git', 'diff', '--cached', '--name-only',
'--diff-filter=ACM'],
stdout=subprocess.PIPE)
all_changed_files = diff.communicate()[0].split("\n")
changed_json_files = [filename for filename in all_changed_files
if filename.endswith('.json')]
ci_args = ['git', 'checkout-index', '--prefix=%s/' % tempdir, '-f']
ci_args.extend(changed_json_files)
subprocess.check_call(ci_args)
exitstatus = 0
for filename in changed_json_files:
with open(os.path.join(tempdir, filename)) as jsonfh:
print "Syntax checking the staged version of %s" % filename
try:
json.loads(jsonfh.read())
except ValueError:
sys.stderr.write("%s is not a syntactically valid JSON file. "
"Preventing checkin.\n" % filename)
sys.stderr.write("If you really need to commit a busted .json "
"file, use 'git commit --no-verify'\n")
exitstatus = 1
exit(exitstatus)
#!/bin/sh
for fname in .git/hooks/pre-commit.d/*; do
if test -x "$fname"; then
if ! "$fname"; then
echo
echo "*** Error running $fname; commit aborted ***"
echo
exit 1
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment