I use git as version control, it is great! But I use different email addresses in different situations and sometimes I get it wrong. Not a terrible problem but quite an annoyance. Let me show you an example:
I recently contributed to the PowerShell repository (you can see my pull request here: https://github.com/PowerShell/PowerShell/pull/6464) and I did an annoying mistake, I used the wrong email address. I have my work email configured in my global git config and sometimes I forget to change that to my private email when contributing to open source projects on GitHub.
So what? Does it really matter?
Not really, but when looking at the log I find it annoying to see the wrong email.
Is there a solution?
Yes, apparently there is! You can’t (or shouldn’t) change what has already been pushed, but we can make sure it doesn’t happen again. I just dove into the world of git hooks and learned about something called a pre-commit hook.
A what-hook you said?
Alright so let’s take this from the beginning. The git client has something called hooks. It’s basically a set of events that can trigger a script. One of these events is called pre-commit and is called every time you do a commit. Simply create a file in the folder .git\hooks named pre-commit (yes, without any extension) and git will run it before every commit. These scripts are not synced to your remote repository, they will only stay on your local machine. Cool huh?
OK, so how does that help me?
I wrote a short PowerShell script that finds out the address of the remote called “origin” and based on that determines which email I want to use. So for example, if my repository is cloned from GitHub, I’ll default to my private email.
But then I have to copy that script to each repository?
Yes, that is a problem! Now I’ll forget to copy the hook to a repo and I’m back where I started. Until I found that in git 2.9 a new config setting was introduced. Now you can configure a global hooks directory!
I used this command:
git config --get core.hooksPath '~/.githooks'
Then I created a folder in my profile called “.githooks” and there I created a script called “pre-commit” (without an extension). In this script I’ve hardcoded the email I want to use for each source so the next time I contribute to PowerShell I’ll get my private email in the log. This is how it looks in my PowerShell console when I do a commit:
You can find my pre-commit hook as a gist here: https://gist.github.com/SimonWahlin/91e974c9128f164ea840b6a8e09e7bd8
Which else uses can you think of where a hook would work? Write a comment!