Advent Day 18: Conditional Includes

December 18, 2018

This is day 18 of my Git Tips and Tricks Advent Calendar. If you want to see the whole list of tips as they're published, see the index.

If you're a professional programmer who also works on open source software, then you might want to keep your work identity a bit separate from your personal identity. For example, I always use my personal email address when I'm working on my personal projects and open source software. In contrast, I always use my work email address when I'm committing to my work repositories.

At least, I try to always do that.

One of the things that helps ensure that I keep this organized is Git's conditional includes.

Instead of configuring both my user.name and user.email in my $HOME/.gitconfig, I set only my name (since that's the same everywhere). This is basically the template for all my Git repository configuration; then I can actually include other configuration files on a per-repository basis.

I keep my repositories in one of three places:

  1. $HOME/Microsoft (Unix) or C:/Microsoft (Windows) for my work repositories.
  2. $HOME/libgit2 (Unix) or C:/libgit2 (Windows) for my libgit2 and related repositories, and...
  3. $HOME/Projects (Unix) or C:/Projects (Windows) for all the other things that I work on.

So I can actually set my user.email based on the location of the repository that I'm working in. My $HOME/.gitconfig actually looks like:

[user]
    name = Edward Thomson
[includeIf "gitdir:C:/Microsoft/"]
    path = .gitconfig.msft
[includeIf "gitdir:C:/LibGit2/"]
    path = .gitconfig.oss
[includeIf "gitdir:C:/Projects/"]
    path = .gitconfig.oss

(Note the trailing slashes on the paths, those are required. Further note that they are forward slashes; this is true even on Windows.)

Then I also have a $HOME/.gitconfig.msft that contains my Microsoft-specific settings:

[user]
    email = ethomson@microsoft.com

And a $HOME/.gitconfig.oss that configures my settings for every other, non-work repository:

[user]
    email = ethomson@edwardthomson.com

I could also have just set a default user.email in my .gitconfig, and allowed another configuration to override it, but I like this forcing function. If I ever put a Git repository somewhere else, say in /tmp, now I must configure my email address explicitly. This protects me if I clone a work repository or a personal repository into a temp directory.