git|version control|
This article was inspired by a member of the Roave Discord community asking a question in our “Help and Advice” forum. Come join our Discord and get even more useful tips and advice!
When you’re setting up Git for the first time, configuring your global name and email address is a common first step. If you’ve configured Git before, chances are you’ve executed a command like the following:
git config --global user.name 'Charles Sprayberry'
git config --global user.email 'charles@example.com'
If you have some repositories that need to use a different configuration, you can easily do so by executing the command from the repo directory and removing the --global flag.
cd /your/repo/path
git config user.name 'cspray'
git config user.email 'cspray@example.com'
However, setting your credentials per repository has a drawback. When you create a new repo, you have to make sure you configure it. If you don’t, your global configuration will be used, or you won’t be able to make commits until credentials are defined.
Fortunately, Git provides a mechanism to easily define a configuration for a set of repositories.
Imagine you have a directory storing your personal projects and another directory storing your employer’s projects. It could look something like the following:
/Code
/personal
/project-a
/project-b
/employer
/app-x
/app-y
/app-z
We can set up the configuration for these repositories—and any new repos added to these directories—by creating, or modifying, three `.gitconfig` files. The first will be the global Git config, then we’ll create a configuration in the directories /Code/personal and /Code/employer.
In our global configuration we’ll use the includeif directive to conditionally include a Git configuration based on which directory our repo is in. We’ll add the following configuration to our global config file. You can execute git config --list --show-origin to find the correct file. Generally, this should be located at ~/.gitconfig in Linux systems.
[includeif "gitdir:/Code/personal/"]
path = /Code/personal/.gitconfig
[includeif "gitdir:/Code/employer"]
path = /Code/employer/.gitconfig
Now, create a file at /Code/personal/.gitconfig. This will have the credentials configured for all of your personal repositories.
[user]
name = cspray
email = cspray@example.com
Finally, create a file at /Code/employer/.gitconfig. This will have the credentials configured for your employer’s repositories.
[user]
name = Charles Sprayberry
email = charles@employer.example.com
In this article, we show how you can easily setup your Git configuration to have different credentials across many repos. This just scratches the surface of what’s possible with Git configurations and the includeif directive.
We highly recommend checking out the Git documentation to learn more ways to improve your Git experience!
If you’d like help optimizing your team’s Git workflow, contact us.