Skip to content

Instantly share code, notes, and snippets.

@cypreess
Last active February 26, 2019 15:27
Show Gist options
  • Save cypreess/9b2a2ed8981c650178e28259229ff92e to your computer and use it in GitHub Desktop.
Save cypreess/9b2a2ed8981c650178e28259229ff92e to your computer and use it in GitHub Desktop.
git pre-commit hook that automatically checks if black formatter should be applied and override files before a commit
#!/bin/bash
# Author: Kris Dorosz <cypreess@gmail.com>
# This git pre commit hook will apply black formatting before any commit and make sure all tracked files are reformatted
echo "Using" `black --version`
black --check . 2>/dev/null
if [ $? -ne 0 ]; then
echo "Reformatting:"
export current_git_branch=`git branch | grep \* | cut -d ' ' -f2`
# Find all files which were reformatted by black and choose only those one which are currently tracked by git
for f in $(comm -12 <(black . 2>&1 | grep -o '/.*\.py$' | sort) <( (git ls-tree -r --name-only $current_git_branch; git diff --name-only --cached) | sed "s,^,`pwd`/,g" | sort)); do
echo " $f"
git add $f
done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment