Juggling multiple Git identities

July 6, 2017

Git is everywhere nowadays, and I use Git pretty much daily. I use it privately, for side projects or things like my dotfiles. I also use it at work, or at clients. That’s where things sometimes get a little complicated.

The problem

For private use, I use both Github and Bitbucket. Fortunately I use the same email address for both services. However, at work or clients I might encounter internally hosted Git services (Bitbucket Server, Github Enterprise, Gitlab, etc) that will most likely not use my private email address. And suddenly you run into the issue where Bitbucket Server is rejecting your commits because your email address is invalid.

One way to deal with that is making sure you properly set up the right Git settings per repo:

cd ~/git/clientA/somerepo
git config user.email benny@clientA.tld

cd ~/git/clientB/somerepo
git config user.email benny@clientB.tld

Etcetera.

A better solution

Maybe it’s just me being very sloppy at this stuff, but manually running git config .. for every repo is bound to go wrong. So, let’s find a better solution.

Fortunately, with the release of Git 2.13, Git gained support for Conditional Configuration.

Using Conditional Configuration, we can easily automate this. I already structured my ~/git directory so that every project/client has its own subdirectory. Now let’s add some includes:

# .gitconfig
...

[includeIf "gitdir:~/git/clientA/**"]
  path = ~/.gitconfig.clientA
[includeIf "gitdir:~/git/clientB/**"]
  path = ~/.gitconfig.clientB

And configure our settings for the various clients:

# .gitconfig.clientA
[user]
  email = benny@clientA.tld
# .gitconfig.clientB
[user]
  email = benny@clientB.tld
  signingkey = ABCD1234

[commit]
  gpgsign = true

This way, I use the correct email address for both clients, and have even set up automatic commit signing for client B. The only thing I need to do is create my repos in the right place.

I have kept the [user] block in the overall .gitconfig file, so by default I’ll use my personal Git identity.

Getting Git 2.13

Currently, Apple ships Git version 2.11.0 with macOS Sierra. If you want to get Git 2.13, the easiest way to do it is using Homebrew.