Git commit hooks can seem like magic, and are hella useful. Whether running some unit tests, or scanning for coding standards. If you know git, and don’t use git commit hooks, you are missing some awesome free help.
What is a git hooks ?
Git hooks are amazingly simple tools. They are scripts to run when you do certain git actions,like after the repository receives a push. In each git project there is a .git directory, full of magic. Along with metadata on the project, one of the folders in there is .git/hooks/. Check it out:
$ ls example/.git/hooks
applypatch-msg post-commit post-update pre-commit update
commit-msg post-receive pre-applypatch pre-rebase
Each of those is simply a scripts that will happen when you run the related git action. Part of the magic is that if the script exits with an error, the action doesn’t complete.
Why a commit hook?
Commit hooks are easily the most useful hooks. Want to scan your project to be pep8 complaint during check-in? Easy. Want to run a spell checker during fresh pull of markdown files from an sp3ll-fail prone collegue? Also easy!
Here’s a quick example script, for running pep8 on *changed files only* when doing a commit. By stashing this into the file .git/hooks/pre-commit and settings that file to executable, a developer can’t commit, until pep8 succeeds.
# find files git lists as changed for this commit
modified = re.compile('^[AM]+\s+(?P
It can be used for more than just work though. Want to play a frustrating prank on a friend? Just update one of their .git/hooks/pre-commit files to contain:
They won’t be able to commit to that repository, and (probably) will get driven a bit crazy figuring out what is failing.