Skip to content

Instantly share code, notes, and snippets.

@annarailton
Last active September 20, 2020 19:10
Show Gist options
  • Save annarailton/afa9c4fb40a2928547b2f14ed1fce8f6 to your computer and use it in GitHub Desktop.
Save annarailton/afa9c4fb40a2928547b2f14ed1fce8f6 to your computer and use it in GitHub Desktop.
Run autoflake against staged .py files on commit
#!/usr/bin/python3
"""Runs autoflake on commit. Blocks commit and requests adding changed files
if autoflake fires.
Installation
------------
1. You will need to install autoflake: https://pypi.org/project/autoflake/
$ pip install --upgrade autoflake
or
$ conda install -c auto autoflake
2. Find out where your autoflake has been installed by doing
$ whereis autoflake
3. Change filename to pre-commit
4. Move to .git/hooks in the top of your git repo
5. Change file permissions
$ chmod a+x pre-commit
"""
import os
import subprocess
import sys
import tempfile
class bcolors:
RED = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
autoflake_loc = '/home/railton/.local/bin/autoflake'
git = subprocess.Popen(
['git', 'diff', '--cached', '--name-only', '--diff-filter=AM'],
stdout=subprocess.PIPE)
staged_files = git.stdout.read().decode("utf-8").strip().splitlines()
# Run autoflake on staged files
updated_files = []
for python_file in [f for f in staged_files if f.endswith('.py')]:
output = tempfile.NamedTemporaryFile(mode='w')
autoflake = subprocess.Popen(
[autoflake_loc, '--remove-all-unused-imports', python_file],
stdout=output)
autoflake.communicate()
if os.stat(output.name).st_size > 0:
updated_files.append(python_file)
# If autoflake fired, run in-place and abort the commit
if updated_files:
for python_file in [f for f in staged_files if f.endswith('.py')]:
autoflake = subprocess.Popen(
[autoflake_loc, '--in-place', '--remove-all-unused-imports', python_file],
stdout=subprocess.DEVNULL)
autoflake.communicate()
print(bcolors.RED + bcolors.BOLD + ">>> COMMIT ABORTED <<<" + bcolors.ENDC)
print("Unused imports removed from staged files [{}]".format(
', '.join(updated_files)))
print("Please restage and commit again")
sys.exit(1)
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment