Skip to content

Instantly share code, notes, and snippets.

@hartfordfive
Last active May 22, 2024 18:30
Show Gist options
  • Save hartfordfive/20b2245ab1f04aca4ecad28416919ffc to your computer and use it in GitHub Desktop.
Save hartfordfive/20b2245ab1f04aca4ecad28416919ffc to your computer and use it in GitHub Desktop.
Git pre-commit hook to verify committer email

Description

The goal of this hook is to allow you catch when you're committing with an email you shouldn't on a public repositories. In some cases, certain companies need to seperate their internal coporate email accounts from those that might be used for committing to public repositories.

Setting up.

The UNWANTED_EMAIL_SUFFIX should be the suffix (after the @ sign) of the email address you do not want to appear in the git logs. The DESIRED_AUTHOR_EMAIL and DESIRED_AUTHOR_NAME are the respective email and name you want to show up in the git logs.

To be used globally on all git projects:

# Set a git templates directory for all projects
git config --global init.templatedir '~/.git-templates'
mkdir -p ~/.git-templates/hooks
cp pre-commit ~/.git-templates/hooks
chmod a+x ~/.git-templates/hooks/pre-commit

or to be used only on specific projects:

cd <YOUR_PROJECT_DIRECTORY>
cp pre-commit ~/.git-templates/hooks
chmod a+x ~/.git/hooks/pre-commit
#!/bin/bash
UNWANTED_EMAIL_SUFFIX=corporatedomain.org # Example: johndoe@corporatedomain.org
CURR_EMAIL=`git config --get user.email`
CURR_NAME=`git config --get user.name`
REPO_ORIGIN=`git config --get remote.origin.url`
DESIRED_AUTHOR_EMAIL=me@example.org
DESIRED_AUTHOR_NAME="My Name"
if [[ ${REPO_ORIGIN} = *github.com* ]] || [[ ${REPO_ORIGIN} = *gitlab.com* ]]; then
echo "NOTICE: Repo is a public repo."
[[ ${CURR_EMAIL} = *@${UNWANTED_EMAIL_SUFFIX} ]]
RES=$?
echo "NOTICE: Current email is ${CURR_EMAIL}"
if [ "$RES" -eq "0" ]; the
echo -e "NOTICE: Incorrect public committer email. Run commit again like this:\nGIT_AUTHOR_EMAIL=${DESIRED_AUTHOR_EMAIL} git commit -m \"<YOUR MESSAGE>\""
exit 1
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment