Conditional git profile configuration

tastefulelk

Sebastian Bille

Posted on March 3, 2021

Conditional git profile configuration

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
Enter fullscreen mode Exit fullscreen mode
// ~/code/work/.gitconfig
[user]
    email = work@example.com
Enter fullscreen mode Exit fullscreen mode

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! 🚀

💖 💪 🙅 🚩
tastefulelk
Sebastian Bille

Posted on March 3, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related