Skip to content

Instantly share code, notes, and snippets.

@IuryAlves
Created August 31, 2017 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IuryAlves/5df487c94b8d1c9a1e1b1532d38f46a6 to your computer and use it in GitHub Desktop.
Save IuryAlves/5df487c94b8d1c9a1e1b1532d38f46a6 to your computer and use it in GitHub Desktop.
git pre-commit hook
#!/usr/bin/env python
# Original at http://tech.yipit.com/2011/11/16/183772396/
# Insert this into .git/hooks/pre-commit
import re
import subprocess
import sys
modified = re.compile('^(?:M|A)(\s+)(?P<name>.*)')
CHECKS = [
{
'output': 'Checking for pdbs...',
'command': 'grep -n "import pdb" %s',
'match_files': ['.*\.py$'],
'print_filename': True,
},
{
'output': 'Running flake8...',
'command': 'flake8 %s',
'match_files': ['.*\.py$'],
'print_filename': False,
},
{
'output': 'Running eslint...',
'command': './node_modules/.bin/eslint %s',
'match_files': ['.*\.js$'],
'print_filename': False,
},
{
'output': 'Running scsslint...',
'command': 'scss-lint %s',
'match_files': ['.*\.scss$'],
'print_filename': False,
},
]
def matches_file(file_name, match_files):
return any(re.compile(match_file).match(file_name) for match_file in match_files)
def check_files(files, check):
result = 0
print(check['output'])
for file_name in files:
if 'match_files' not in check or matches_file(file_name, check['match_files']):
if 'ignore_files' not in check or not matches_file(file_name, check['ignore_files']):
process = subprocess.Popen(check['command'] % file_name, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=True)
out, err = process.communicate()
if out or err:
if check['print_filename']:
print('\t%s:' % file_name)
print(out.decode('utf-8'))
if err:
print(err.decode('utf-8'))
result = 1
return result
def main():
files = []
p = subprocess.Popen(['git', 'status', '--porcelain'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
match = modified.match(line.decode("utf-8").lstrip(' '))
if match:
files.append(match.group('name'))
result = 0
for check in CHECKS:
result = check_files(files, check) or result
sys.exit(result)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment