Post

Automatically Set Git Configs Based on the Domain/Server of a Repository

Dynamically set your username, email, or any other setting in .gitconfig depending on the remote URL of a repository.

Automatically Set Git Configs Based on the Domain/Server of a Repository

This is a simple example of how to dynamically adjust settings in .gitconfig based on the remote URL of a repo. In the example below, I am only changing the email address. You can add or override any settings this way.

Make sure your ~/.gitconfig sets all of your preferred default options. Then use includeIf conditions to include another file containing configs. The included file will override any existing settings. You can also set additional settings.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[user]
        name = Jason Raveling
        email = my.email@jasonrav.com

[credential]
        helper = cache --timeout 300

[core]
        editor = vim
        filedMode = false
        autocrlf = input

[pull]
        rebase = false

# Use hasconfig to check if the remote URL is Github.
[includeIf "hasconfig:remote.*.url:https://*.github.com/**"]
    path = /home/jasonrav/.gitconfig-users/github

# Use hasconfig to check if the remote URL is Github.
[includeIf "hasconfig:remote.*.url:git@*.github.com:*/**"]
    path = /home/jasonrav/.gitconfig-users/github

You can use relative paths. I am using SublimeMerge which only works with absolute paths. Be sure to replace jasonrav with your username.

Once you have saved your .gitconfig, be sure the path and file you want to include have been created.

1
2
mkdir /home/jasonrav/.gitconfig-users/ # Create the directory.
touch /home/jasonrav/.gitconfig-users/github # Create the file.

Edit /home/jasonrav/.gitconfig-users/github with any settings you would like to override or add. Any settings will be treated as if it were in the standard .gitconfig file. I am only changing my email address in this example.

1
2
[user]
        email = different.email@webunraveling.com

With this setup, git will use the email from ~/.gitconfig (i.e. my.email@jasonrav.com) by default. When I make commits and push them to Github, the includeIf conditional will insert the configs from /home/jasonrav/.gitconfig-users/github in to the ~/.gitconfig file. This will override my default email address, setting it to different.email@webunraveling.com.

Additional reading

For more details on including files, see the Git Config docs on Includes.

This work by Jason Raveling is licensed under CC BY-ND 4.0 .