Skip to content

Instantly share code, notes, and snippets.

@KeyAmam
Last active October 20, 2023 07:22
Show Gist options
  • Save KeyAmam/6a0e8805c0b6a662adb6bcf8118a089a to your computer and use it in GitHub Desktop.
Save KeyAmam/6a0e8805c0b6a662adb6bcf8118a089a to your computer and use it in GitHub Desktop.
post-checkout hook to configure a git account to a repo only after git clone (not after git checkout)
#!/bin/bash
# NOTES
# set git accounts info in ~/.sources/.gitvariables like so:
# GIT_USER_NAME_WORK=...
# GIT_USER_EMAIL_WORK=...
# GIT_SSH_NAME_WORK=...
# GIT_USER_NAME_PRIVATE=...
# GIT_USER_EMAIL_PRIVATE=...
# GIT_SSH_NAME_PRIVATE=...
# add .sources/.gitvariables to ~/.gitignore
set -e
# set -u
# set -x
HOOK_NAME='post-checkout'
echo "Executing $HOOK_NAME.."
########## START OF CHECKOUT HOOK ##########
########## END OF CHECKOUT HOOK ##########
########## START OF CLONE HOOK ##########
# __HOOKS__ON_GIT_CLONE is set in .bash_hooks
if [ -z "$__HOOKS__ON_GIT_CLONE" ]; then
exit
fi
# set/load variables
REPO_ROOT_DIR="$(git rev-parse --show-toplevel)"
GPG_SCRIPT="$HOME/.scripts/gitconfig-set-gpg.sh"
. "$HOME/.sources/.gitvariables"
function set_work_account_to_config() {
git config --local user.name "$GIT_USER_NAME_WORK"
git config --local user.email "$GIT_USER_EMAIL_WORK"
git config --local url."$GIT_SSH_NAME_WORK".insteadOf "[email protected]"
[[ -f "$GPG_SCRIPT" ]] && "$GPG_SCRIPT"
}
function set_private_account_to_config() {
git config --local user.name "$GIT_USER_NAME_PRIVATE"
git config --local user.email "$GIT_USER_EMAIL_PRIVATE"
git config --local url."$GIT_SSH_NAME_PRIVATE".insteadOf "[email protected]"
[[ -f "$GPG_SCRIPT" ]] && "$GPG_SCRIPT"
}
# check if current dir is under work or private account
case "$REPO_ROOT_DIR/" in
*$GIT_REPOS_DIR_WORK/*)
echo "Using work account.."
set_work_account_to_config
;;
*$GIT_REPOS_DIR_PRIVATE/*)
echo "Using private account.."
set_private_account_to_config
;;
*)
;;
esac
echo 'Unsetting __HOOKS__ON_GIT_CLONE in post-checkout..'
unset __HOOKS__ON_GIT_CLONE
echo "Done $HOOK_NAME"
########## END OF CLONE HOOK ##########
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment