Skip to content

Instantly share code, notes, and snippets.

@acecilia
Last active April 28, 2020 17:23
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 acecilia/f7eb2ba6b1b5d015e96a9a52f3f12480 to your computer and use it in GitHub Desktop.
Save acecilia/f7eb2ba6b1b5d015e96a9a52f3f12480 to your computer and use it in GitHub Desktop.
A pre-push hook to prevent using the wrong email when pushing to a specific remote
#!/bin/sh
########################################
# A pre-push hook to prevent using the wrong email when pushing to a specific remote
#
# Setup:
# $ curl https://gist.githubusercontent.com/acecilia/f7eb2ba6b1b5d015e96a9a52f3f12480/raw --output ~/.githooks/pre-push
# $ chmod +x ~/.githooks/pre-push
#
# In your .gitconfig add the following under the [core] section:
# hooksPath = ~/.githooks
########################################
set -euo pipefail
# The commits range being pushed
range="--all"
# Calculate the range of commits that are being pushed
# From https://github.com/git/git/blob/master/templates/hooks--pre-push.sample
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, examine all commits
range="$local_sha"
else
# Update to existing branch, examine new commits
range="$remote_sha..$local_sha"
fi
fi
done
# Setup
echo "Inspecting the following commit range: ${range}"
remote="$2"
unknown_remote=true
# Obtain emails in commits
authors=`git shortlog -s -n -e ${range}`
committers=`git shortlog -s -n -e -c ${range}`
emails="${authors} ${committers}"
function avoidLeakingEmail {
remoteRegex="$1"
privateEmail="$2"
if [[ $remote == *"$remoteRegex"* ]]; then
unknown_remote=false
if [[ $emails == *"$privateEmail"* ]]; then
echo "The email '${privateEmail}' shows up as author or commiter in this repository"
exit 1
fi
fi
}
########################################
# Add your remotes and private emails below
########################################
# Any github remote
avoidLeakingEmail "github" "you@your_company.com"
if [ "$unknown_remote" = true ] ; then
echo 'This remote is unknown: update your private emails in the pre-push hook'
exit 1
fi
# Run local pre-commit hook if exists
if [ -e ./.git/hooks/pre-push ]; then
./.git/hooks/pre-push "$@"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment