Skip to content

Instantly share code, notes, and snippets.

@dreness dreness/pre-commit
Last active Sep 24, 2019

Embed
What would you like to do?
#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
You can’t perform that action at this time.