Last active
June 2, 2020 08:05
-
-
Save F1ashhimself/262813f40333b7614116 to your computer and use it in GitHub Desktop.
Flake8 pre-commit hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from __future__ import with_statement | |
import os | |
import re | |
import shutil | |
import subprocess | |
import sys | |
import tempfile | |
from shutil import copyfile | |
def system(*args, **kwargs): | |
kwargs.setdefault('stdout', subprocess.PIPE) | |
proc = subprocess.Popen(args, **kwargs) | |
out, err = proc.communicate() | |
return out | |
def main(): | |
modified = re.compile(r'^[AM]+\s+(?P<name>.*\.py)', re.MULTILINE) | |
files = system('git', 'status', '--porcelain') | |
files = modified.findall(files.decode()) | |
tempdir = tempfile.mkdtemp() | |
config_file = 'setup.cfg' | |
if os.path.exists(config_file): | |
copyfile(config_file, os.path.join(tempdir, config_file)) | |
for name in files: | |
filename = os.path.join(tempdir, name) | |
filepath = os.path.dirname(filename) | |
if not os.path.exists(filepath): | |
os.makedirs(filepath) | |
with open(filename, 'w') as f: | |
system('git', 'show', ':' + name, stdout=f) | |
output = system('flake8', '.', cwd=tempdir) | |
shutil.rmtree(tempdir) | |
if output: | |
print('Flake8 style violations have been detected. Please fix them\n ' | |
'or force the commit with "git commit --no-verify".\n') | |
print(output,) | |
sys.exit(1) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment