Skip to content
Logo Theodo

Never Commit Something Stupid Again - Sanity-Check your Commit in a Hook!

Foucauld Degeorges2 min read

Today, for the 185th time, I accidentally committed some debugging code on my project. But there won’t be a 186th time.

How hard can it be to get a warning when I’m about to commit a diff that contains certain forbidden strings?

Of course it isn’t - it’s called pre-commit hooks.

And Github user pimterry came up with a pre-commit hook that does just this and lets you choose whether to abort or to commit nevertheless.

Setting it up

To check for the presence of Mocha’s describe.only and it.only methods on my project, I added these two entries to my Makefile:

install-git-hook:
	curl https://cdn.rawgit.com/pimterry/git-confirm/v0.2.1/hook.sh > .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit && make configure-git-hook

configure-git-hook:
	git config --unset-all hooks.confirm.match || echo 'Nothing to clear'
	git config --add hooks.confirm.match 'describe.only'
	git config --add hooks.confirm.match 'it.only'

How it works

Then, run make install-git-hook in your project directory.

Now when you commit a file containing a forbidden string, this is what you get:

keyword-matched

The default configuration includes a few usual suspects such as TODO and @ignore.
Viewing or editing your list of forbidden keywords is all a matter of playing with git config. You can refer to the Git Confirm repo for details.

Liked this article?