Skip to content

Instantly share code, notes, and snippets.

@dreness
Last active June 22, 2021 13:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dreness/2de62e01d2053f9440eb to your computer and use it in GitHub Desktop.
Save dreness/2de62e01d2053f9440eb to your computer and use it in GitHub Desktop.
#git pre-commit #hook to set commit email address based on the repo's remote domain(s)
#!/bin/zsh
#
# Set repo's user.email to a default or alternate value based on remote domain.
# Because the in-flight commit info has already been set, if an email address
# change is needed, this commit is aborted. Retry the commit to use the new address.
#
# To automatically install custom hooks to new repos:
# 1) Add something like the following to ~/.gitconfig:
# [init]
# templatedir = ~/.git/templates
# 2) Create a directory at ~/.git/templates/hooks and install this file there
# Use 'git init' to add to existing repos
# If this repo's remote domain contains the string ALT_DOMAIN, set user.email
# to ALT_EMAIL, otherwise use DEFAULT_EMAIL.
ALT_DOMAIN='example.com'
ALT_EMAIL='dre@example.com'
DEFAULT_EMAIL='dre@pretendco.com'
# Current repo's configured email address and remotes
EMAIL=$(git config --local user.email)
REMOTES="$(git remote -v)"
# If this repo has a local user.email setting, do nothing. This allows for
# manually setting user.email instead of using this script.
if [[ -n ${EMAIL} ]]; then
exit 0
fi
if [[ "${REMOTES}" == *${ALT_DOMAIN}* ]]; then
# This repo has a remote in ALT_DOMAIN
echo "Setting user.email to ${ALT_EMAIL}. Retry."
git config --local user.email "${ALT_EMAIL}"
exit 1
else
# This repo does NOT have a remote in ALT_DOMAIN
echo "Setting user.email to ${DEFAULT_EMAIL}. Retry"
git config --local user.email "${DEFAULT_EMAIL}"
exit 1
fi
SCRIPT_PATH=$0:A
printf "ERROR in pre-commit hook: %s\nCan't configure email address?! \n" ${SCRIPT_PATH}
exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment