Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Git commit hook to check for lines with "TODO" in them
#!/usr/bin/python
import logging
import re
import sys
import envoy
def _exec_git(cmd, args=''):
cmd = 'git {0} --color=never {1}'.format(cmd, args)
logging.debug('Calling: {0}'.format(cmd))
res = envoy.run(cmd)
if res.status_code != 0:
raise Exception('Command \'{0}\' failed: {1}'.format(cmd, res.std_err))
return res
def get_diff():
res = _exec_git('diff', '--cached HEAD')
return res.std_out.splitlines()
def check_commit():
errors = 0
diff = get_diff()
file_re = re.compile('^\+\+\+ b\/(.+)$')
diff_re = re.compile('^@@ -[0-9]+,[0-9]+ \+([0-9]+),[0-9]+ @@')
regex = re.compile('^\+.*TODO.*')
filename = None
position = 0
for line in diff:
# read diff line, like '@@ -5,6 +5,18 @@'
match = diff_re.match(line)
if match:
position = int(match.groups()[0])
logging.debug('Hunk position: {0}'.format(position))
continue
# read file line, like '+++ b/foo/bar/file.py'
file_match = file_re.match(line)
if file_match:
filename = file_match.groups()[0]
logging.debug('Filename: {0}'.format(filename))
continue
match = regex.match(line)
if match:
print '{0}:{1}: Line has TODO statement: {0}'.format(filename, position, line)
errors += 1
if not line.startswith('-'):
position += 1
return errors
def main():
logging.basicConfig()
return check_commit()
if __name__ == '__main__':
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment