From 841bdf022dcae9204884d4fdf221d05052970673 Mon Sep 17 00:00:00 2001 From: Matthew Stratford Date: Sat, 24 Oct 2020 15:23:06 +0100 Subject: [PATCH] Add pre-commit autopep8 --- dev/pre-commit | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 dev/pre-commit diff --git a/dev/pre-commit b/dev/pre-commit new file mode 100644 index 0000000..c23b75c --- /dev/null +++ b/dev/pre-commit @@ -0,0 +1,61 @@ +#!/usr/bin/env python + +# from https://github.com/chibiegg/git-autopep8 +from __future__ import with_statement, print_function +import os +import re +import shutil +import subprocess +import sys +import tempfile + +# don't fill in both of these +select_codes = [] +ignore_codes = [] #"E121", "E122", "E123", "E124", "E125", "E126", "E127", "E128", "E129", "E131", "E501"] +# Add things like "--max-line-length=120" below +overrides = ["--max-line-length=120"] + + +def system(*args, **kwargs): + kwargs.setdefault('stdout', subprocess.PIPE) + proc = subprocess.Popen(args, **kwargs) + out,_ = proc.communicate() + return out + + +def autopep8(filepath): + args = ['autopep8', '--in-place'] + if select_codes and ignore_codes: + print(u'Error: select and ignore codes are mutually exclusive') + sys.exit(1) + elif select_codes: + args.extend(('--select', ','.join(select_codes))) + elif ignore_codes: + args.extend(('--ignore', ','.join(ignore_codes))) + args.extend(overrides) + args.append(filepath) + system(*args) + + +def main(): + print("Running pre-commit hook.") + try: + import autopep8 as ap8 + except ImportError: + print("'autopep8' is required. Please install with `pip install autopep8`.", file=sys.stderr) + exit(1) + + modified = re.compile('^[AM]+\s+(?P.*\.py)', re.MULTILINE) + basedir = system('git', 'rev-parse', '--show-toplevel').decode("utf-8").strip() + files = system('git', 'status', '--porcelain').decode("utf-8") + files = modified.findall(files) + + for name in files: + filepath = os.path.join(basedir, name) + print("Processing file:", filepath) + autopep8(filepath) + system("git", "add", filepath) + + +if __name__ == '__main__': + main()