Path-Aware "Smart" Git Config

in Programming & Dev2 years ago

Introduction

For people who have become a committer in several open source organizations and were assigned email addresses specific to these organizations, if they prefer attributing contributions to the corresponding email addresses they got, they have to set separate git config for each repository, or else the email used for Git commits will be the global default.

However, Git 2.13 introduced conditional configuration includes, which when combined with the gitdir: keyword made it possible to import Git configuration from different files for repositories under different directories.

git-iif.png

Configuration

First, upgrade your Git if it's below version 2.13! Next, create a new file with organization-specific settings like user.email and user.name. Last, add an [includeIf] sections like the one below to your ~/.gitconfig. Remember to try it out by creating a new repository under the gitdir path!

$ tail -n5 ~/.gitconfig
[user]
  name = harryl
  email = harryl@example.com
[includeIf "gitdir:~/Repos/work/"]
  path = .gitconfig-work
$ cat ~/.gitconfig-work
[user]
  email = i@work.o

Trivia Facts

  • Actually I have put ** at the end of each gitdir condition in my config, but there's no difference as long as the pattern ends with /. In this case, ** is implied and will be automatically added.
  • Included file path is searched relative to the main config file, so we could simply use a relative path like .gitconfig-work.