Conditional git profile configuration

ยท

2 min read

I always found it inconvenient that I had to either keep changing the email in my .gitconfig every time I wanted to switch between working on a personal project and a work project, or I had to remember to configure the email in each repository as I cloned it. I often forgot and git discipline being something of a pet peeve of mine, I spent way too much time rewriting history just to change my darned email address so that it wouldn't be inconsistent in the git log. I have a problem, I know but let's keep on topic here mmhkay?

Turns out, there's a much easier way to do this. It's possible to conditionally extend the git configuration based on where your repository is located in your file system. That means we can have a global git configuration with all the default configuration and then in a few overrides for all repositories within, for example, the ~/code/work/ folder by adding a little something like this to the ~/.gitconfig file.

// ~/.gitconfig
[user]
    name = Sebastian Bille
    email = personal@example.com

[includeIf "gitdir:~/code/work/"]
    path = ~/code/work/.gitconfig
// ~/code/work/.gitconfig
[user]
    email = work@example.com

Now all repositories inside of the ~/code/work/ folder will use your overridden email but all others will keep using the default configuration.

This could of course be used to override or add any other configuration conditionally as well.

If you enjoyed this guide and want to see more, follow me on Twitter at @TastefulElk where I frequently write about serverless tech, AWS and developer productivity!

Happy hacking! ๐Ÿš€

Did you find this article valuable?

Support Sebastian Bille by becoming a sponsor. Any amount is appreciated!

ย