Version control is a big necessity when coding, even when working on your project alone. When coding is both your full time job and a hobby (so you are like me) you should keep your commits and merge requests separated. Internally, Git uses your user name and email address to associate your commits with your identity. It is best to not use your personal email address for work related code, and vice versa. This blog will guide you through the steps to review your current configuration and provides you with an 'set and forget' solution to make sure you are always using the right username and email address.
Your Git client installed on your workstation uses the global settings by default. These settings are stored by default at
~/.gitconfig. Git provides a CLI command to change the username and email address globally:
1git config --global user.name "Your Username" 2git config --global user.email "email@example.com"
When initializing, pulling or cloning a new or existing repository, a
.git directory will be created locally within the root folder of the repository. The file
git/config will hold all the repository specific settings. You can use the previous CLI command without the --global flag to configure it for the current repository only:
1git config user.name "Your Username" 2git config user.email "firstname.lastname@example.org"
Most guides suggest to change your git username and email addresses on each repository, or even change the global ones on each commit. This is hard to maintain, and easy to lose track off.
In my opinion, the best way to handle this, is to let Git know which username and email address to use based on a local parent folder of your repositories. If you are like me, you probably separate your work and personal folders like the following:
Projects |-- Personal `-- Work
Let's configure Git to use our work email and username for every repository stored within
/Work and our personal email and username for the ones within
/Personal. Git has a really handy
includeIf directive to conditionally include other config files:
1# ~/.gitconfig 2[user] 3 name = Jesse de Jonge 4[includeIf "gitdir:Personal/"] 5 path = .gitconfig-personal 6[includeIf "gitdir:Work/"] 7 path = .gitconfig-work
1# ~/.gitconfig-work 2[user] 3 email = email@example.com
1# ~/.gitconfig-personal 2[user] 3 email = firstname.lastname@example.org
And we are done! 🥳 Name and email addresses aren't the only things you can conditionally configure. Take a look at the git documentation for more values.
To make sure the right email and username is used, you can add .patch to the end of a commit link. See this commit for example. As you can see, Linus correctly configured his commit username and email address. 👍