Article
Change of Git user with includeif
In this article, we will learn how to change of git user. Across a concrete case, we will use the includeif directive. This will allow us to automatize the change of git context in order to have different users committing following defined rules.
Introduction
When you are working on multiple projects at the same time, you will sometimes have to use git users with different email addresses. That's for example the case if you work at the same time on a personnal project and a project for a client who gave you a @client.fr address.
Concrete case
Thomas is making github projects with his personnal email address thomas@gmail.com. Here is his .gitconfig :
[user]
name = Thomas
email = thomas@gmail.com
username = tthomasIn order to work with his new client, he must use a thomas@client.com address.
He can not modify his .gitconfig or else he will erase his personnal github account config. He can make many gitconfig and change everytime but he could get confused that way and commit under the wrong address for his project. This is where the IncludeIf directive appears !
The IncludeIf directive
The includeif directive, as you can guess by its name, allows you to include a config file if some condition is set. Thomas will then have a general .gitconfig and some specific .gitconfigs according to conditions he chose, in our case the current folder.
Into the general .gitconfig, he will put the includeIf directive as well as the path to the specific .gitconfigs :
[includeIf "gitdir:~/workspaces/personal/"]
path = ~/.gitconfig-personal
[includeIf "gitdir:~/workspaces/entreprisea/"]
path = ~/.gitconfig-entrepriseaIn .gitconfig-personal, he will put the informations linked to his personnal github account :
[user]
name = Thomas
email = thomas@gmail.com
username = tthomasIn .gitconfig-entreprise, he will put the informations linked to his client project :
[user]
name = Thomas
email = thomas-ext@entreprise-a.com
username=thomasextDefault user
In your .gitconfig you can add the [user] property with all your user informations :
[user]
name = John default
email = john@default-mail.com
username = jdef
[diff]
tool = vimdiff
[includeIf "gitdir:~/workspaces/personnal/github/"]
path = ~/.gitconfig-personnalgithub
[includeIf "gitdir:~/workspaces/proA/"]
path = ~/.gitconfig-entrepriseaConclusion
In this article, we saw how to simply use includeIf to put conditions on your config injection, according to your path. Another condition exists on the branch. You can take a look at the official documentation to learn more.
Troubleshooting
On Windows, if your gitdir is a absolute path, don't forget to put :/ at the beginning :
[includeIf "gitdir:C:/workspaces/monClient1/"]
path = ~/.gitconfig-monclient1