As a consultant, I work in different code repositories for ThoughtWorks, our clients and also some personal projects. And for each of these, I have different needs when using git. For example, I commit with different emails depending on the environment I’m working for: I commit with my ThoughtWorks email address for ThoughtWorks’s internal projects, client’s corporate email address for the project I’m assigned to and my own personal email for my side projects.
I also happen to organise my workspace in different ‘environments’ or subfolders: ~/Workspace/thoughtworks, ~/Workspace/client and ~/Workspace/gorkaio. So, all of the individual repositories I work with for ThoughtWorks would be like:
While the client repositories would live in:
And my personal repositories… well, you get the idea.
Setting git config locally for each repository I work with quickly becomes a painful and error-prone practice when the number of repositories grows, so I decided to automate switching my git persona according to the environment I’m working with. Here’s how to make git config aware of the repository path, and not only the repository in isolation.
Using git conditional includes it is possible to include a git config file in the global settings depending on some condition. One of the possible conditions is gitdir, the location of the git directory. If the given value matches the location of the git directory, we can include another file like its contents were declared right in the spot where the conditional include happened:
; include for all repositories inside $HOME/to/group
path = /path/to/foo.inc
Knowing this, we can just create a git config file in each of the workspace subfolders and have it included in our main gitconfig file whenever we are in a repository under that path, by adding this to our ~/.gitconfig file:
path = ~/Workspace/thoughtworks/.gitconfig
path = ~/Workspace/client/.gitconfig
path = ~/Workspace/gorkaio/.gitconfig
And, for each of these environments or subfolders, we can create a `.gitconfig` file that will be included whenever the repository we are working with is under a matching path:
name = Gorka López de Torre
email = firstname.lastname@example.org
Ta-dah! Now my name and email will be switched according to the environment I’m working in and I will never make a commit in a client project using my personal email.
Of course, this not only applies to switching your user email: you could also use very specific aliases or other configurations depending on the environment like, for a more interesting example, change the default SSH behaviour of git using core.sshCommand to automatically choose a particular certificate.
Give it a try and let me know if you found it useful! And, if you liked this post, consider buying me a beer with the Paypal donation button bellow 🙂