Skip to content

Instantly share code, notes, and snippets.

@seppestas
Last active April 10, 2020 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seppestas/46251be5678b448e96d2b04cd270c56b to your computer and use it in GitHub Desktop.
Save seppestas/46251be5678b448e96d2b04cd270c56b to your computer and use it in GitHub Desktop.
Gerrit anti-unintended changes pre-push hook
#!/bin/sh
# Git pre-push script to notify the user in case more than 1 commit is pushed.
# Handy when pushing to the gerrit review system where each commit will result
# in a change review. Pushing to or from an incorrect branch could result in a
# bunch of unintended change reviews to be created and/or changes dependent on
# unsubmitted changes.
remote="$1"
url="$2"
z40=0000000000000000000000000000000000000000
# GERRIT_MAX_PUSH can be configured, defaults to 1
GERRIT_MAX_PUSH="${GERRIT_MAX_PUSH:-1}"
while read local_ref local_sha remote_ref remote_sha
do
if [ "$local_sha" = $z40 ]
then
# Handle delete
:
else
# Check if remote_ref is for Gerrit.
# Uses the "Remove Largest Prefix Pattern" sh parameter expansion to
# return an empty string if remote_ref has the refs/for/* pattern.
if [ -z ${remote_ref##refs/for/*} ]
then
echo "Creating or updating a Gerrit review. GERRIT_MAX_PUSH=$GERRIT_MAX_PUSH"
# Get the name of the branch we are creating the review for
branch=${remote_ref#refs/for/}
# Count the amount of commits between the commit we are pushing and
# $remote/$branch. Assumes $remote/$branch is up-to date.
# Ignore error if $remote/$branch does not exists, let Gerrit handle
# this
count=`git rev-list --count "$remote/$branch".."$local_ref"` 2> /dev/null || count=1
if [ $count -gt $GERRIT_MAX_PUSH ]
then
echo "Warning: Pushing $count commits to Gerrit might create $count reviews and/or create reviews dependent on other reviews"
exec < /dev/tty # Enable reading
read -p "Continue? (y/N): " yn
exec <&- # Disable reading
if [ $yn != "y" -a $yn != "Y" ]
then
echo >&2 "User aborted, not pushing"
exit 1
fi
echo "Note: set GERRIT_MAX_PUSH to prevent this message"
fi
fi
fi
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment