It's very annoying when you write some code at work, say, reproducible cases for OSS issues, but then commit those under work-related credentials and push on GH
To avoid this from happening, I've wrote such a pre-push
hook and put it into .git-templates
folder (see recipe on global hooks)
#!/bin/bash -e
#
# Git pre-push hook that blocks push if commits are authored or committed using non-personal credentials
#
# Source: https://github.com/git/git/blob/87c86dd14abe8db7d00b0df5661ef8cf147a72a3/templates/hooks--pre-push.sample
#
remote="$1"
url="$2"
z40=0000000000000000000000000000000000000000
# Only apply to repositories under "personal" folder
if [[ `pwd` == *"/IdeaProjects/personal/"* ]]; then
while read local_ref local_sha remote_ref remote_sha
do
if [ "$local_sha" = $z40 ]
then
# Handle delete
exit 0
else
if [ "$remote_sha" = $z40 ]
then
# New branch, examine all commits
range="$local_sha"
else
# Update to existing branch, examine new commits
range="$remote_sha..$local_sha"
fi
fi
if git rev-list "$range" --format=format:"%H %an %ae %cn %ce" --no-commit-header | grep -v "username [email protected] username [email protected]";
then
echo "Found wrongly authored commit in $local_ref, not pushing"
exit 1
fi
done
fi
exit 0
In order to commit (and author) with correct credentials, add this to `.git/config" file per project:
[user]
name = username
email = [email protected]
BONUS: in order to re-write author name or email in existing commits, after updating git config, run this:
git rebase --root --exec "git commit --amend --no-edit --reset-author"
(this will re-write all commits between current HEAD and the start of history; if you want to narrow this down, see this answer