Skip to content

Instantly share code, notes, and snippets.

@smerritt
Created August 30, 2013 20:01
Show Gist options
  • Save smerritt/6393736 to your computer and use it in GitHub Desktop.
Save smerritt/6393736 to your computer and use it in GitHub Desktop.
pre-commit hook I use to prevent trailing commas in JSON test files
#!/usr/bin/env python
import sys
import os.path
import subprocess
import tempfile
import re
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)
changed_json_files = [filename for filename in diff.communicate()[0].split("\n")
if re.search('\.json$', filename)]
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment