Skip to content

Conditional Includes For Git Config

2017-05-11

Auto-manually keeping your git identities separate between work & personal accounts

I have a section of script in my profile that looks at my current directory and if it is in my root code directory my profile script calls git config --global user.email $personal_email. If the current directory is my work code sub-directory my profile script calls git config --global user.email $work_email. The purpose of this is to setup my git username and email address to the appropriate value depending on what I'm working on. From my terminal if I'm in any directory on my machine that isn't my designated 'work' directory then those are set to my personal contact info. I always thought it was a bit of a hack but honestly it meets my requirements of keeping my git identity bound to the current directory location.

Silvrback blog image sb_float_center

A better way?

With git 2.13 you get a feature called conditional includes

This means that I can have git automatically apply the correct name and email address to my commits and I can keep my current source directory layout on my machine.

C:\users\eric\code
├───oss1
├───oss2
├───webapp452
└───work
    ├───client1
    ├───client2
    └───client3

Removing the following section in my .gitconfig

[user]
name = Firstname Lastname
email = [email protected]

with this conditional

[includeIf "gitdir:~/code/"]
  path = .gitconfig-personal
[includeIf "gitdir:~/code/work/"]
  path = .gitconfig-work
Then I add two additional sibling files to my profile root directory, next to my .gitconfig

For my personal & open source work I have my non-work values in a .gitconfig-personal file

[user]
name = Eric Williams
email = [email protected]

For my source code work related to my.gitconfig-work

[user]
name = Eric Williams
email = [email protected]

So that I end up with these files in my profile root.

C:\users\eric\
├───.gitconfig
├───.gitconfig-personal
└───.gitconfig-work

This approach could be replicated to any number of patterns you choose. If you have specific accounts you use for client work you just add more entries to the conditional block. There have been scenarios where I would need to use an identity given by the client so that would require another conditional entry and .gitconfig-work-acme-archery config file.

I did find that with the nested directory approach the last entry wins so you have to put more specific values at the end.

This effectly translates an if or switch statement in my profile to explicit .gitconfig entries and config files. I'm not sure if I'll stick with it but I'll test drive it for now.