Using Git Configurations per Project

101

At work we use a software development approach called mob programming. We facilitate this by connecting to a shared computer, and we all work on the same code base using rotations. This is great for collaboration and we all get to learn from each other. Part of how we like to present ourselves to clients is by using a single team email and GitHub account. However, we do take breaks and work solo on our own machines to mix it up.

This is where I ran into a problem. I wanted to separate my personal and work git configurations so I wasn't contributing using my personal account. This post will show you a way how to do that.

Workspace Structure

I'm going to assume you have a local workspace setup along the lines of:


~/.ssh
├── personal_rsa # private key
├── personal_rsa.pub # public key
├── work_rsa # private key
└── work_rsa.pub # public key
~/workspace
├── personal
├── personal-project1
├── personal-etc
└── work
├── project1
├── project2
└── project3

What I'd like is a default git configuration to be used unless I specificy otherwise. In this case I want a custom git configuration to kick in when I'm in any git directories within the work directory.

Git Configurations

First, make sure you have a default .gitconfig file in your home directory. This is where you can set your global git configurations. For example, I have the following:

~/.gitconfig

_10
# Very basic example
_10
# See https://git-scm.com/docs/git-config#_configuration_file
_10
[user]
_10
email = personal@email.com
_10
name = Jake Klassen
_10
_10
[init]
_10
defaultBranch = main

Now if you were to type git config --global user.email you would see the email address you set in the .gitconfig file.

Next, we're going to create a new .gitconfig-work file that will be used when we're in the work directory. This is where we can set our work specific configurations. For example, I have the following:

~/.gitconfig-work

_10
[user]
_10
email = email@work.com
_10
name = Team Name
_10
_10
[core]
_10
# This is how we identifiy as another user
_10
sshCommand = "ssh -i ~/.ssh/work_rsa -o IdentitiesOnly=yes"

Includes

Next we're going to leverage conditional includes. We'll use includeIf within our .gitconfig file to include a different configuration file based on the value of the path variable.

~/.gitconfig

_11
# Very basic example
_11
# See https://git-scm.com/docs/git-config#_configuration_file
_11
[user]
_11
email = personal@email.com
_11
name = Jake Klassen
_11
_11
[init]
_11
defaultBranch = main
_11
_11
[includeIf "gitdir:~/workspace/work/"] # Note the trailing slash!!
_11
path = ~/.gitconfig-work

Now, cd into any git directory within your work directory and test out the config by running: git config --global user.email and confirm the result is as expected.

This is pretty easy to repeat for any other situations you may have.

Happy coding!