Using includeIf to manage your git identities
If you’re like me, you work on different projects for different companies, or maybe you work for your company and you work on your personal projects. While doing so, I found it annoying to have to set my name and e-mail address for every single project.
Of course, you can set your options globally (with git config --global
), but this wasn’t the answer for me, since I have a strict policy of what e-mail address I use where. So, I went out looking for another option, and it turns out, there is.
Git config has a great manual on what you can do with your configuration files. One of those options is includes and another is conditional includes. Since my projects are structured in a nice way on my disk, I chose the latter.
All my projects are on my disk in a directory SOURCE
. Since I’m on Windows, this makes it C:\SOURCE
for me. Inside that directory, I have sub-directories for PERSONAL
, COMPANY1
, COMPANY2
, et cetera. For each of these, I want to be able to specify different options that I can’t set globally, because they aren’t necessarily the same on each repository. Using includeIf
, I came to the following solution.
(Part of) my ${HOME}\.gitconfig
looks like this:
[includeIf "gitdir:C:/SOURCE/PERSONAL/"]
path = .gitconfig-personal
[includeIf "gitdir:C:/SOURCE/COMPANY1/"]
path = .gitconfig-company1
[includeIf "gitdir:C:/SOURCE/COMPANY2/"]
path = .gitconfig-company2
You’ll notice a couple of things:
- I used forward slashes, since Git doesn’t care and it saves me the trouble of escaping them (if so required? I don’t know, really);
includeIf
operates on (partial) paths, so the include works for every repository that I cloned inside the directories specified;- The
path
parts are relative, which means relative to the file that includes them (${HOME}\.gitconfig
), rather than relative to the repository they operate on.
So, I can now create the included .gitconfig-…
files in my home directory and specify the options I need to override there, rather than globally. Here’s my ${HOME}\.gitconfig-personal
:
[user]
name = Gillis J. de Nijs
email = gillis@home.tld
And here’s an example of ${HOME}\.gitconfig-company1
:
[user]
name = Gillis de Nijs
email = gillis.de.nijs@company1.tld
In conclusion, I never have to specify my name and e-mail address ever again for any repository. If I do, that means I haven’t configured an include for that directory (or company), yet, and I can easily specify it once, and never have to worry about it again.
Turns out, reading manual pages every now and then is very much worth your time.
TL;DR: Conditional includes are a powerful way to customize your git when certain conditions are met. Everything you need to know is in the manual.