Managing Multiple Git Identity Configurations

Ever since I first used git, I really didn’t like the fact the I need to set my name and e-mail address. In time I got used to it, but my git identity problems started after I started working.

I had two e-mail addresses (personal and work), and if I was working from my personal computer on a work related project, I needed to set my user.email config to my work e-mail address for that repository.

It is quite easy actually, you just type

$ git config user.email dogukan@example.com

However, the problem was that I always forgot to do it, and commit history has two identities for me. Seeing different e-mail addresses on commit history is really annoying.

Another problem is that git stats of your profile is effected, because some commits actually doesn’t belong to you anymore.

Solution

For a long time, I looked for a good solution for this problem, I wrote a simple scripts that changes your identity at .gitconfig file, and used that until recently.

I came accross includeIf config option of git-config which was added to git in versionv2.13 and yeah, I can finally change my ugly (but practical) solution to change my git profiles.

With the script on your $PATH you can set different profiles (git-config options) for your current working directory (tree).

From now on I create different profiles for my work and personal life, ~/.gitconfig-work and ~/.gitconfig-personal. I can now set different configuration options for each of them.

For example, on a specific repository that I want to use work profile, I enable a profile on my ~/.gitconfig using:

$ cd some-specific-repository
$ set-git-config-profile.sh work

The script basically adds a includeIf config option for current directory on your ~/.gitconfig like the following lines:

[includeIf "gitdir:~/projects/some-specific-repository/"]
	path = ~/.gitconfig-work

Additional Options

You can remove any profiles attached to your current directory.

$ set-git-config-profile.sh -r

If you try to attach to a non-existing profile, the script asks to create the profile.

$ set-git-config-profile.sh new-profile
Git config profile ~/.gitconfig-new-profile does not exist
Do you wish to create an empty one and continue? (yn) y
Create empty profile: ~/.gitconfig-new-profile
Setting profile new-profile for current directory

Here you can set any config action easily for your new profile:

$ git config -f ~/.gitconfig-new-profile user.name "John Doe"
$ git config -f ~/.gitconfig-new-profile user.email "john.doe@example.com"

In Conclusion

I really liked this new solution to my “git” identity crisis :)

It is a repeatable and progressive solution that creates an easy way to add/change working profiles when working with different profiles for your git repositories. Additionally, you are not limited to changing your e-mail address only, you can change your profiles with any git-config option for other type of changing requirements of your working environment.