5 July 2017

A pre-commit hook to block tab-indented code

I work in a team who use a mix of Windows and Mac machines to review and edit code. In fact I myself use a mix, coding on an iMac in the office but a Windows machine at home. This scenario seems to be becoming more and more common these days and with the distributed nature of open source projects it's almost guaranteed code will travel across platforms during it's life.

Avoiding tab-indentation is the best way to ensure code looks the same on all code editors/viewers including Mac, Windows, Vim and the GitHub website. It's just sensible and courteous to try and ensure code is visually formatted in a consistent manner for all contributors. Tabs are not consistent. Use spaces.

So now that's settled lets move on to how to enforce that policy on a day-to-day basis...

Switching your code editor to indent using spaces by default goes a long way. But if you are managing legacy code - written before you decided to set a standard - you may be opening files with hundreds of lines of tab-indented code but wanting your new lines to be indented with spaces. If you hit "Return" at the end of an indented line, most code editors will try and be friendly by auto-completing to whatever the previous line uses so even with your code editor defaulting to use spaces you can easily end up accidentally generating some tab-indented lines. It's clear we need a guardian to watch over us and catch these mistakes!

So I made a Git pre-commit hook that lints (checks) your newly added lines (only the new lines) for tab indentation and stops the commit if it finds any, printing a handy report to the command line when it does. Download the hook at https://github.com/martinjoiner/portable-code-pre-commit-hook