I discovered gitconfig’s includeIf feature can change your global Git config depending on which directory you are working in.

This is super useful if you have different identities for different project, or you need to specify the SSH key to use, etc.. in my case I want to use my personal email address for personal projects and work email for work projects.

So let’s assume a directory layout like this:

code/
├── heaton/
|   ├── heaton.dev/
|   └── test/
└── corp/
    ├── BigData/
    └── LittleData/

Where heaton and corp are the different organisations and the directories below them are cloned repositories.

In this example we can add a .gitconfig file under heaton/ and corp/, we’ll populate the file accordingly:

[user]
    name = Heaton
    email = [email protected]

Now we can reference this file in our global git config which you can find at ~/.gitconfig. (Possibly also ~/.config/git/config).

[includeIf "gitdir:~/code/heaton/"]
    path = ~/code/heaton/.gitconfig

[includeIf "gitdir:~/code/corp/"]
    path = ~/code/corp/.gitconfig

Even if we set a global git email using git config --global user.email [email protected], it will be overridden by our includeIf if we are inside those directories!