Select Git Committer Depending on Repository

Having two Git accounts; one for personal and one for work is inevitable for most of the developers. A common problem of having two GitHub accounts is configuring committer for each commits. This story provides a solution using Git Hooks to select the committer automatically based on repository URL. You can customize this solution depending on your requirement.

Step 1: Remove global configuration of user email.

git config --global --unset-all user.email

Step 2: Create a file named post-checkout with the following content

Replace the <personal-account-name>, <personal-email> and <official-email> with suitable values. This code checks the remote origin URL and set the committer email based on the URL. You can change the logic according to your preference.

Step 3: Copy the post-check to Git hooks template and make it executable.

sudo cp post-checkout /usr/share/git-core/templates/hooks/
sudo chmod +x /usr/share/git-core/templates/hooks/post-checkout

Now clone a repository from your personal GitHub account, add a new file and commit it. After the commit use the following command to check the last commit details.

git log -1 --stat

Try the same for any other repositories and check the result. You will see that Git uses your personal account for personal repository and office account for any other repositories.

Note: This solution will not affect already cloned repositories. Manually copy and paste post-check into local .git/hooks folder and checkout any branches to run the script.