Git pre-commit hook to help with multiple identities

I use git both at work and for personal projects. Unfortunately I always forget to properly set my user.email and user.name for new work repositories, and so I end up committing under my personal email address. No big deal, but not exactly brilliant either.

When this happened again recently I decided it would be the last time. Enter Git hooks. By using a pre-commit hook I now make sure I never commit to a repo with a mycompany.com remote unless the configured user email address is a mycompany.com address.

Update 2016-03-20: Updated to also catch the case of committing under a company email address without a mycompany.com remote.

#!/usr/bin/env ruby

# Make sure that users with a MyCompany email address can only commit to
# repositories that contain a MyCompany remote.

useremail=`git config user.email`
remotes=`git remote -v`

if remotes.match(/mycompany\.com/) and not useremail.match(/mycompany\.com/) then
    puts "Pre-commit error: #{useremail.strip} is not a MyCompany email address "
    puts "but this repository has MyCompany remotes."
    puts
    exit 1
elsif useremail.match(/mycompany\.com/) and not remotes.match(/mycompany\.com/) then
    puts "Pre-commit error: MyCompany email address used for repository with no MyCompany remotes."
    puts "Remotes:"
    puts (remotes.strip)
    puts
    exit 1
end

This code goes in a pre-commit file in your repo’s .git/hooks directory, or in your Git templates directory to apply to all future repos (C:\Program Files (x86)\Git\share\git-core\templates\hooks on my machine. You can apply it to existing repos by re-calling git init which will re-copy the templates). The file needs to be executable (which it is if you’re running Windows :)), and you’ll obviously need Ruby for this specific example.

For more information and some much more impressive examples of Git hooks, have a look at Glenn Gillen’s post on Slaying dragons with git, bash and ruby.

Update 2011-06-15: Found a StackOverflow answer with a nice way of setting a per-user template directory for hooks using init.templatedir.

Comments