Created
November 15, 2016 17:41
-
-
Save orenshk/6cab23fcff847d704af7f3eec22b1ba6 to your computer and use it in GitHub Desktop.
Run autopep8 and any tests you can find. To have a as a pre-commit hook, add to .git/hooks/pre-commit
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 bash | |
# Script to run before doing a commit. This will run autopep8 and any unit tests it can find. | |
# Place this script in .git/hooks/ directory of your repo and rename it pre-commit (no extension) | |
# To have this file copied to every new repo you created, place it in $HOME/.git_template/hooks/pre-commit | |
# NOTES: | |
# 1. This is an opinionated script, following the notion that code formatting issues are the most contentious but the | |
# least consequential. As such it borrows a page from Go and lets the machine decide on the formatting. Concretely, | |
# this means that any PEP8 violations will be fixed before commit, so long as the semantics of the code aren't changed | |
# (e.g. x == None is not replaced with x is None) | |
# | |
# 2. If any tests fail the commit will be aborted. To force a commit (at your own peril!), use 'git commit --no-verify' | |
function python_checks { | |
staged=$1 | |
# test that we have autopep8. | |
which autopep8 > /dev/null 2>&1 | |
# examine exit status | |
if [ $? -gt 0 ]; then | |
echo "autopep8 not installed. Cannot proceed" | |
exit 1 | |
fi | |
# run autopep8 to see if changes need to made. | |
mln=120 # max line length. Should be something sensible for the modern world. | |
autopep_results=$(autopep8 --max-line-length ${mln} --diff ${staged}) | |
if [ "$autopep_results" != "" ]; then | |
# if colordiff is installed, we'll use it. | |
which colordiff > /dev/null 2>&1 | |
if [ $? -eq 0 ]; then | |
echo "$autopep_results" | colordiff | |
else | |
echo "$autopep_results" | |
fi | |
# Make the changes. | |
autopep8 --max-line-length ${mln} --in-place ${staged} | |
# And restage. | |
git add ${staged} | |
fi | |
# run tests | |
python -m unittest discover . --failfast | |
# unittest exists with 0 if all tests passed, 1 otherwise. | |
tests_failed=$? | |
if [ ${tests_failed} -eq 1 ]; then | |
echo "Tests failed. Aborting commit" | |
exit 1 | |
fi | |
} | |
# Look for python files that are about to be committed. | |
staged_py_files=$(git diff --name-only --cached | grep "\.py$") | |
if [[ ! -z "$staged_py_files" ]]; then | |
python_checks ${staged_py_files} | |
fi | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment