Using Git Conditional Includes for Multiple Configurations

 
 
  • Gérald Barré

When working across multiple Git repositories, you often need different configurations for each context. For example, you might use your personal email for open-source contributions and your work email for company projects. While you can configure Git globally or per repository, managing these settings manually becomes tedious and error-prone.

Git's conditional includes feature solves this problem by automatically applying different configurations based on criteria like repository location, remote URL, or branch name. This ensures the correct settings are always used without manual intervention.

Here's a practical example that applies specific configuration when working with your personal GitHub repositories:

Gitconfig
[includeIf "hasconfig:remote.*.url:https://github.com/meziantou/*"]
    path = .gitconfig-github-personal

When Git detects a remote URL matching this pattern, it automatically includes the settings from .gitconfig-github-personal, which might contain your personal email and signing key.

#Understanding Git Conditional Includes

Git supports several condition types for conditional includes, each serving different use cases:

##gitdir - Match by Repository Path

The gitdir condition matches repositories based on their filesystem path. This is case-sensitive on Unix-like systems.

Gitconfig
[includeIf "gitdir:~/personal/"]
    path = .gitconfig-personal

[includeIf "gitdir:~/work/"]
    path = .gitconfig-work

This applies .gitconfig-personal to all repositories under ~/personal/ and .gitconfig-work to repositories under ~/work/.

##gitdir/i - Case-Insensitive Path Match

Similar to gitdir, but case-insensitive. Useful on Windows or when you need flexible path matching.

Gitconfig
[includeIf "gitdir/i:c:/projects/company/"]
    path = .gitconfig-company

##onbranch - Match by Current Branch

The onbranch condition applies configuration based on the currently checked-out branch.

Gitconfig
[includeIf "onbranch:main"]
    path = .gitconfig-production

[includeIf "onbranch:feature/**"]
    path = .gitconfig-development

This is useful for applying different settings when working on production versus development branches.

##hasconfig - Match by Existing Configuration

The hasconfig condition checks if a specific configuration value exists and matches a pattern. This is particularly useful for matching remote URLs.

Gitconfig
[includeIf "hasconfig:remote.*.url:https://github.com/meziantou/*"]
    path = .gitconfig-github-personal

[includeIf "hasconfig:remote.*.url:git@company.com:*/**"]
    path = .gitconfig-company

This allows you to apply different configurations based on where your repository is hosted, regardless of its local path.

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub