Multiple Git Configurations - conditional includes

Today, I got across the git feature conditional_includes. You can specify which git configurations should be applied under which circumstances.

As a software engineer I am used to work on different projects and sometimes for different organizations. I do not want to use the same e-mail address for all git repositories. I made use of the git local configuration to specify the e-mail address I want to show in my git commits for the corresponding git repository (for example: git config --local user.email "Some.Name@TechEule.com").

Using git conditional_includes in the ~/.gitconfig file would reduce unwanted e-mail addresses in the wrong git repositories. There are very useful conditions which can be defined in ~/.gitconfig file.

  • Include for all repositories inside $HOME/dev/organization-1/.

    1
    2
    
    [includeIf "gitdir:~/dev/organization-1/"]
      path = ~/.git-configs/organization-1.inc

    Content of ~/.git-configs/organization-1.inc

    1
    2
    3
    
    [user]
      name = Max Peter
      email = peter.max.org1@organization-1.com

  • Include for all repositories inside $HOME/clients/Xyz-Inc/.

    1
    2
    
    [includeIf "gitdir:~/clients/Xyz-Inc/"]
      path = ~/.git-configs/clients-Xyz-Inc.inc

  • Content of ~/.git-configs/clients-Xyz-Inc.inc

    1
    2
    3
    
    [user]
      name = Max Peter (Xyz)
      email = peterM@xyz-1-inc.com

  • Include only if a remote with the given URL exists.

    1
    2
    3
    4
    5
    
    [includeIf "hasconfig:remote.*.url:https://git.organization-2.com/**"]
      path = ~/.git-configs/organization-2.inc
    
    [includeIf "hasconfig:remote.*.url:git@github.com:organization-3/**"]
      path = ~/.git-configs/organization-3.inc

    Content of ~/.git-configs/organization-2.inc

    1
    2
    
    [user]
      email = MaxPeter@organization-2.com

    Content of ~/.git-configs/organization-3.inc

    1
    2
    
    [user]
      email = PeterMax2@organization-3.com

The examples are copied or inspired from https://git-scm.com/docs/git-config.

Conclusion

When using the above exampels, you can set it up only once and you do not have to re-configure e.g. the user.email when ever you clone a repository.

Resources: