Skip to content

Instantly share code, notes, and snippets.

@jtroussard
Created April 26, 2021 12:34
Show Gist options
  • Save jtroussard/01531d16a7e4225762fd2afa913a35c3 to your computer and use it in GitHub Desktop.
Save jtroussard/01531d16a7e4225762fd2afa913a35c3 to your computer and use it in GitHub Desktop.
Git Hook: Format python code with black on commit
#!/bin/bash
REDBOLD='\e[1;31m'
GREENBOLD='\e[1;32m'
BOLD='\e[1m'
NORMAL='\e[97;0m'
# Make sure commited python files are formatted using black
#
# Needs work - but usable.
#
# Issues
# - get full path of stagged file so that black can run on files beyond current directory.
echo -e "${BOLD}Kicking off black format check. . . ${NORMAL}"
staged=`git diff --name-only --cached | grep "\.py"`
ret_code=0
for file in $staged
do
echo -n "Checking file: ${file}"
black --check --quiet $file
if [ $? == 1 ]
then
ret_code=1
echo -e " --- ${REDBOLD}FAILED ${NORMAL}"
else
echo -e " --- ${GREENBOLD}PASSED ${NORMAL}"
fi
done
if [ $ret_code == 0 ]
then
echo -e "${GREENBOLD}Your code passed the black formatting check, commiting your changes now. ${NORMAL}"
exit
elif [ $ret_code == 1 ]
then
echo -e "${REDBOLD}Your code did not meet the black formatting standards, please run black against these files, restage them, and try you commit again. ${NORMAL}"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment