The global configuration file for git resides usually at ${HOME}/.gitconfig
which is also the place where settings like git config user.name "John Doe"
end up when you set them (only when applied outside of a git repository).
A while ago I was revisting my settings and decided to split the file into smaller chunks, which I placed in ${HOME}/.config/git
and looks like this.
.
├── conf
│ ├── aliases.gitconfig
│ ├── settings.gitconfig
│ └── user.gitconfig
└── config
Any configuration file under conf
gets added to config
by include statements which bascially look like this:
[include]
path = ./conf/user.gitconfig
path = ./conf/settings.gitconfig
path = ./conf/aliases.gitconfig
[init]
defaultBranch = main
[fetch]
prune = true
user.gitconfig
is exactly what one would expect: the configuration of my default user name and email.
Let's assume you have repositories that require different identities, e.g. a work repository vs a private repository.
One way to solve this issue would be to configure the identity in the repository like
git config user.name "John Doe"
which will then end up in <GITCHECKOUT>/.git/config
and as you might already suspect that this gets easily tedious and is very error prone, but
One awesome feature of the git configuration files is that you can conditionally include config files, and this is what does the trick.
[include]
path = ./conf/user.private.gitconfig
path = ./conf/settings.gitconfig
path = ./conf/aliases.gitconfig
[includeIf "gitdir:~/src/work/"]
path = ./conf/user.work.gitconfig
[init]
defaultBranch = main
[fetch]
prune = true
By default, the configuration from user.private.gitconfig
is always set. Once a repository is located inside ${HOME}/src/work/
, my work identity is being included which has my work email address and the corresponding username configured.
This simple trick simplified my setup by leaps, as I have ${HOME}/.config/git
available everywhere, but I usually tend to forget to set the correct email and username after cloning.
Furthermore, this is of course not limited to user name and email, but to any configuration parameter that can be used in .gitconfig
.