From 83173ee4f159b978fb9fe62518b827e0a58a3280 Mon Sep 17 00:00:00 2001 From: "Justin W. Flory" <4721034+jwflory@users.noreply.github.com> Date: Thu, 28 Nov 2019 18:17:29 -0500 Subject: [PATCH] :checkered_flag: Add precommit lint script (#252) 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 --- code_lint.sh | 10 ---------- pre_commit.sh | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 10 deletions(-) delete mode 100755 code_lint.sh create mode 100755 pre_commit.sh diff --git a/code_lint.sh b/code_lint.sh deleted file mode 100755 index 4a9aee33..00000000 --- a/code_lint.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/sh -# -# This script is used to lint our code according to a specific standard. For -# this script to work, you must install the project development dependencies: -# -# $ pipenv shell -# $ pipenv sync --dev -# - -black . diff --git a/pre_commit.sh b/pre_commit.sh new file mode 100755 index 00000000..b8160fae --- /dev/null +++ b/pre_commit.sh @@ -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