Skip to content

Instantly share code, notes, and snippets.

@Norbo11
Last active October 26, 2023 11:17
Show Gist options
  • Save Norbo11/7f24bc4289319c1471537c3b3910b95f to your computer and use it in GitHub Desktop.
Save Norbo11/7f24bc4289319c1471537c3b3910b95f to your computer and use it in GitHub Desktop.
Pre-push git hook to run flake8 on changed .py files only
#!/bin/sh
# An example hook script to verify what is about to be pushed. Called by "git
# push" after it has checked the remote status, but before anything has been
# pushed. If this script exits with a non-zero status nothing will be pushed.
#
# This hook is called with the following parameters:
#
# $1 -- Name of the remote to which the push is being done
# $2 -- URL to which the push is being done
#
# If pushing without using a named remote those arguments will be equal.
#
# Information about the commits which are being pushed is supplied as lines to
# the standard input in the form:
#
# <local ref> <local sha1> <remote ref> <remote sha1>
remote="$1"
url="$2"
z40=0000000000000000000000000000000000000000
while read local_ref local_sha remote_ref remote_sha
do
if [ "$local_sha" = $z40 ]
then
# Handle delete
:
else
if [ "$remote_sha" = $z40 ]
then
# New branch, so we don't have a remote SHA yet. Assume we branched from master and diff against that
range="master..$local_sha"
echo "New branch, using range $range"
else
# Update to existing branch, examine new commits
range="$remote_sha..$local_sha"
echo "Existing branch, using range $range"
fi
# Get a list of files changes in the given range, filter down to Python files, ignore "users" folder, change newlines to spaces and invoke "ls -d" on each file to filter down to only those that exist
pushed_files=$(git diff --name-only $range | grep .py$ | grep -v users/ | tr '\n' ' ' | xargs -r ls -d 2> /dev/null)
# Exit early if no pushed files to prevent flake8 from running on whole repo
if [ -z "$pushed_files" ]; then
exit 0
fi
echo "Running flake8 for $(echo "$pushed_files" | wc -w) changed .py files according to git diff $range"
echo "/home/npodsadowski/.pyenv/versions/bluecove/bin/flake8 $pushed_files"
if /home/npodsadowski/.pyenv/versions/bluecove/bin/flake8 $pushed_files; then
exit 0
else
exit 1
fi
fi
done
Stick this file inside your-repo/.git/hooks/ and update the path to flake8. Make sure you also `chmod +x your-repo/git/hooks/pre-push` or git won't run your hooks.
When you push from an IDE, the presentation of the result may vary.
In IntelliJ IDEA, the Console tab under Version Control will list all flake errors detected before the push.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment