Skip to content

Instantly share code, notes, and snippets.

@bskim45
Created July 10, 2019 10:26
Show Gist options
  • Save bskim45/a94bf34a60c14db011803933f9a6ba06 to your computer and use it in GitHub Desktop.
Save bskim45/a94bf34a60c14db011803933f9a6ba06 to your computer and use it in GitHub Desktop.
python + flake8 pre-receive git hook
#!/bin/bash
if test -n "$GIT_PUSH_OPTION_COUNT"
then
i=0
while test "$i" -lt "$GIT_PUSH_OPTION_COUNT"
do
eval "value=\$GIT_PUSH_OPTION_$i"
case "$value" in
force)
echo "Force push"
exit 0
;;
esac
i=$((i + 1))
done
fi
set -e
zero_commit="0000000000000000000000000000000000000000"
while read oldrev newrev refname; do
# Pass delete operation. ($newrev is zero commit)
if [[ $newrev == $zero_commit ]]; then
continue
fi
# Handle only branch. Pass tags (refs/tags/*) and tracking branch (refs/remotes/*).
if [[ ! $refname =~ ^refs/heads/ ]]; then
continue
fi
# new branch created
if [[ $oldrev == $zero_commit ]]; then
oldrev=HEAD
fi
WORKSPACE=$(mktemp -d -t "prerecv.XXXXXXXXXX")
# Get the file names, without directory, of the files that have been modified
# between the new revision and the old revision
files=`git diff --name-only ${oldrev}..${newrev}`
# also include config files
files+='.flake8 setup.cfg tox.ini'
# Get a list of all objects in the new revision
objects=`git ls-tree --full-name -r ${newrev}`
for file in $files; do
# Search for the file name in the list of all objects
object=`echo -e "${objects}" | egrep "(\s)${file}\$" | awk '{ print $3 }'`
# If it's not present, then continue to the the next itteration
if [ -z ${object} ]; then
continue;
fi
# Otherwise, create all the necessary sub directories in the new temp directory
mkdir -p "${WORKSPACE}/`dirname ${file}`" &>/dev/null
# and output the object content into it's original file name
git cat-file blob ${object} > ${WORKSPACE}/${file}
done
pushd "$WORKSPACE" > /dev/null
{
set +e
flake8
RET=$?
set -e
}
popd > /dev/null
rm -rf "$WORKSPACE" &> /dev/null
if [ $RET -ne 0 ]; then
echo "================"
echo "PUSH IS REJECTED"
echo "Use \"--push-option=force\" to push anyway."
echo "================"
exit $RET
fi
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment