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.

#!/usr/bin/env ruby

# Make sure that the user has a MyCompany email address before committing
# to a repository that contains 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
end

Obviously there’s much more we could do with this (ensure non-company repos don’t get commits under company email addresses for one), but this simple version solves the immediate problem.

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 nice way of setting a per-user template directory for hooks on StackOverflow.

Comments