raw.githack.com

Per-directory git configuration Sometimes, you want different config files to be in action based on the directory you're in

Let’s jump right to the example from my practice. At my job, we have a self-hosted git solution where internal emails are used for authentication. At the same time, sometimes I need to work on open-source projects used by our company services, and want to send patches there signed off with my personal email.

There are multiple approaches to this.

The first is to have per-project git configurations. This works if you have just a few repos, and you need not to forget to reconfigure every new project you create or clone. The second approach is to override a commit’s author using environment variables or one-run configuration changes each time you do commit your changes. This is even more cumbersome.

The third approach and easiest one is to use conditional includes in your global config file. Let’s say all your work-specific repos are located in ~/work directory. Then, you can have something like this in your global ~/.gitconfig file:

[user]
name = John Doe
email = john.doe@gmail.com

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

This way, if your git directory is a subdirectory of ~/work, git will include configuration from ~/.gitconfig.work, in which you can easily override your email (and any other configuration if you want), as simple as that:

[user]
email = john.does@my-company.com

So now, when you do commit in your ~/work/super-secret-project, your john.does@my-company.com will be used as an email, while if you do that in ~/open-source/dependency your regular john.doe@gmail.com will be used instead! Voila!

Happy hacking!