Make git ask my email every time I commit

Viewed 248

I used to make git commits only with my personal email address. Now I have started working as a software developer. I want to use my work email address for my work repositories and my personal email address for personal repositories. I use git config user.email "username@example.com" to do this. The problem is that I have a lot of repositories and I sometimes forget to set user.email. Sometimes, I commit and push with the wrong email address.

Is there a way to force git to not allow me to commit if user.email is not explicitly set for a repository? I removed user.email from my global ~/.gitconfig, but then git uses username@hostname.local as my commit email address.

I'm using git version 2.18.0 on MacOS High Sierra. I installed git using homebrew.

1 Answers

You can use conditional includes to include a different configuration file for some path. This way you can set a global email address and different other email addresses for the repos stored in certain directories (and their subdirectories). You should also set user.useConfigOnly to true to forbid Git guess the email address when it is not set.

My ~/.gitconfig contains these sections:

[user]
    name = John Doe
    # The default email, used for personal projects
    email = john.doe@example.org
    # This prevents Git guess the email address if it is not set
    useConfigOnly = true

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

The file ~/.config/git/config-work looks like this:

[user]
    name = John Doe
    email = john.doe@company.org

It is loaded only for the repositories located in ~/work or its subdirectories.

You can use multiple [includeIf] sections in your ~/.gitconfig file if you need it. Each included file can overwrite the configuration entries listed in ~/.gitconfig or add new entries as needed.

Related