Skip to content

Instantly share code, notes, and snippets.

@jalp
Created January 27, 2014 07:55
Show Gist options
  • Save jalp/8644604 to your computer and use it in GitHub Desktop.
Save jalp/8644604 to your computer and use it in GitHub Desktop.
Precommit file using fabric to test and run PEP8 after commit files
#!/usr/bin/env python
import os
import re
import subprocess
import sys
modified_re = re.compile(r'^(\s[AM]+)\s+(?P<name>.*\.py)')
def get_staged_files():
"""Get all files staged for the current commit.
"""
git = subprocess.Popen(['git', 'status', '--porcelain'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out,error = git.communicate()
staged_files = modified_re.findall(out)
return staged_files
def main():
abort = False
# Getting stage files
staged_files = get_staged_files()
# Stagging changed files
subprocess.call(['git', 'stash', '-u', '--keep-index'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print '========== Checking PEP8 =========='
for filename in staged_files:
proc = subprocess.Popen(['pep8', '--max-line-length=119', '--show-source', filename[1]],
stdout=subprocess.PIPE)
output, _ = proc.communicate()
# If pep8 still reports problems then abort this commit.
if output:
abort = True
print '========= Found PEP8 ERROR =========='
print output
else:
print 'PEP8 correct'
# Run unit tests
print '============== Running unit tests ============='
proc = subprocess.Popen(['fab', 'test'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, error = proc.communicate()
if 'FAILED' in error:
print 'There are error in unit tests: {0}'.format(error)
abort = True
# Un-staging previously files
subprocess.call(['git', 'stash', 'pop', '-q'], stdout=subprocess.PIPE)
# Final result
if abort:
print '=============== ABORTING commit ==============='
sys.exit(1)
else:
sys.exit(0)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment