Skip to content

Instantly share code, notes, and snippets.

@hartfordfive
Last active December 18, 2024 16:28
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_REGEX=".*(your|regex|here).*"
CURR_EMAIL=$(git config --get user.email | tr [:upper:] [:lower:])
CURR_NAME=`git config --get user.name`
REPO_ORIGIN=$(git config --get remote.origin.url | tr [:upper:] [:lower:])
if [[ ! -z ${GIT_HOOK_DEBUG} ]]; then
echo ""
echo "[DEBUG] Curr dir: $(pwd)"
echo "[DEBUG] Curr email: $CURR_EMAIL"
echo "[DEBUG] Unwanted regex: ${UNWANTED_REGEX}"
echo ""
fi
[[ $(grep --exclude-dir=".git" -inr -E "$UNWANTED_REGEX") ]]
RES=$?
if [[ $RES -eq 0 ]]; then
echo "Some files have been found to have matches of sensitive strings in your code. Aborting commit."
echo "Occurences found:"
grep --exclude-dir=".git" -inr -E "$UNWANTED_REGEX"
exit 1
fi
if [[ ${REPO_ORIGIN} = *github.com* ]]; then
echo -e "\n[NOTICE] You consider this repo public.\n"
[[ ${CURR_EMAIL} =~ ${UNWANTED_REGEX} ]]
RES=$?
if [ "$RES" -eq 0 ]; then
echo "[ERROR] Committer email isn't the one you should be using. Aborting!"
exit 1
fi
fi
if [[ ! -z ${GIT_HOOK_DEBUG} ]]; then
echo "[NOTICE] Failing hook due to debug mode enabled"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment