A friend showed me his .gitconfig today, which had a feature that blew my mind!

Depending on the URL of his git-repository, the username and email would automatically be set. This comes in very handy in a company that has both internal git-repos and GitHub-repos, since things like names will typically be different, or if your university has a GitLab instance for uni projects, but you also happen to have a GitHub for personal repositories.

I usually ran the following to commands for all repos that were not on GitHub:

git config --local user.email "different@mail.example.com"
git config --local user.name "Different Name"

How do I do this?

First of all, you need to create config files, that only contain the remote-specific settings. I created mine in .config/git/, but you can choose any location. My GitHub config looks like this:

[user]
        name = hoppjan
        email = 83405332+hoppjan@users.noreply.github.com

Rinse and repeat for all your remotes!

Once you have created the remote-specific files, add them to your ~/.gitconfig:

[includeIf "hasconfig:remote.*.url:*github.com*/**"]
        path = .config/git/config_github

You can, of course, customize the URL-pattern. For example: I used to use HTTPS remotes, but today I mostly use SSH remotes. I omitted https:// in front of the URL, but if you never use SSH, you could add it!

Other Matching Options

You could also match the directory path, if you organized your project directories around your git identities:

[includeIf "gitdir:~/Projects/personal/"]
...
[includeIf "gitdir:~/Projects/work/"]
...

Limitations

After I got things working, I was wondering whether I could inline my config files into the ~/.gitconfig file. Sadly, this does not seem to be the case. The following did not work:

[includeIf "hasconfig:remote.*.url:*github.com*/**"]
        user.name = hoppjan
        user.email = 83405332+hoppjan@users.noreply.github.com

I think this would be a welcome enhancement, but it offers little practical value. Since includeIf seems to work similarly to include, which allows you to include other files to your git config, I doubt this will ever be added to git.

Credit