Skip to content

Instantly share code, notes, and snippets.

@borgar
Created September 19, 2011 19:48
Show Gist options
  • Save borgar/1227396 to your computer and use it in GitHub Desktop.
Save borgar/1227396 to your computer and use it in GitHub Desktop.
Git pre-commit hook to prevent JS trailing commas being checked in to projects.
#!/usr/bin/env python
"""
Git pre-commit hook to prevent JS trailing commas being checked in.
They have a tendency to sneak into the project and they crash MSIE7.
"""
import sys
import re
import subprocess
def has_trailing_commas( files ):
single_str = ur"'(?:\\'|\\?[^'])*'"
double_str = ur'"(?:\\"|\\?[^"])*"'
regexp_lit = ur'\/(?:\\\/|[^\/\n])*\/'
ml_comment = ur'\/\*[\S\s]*?\*\/'
sl_comment = ur'//[^\n]*'
re_trailing_comma = re.compile( ur'(,\s*(\n\s*)*\})' )
re_ignore = re.compile( ur"(%s|%s|%s|%s|%s)" % (
ml_comment, sl_comment, regexp_lit, single_str, double_str) )
def str_collapse( m ):
# remove all commas from match ...
return ''.join(c if c != ',' else ' '
for c in m.group(0))
found = False
for f in files:
if f.endswith('.js'):
js = open(f, "r").read()
# neutralize comments & strings
nostr_js = re_ignore.sub( str_collapse, js )
# test remainder for problems
if re_trailing_comma.search( nostr_js ):
found = True
problems = re_trailing_comma.finditer( nostr_js )
lines = js.split('\n')
print "Identified trailing comma problems in '%s'" % f
for problem in problems:
line_nr = len( nostr_js[0:problem.start()].split('\n') )
line = lines[line_nr-1].strip()
if problem.start() > 50:
line = "... %s ..." % js[ problem.start()-15: problem.start()+15 ].replace('\n','\\n').strip()
print ' -- line %s @%s: %s' % (line_nr, problem.start(), line)
return found
if __name__ == '__main__':
# get the files about to be changed
stdout_text, stderr_text = subprocess.Popen(
['git', 'diff', '--name-only', '--staged', '--diff-filter=AM'],
stdout=subprocess.PIPE).communicate(None)
files = stdout_text.split()
# scan files for problems
if has_trailing_commas( files ):
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment