Skip to content

Commit

Permalink
🏁 Add precommit lint script (#252)
Browse files Browse the repository at this point in the history
This commit revises the `code_lint.sh` script and renames it to
`pre_commit.sh`. It adds checks to create the pre-commit hook if the
script is ran from the root directory of the repo for the first time.
Then, it uses Black to automatically format the project code.

Also, it will temporarily stash uncommitted changes so Black will not
overwrite someone's files that are still a work in progress. The stash
should be popped (i.e. the changes are restored) at the end.

More reading:

https://githooks.com/

https://codeinthehole.com/tips/tips-for-using-a-git-pre-commit-hook/

http://omerkatz.com/blog/2013/5/23/git-hooks-part-2-implementing-git-hooks-using-python

Signed-off-by: Justin W. Flory <[email protected]>
  • Loading branch information
jwflory authored and leong96 committed Nov 28, 2019
1 parent 62a2e87 commit 83173ee
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 10 deletions.
10 changes: 0 additions & 10 deletions code_lint.sh

This file was deleted.

35 changes: 35 additions & 0 deletions pre_commit.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/bin/sh
#
# Stash unstaged changes and lint Python files to PEP-8/Black standard
#
# This script is used to enforce style changes before a commit is saved. This
# means this script is executed automatically before a commit is made. The
# script does the following:
#
# * Stores unstaged changes in a git stash
# * Lints code using Black
# * Pops stashed changes back to staging
#
# You must install development dependencies for this script to work:
#
# $ pipenv shell
# $ pipenv sync --dev
#

# If the git pre-commit script does not exist yet, create it.
if [ -d ".git" ] && [ ! -f ".git/hooks/pre-commit" ]; then
ln -s ../../pre_commit.sh .git/hooks/pre-commit
fi

# Stash any unstaged changes to avoid overwriting ongoing work.
STASH_NAME="pre-commit-$(date +%s)"
git stash save -q --keep-index $STASH_NAME

# Lint code according to PEP-8/Black rules.
black . --exclude=grasa_event_locator/migrations

# Pop stashed changes back into staging.
STASHES=$(git stash list)
if [[ $STASHES == "$STASH_NAME" ]]; then
git stash pop -q
fi

0 comments on commit 83173ee

Please sign in to comment.