Directory Scoped Git Configuration

I have always had a problem with the configuration of different email addresses in different git repositories. The git configuration is split into a global (~/.gitconfig) and a local/repository part (project_dir/.git/config). This works only for simple setups with one default configuration and 1-2 exceptions with per-repo overrides.

But it does not work for me, I have multiple different repositories checked out and I always forget to configure the right email address after the git clone. And it is not only “normal/private” vs. “work” address but I also have multiple addresses for different customers and open source projects. It’s a mess.

Today I finally learned about a working solution for this with git-config conditional includes. These were introduced in 2017 with git 2.13 and I found them via StackOverflow.

With conditional includes I can have multiple configuration files to overwrite the global values like these two files:

# ~/.gitconfig-bsd
[user]
	name = Martin Schütte
	email = mschuett@netbsd.org
# ~/.gitconfig-work
[user]
	name = Martin Schütte
	email = martin.schuette@example.org

Now my global ~/.gitconfig does two things: it sets a default value, and it also specifies the overwrite files depending on the directory tree:

# ~/.gitconfig
[user]
	name = Martin Schütte
	email = info@mschuette.name
# ...

[includeIf "gitdir:~/projects/work/"]
	path = ~/.gitconfig-work
[includeIf "gitdir:~/projects/bsd/"]
	path = ~/.gitconfig-bsd

The gitdir directories are prefixes because git will add “**”, thus recursively matching all paths below that directory. So as long as there is some hierarchy in the file system this works.

Comments are closed.