How to add JSCS to your pre-commit hook
I recently came across JSCS and thought it would be a great addition to our git flow to enforce consistent code style for all of our JavaScript code.
JSCS is a code style checker for JavaScript. It lets you decide if you prefer your if
’s with or without a space after them; if you’re OK with declaring multiple variables with one var
keyword; if your lines shouldn’t go over 80 characters; etc. A lot of it is a matter of taste of course, but the main goal is consistency.
So far we’ve been pretty good at having a fairly homogeneous style in our JavaScript files, but as our team grows, new people need to adapt to the implied preferences of our code base. Adding JSCS means that our style guide is codified in JSCS’ config file and less prone to interpretation.
Having it as part of our pre-commit hook results in less time spent in code reviews saying things like “if you don’t mind, you missed a space here”. Some might think it’s nitpicky, but we’re looking at it with the broken windows theory in mind.
So, here is the addition we made to our precommit hook to run JSCS on any JavaScript files that are staged:
It’s fairly simple: we use git checkout-index
to output the staged files to a temporary folder, run JSCS against it and print out any errors, and stop the commit if there are any errors.
The main drawback is that you can only really run JSCS against a full file and not just the diff. So even if you change only one line in a file, you’ll have to fix all the existing errors in that file, and the related pull request will be more cluttered than necessary. But that should only be a transitional period: once all your files have been cleaned up, you will get errors only on the changes you’ve made.
Here are some tips to keep the initial cleanup manageable:
- Cleanup your whole codebase in one big pull request containing only style fixes. We did that mostly but split the cleanup by modules: models first, then collections, etc.
- On GitHub, on a pull request or commit page, you can add
?w=1
to the URL to hide all whitespace-related diffs (from GitHub’s blog). This won’t cover all the changes caused by JSCS, but probably most of them. - Improve the hook to only keep errors for the staged lines. This is a bit tricky to write and probably not worth the hassle since eventually we’d like to have the whole project properly styled.
How to add this to your pre-commit hook
- Install JSCS (see instructions).
- Create a file named
.jscs.json
with your preferred options. As a starting point, you can check our current configuration. - Paste the script above to your pre-commit hook in
.git/pre-commit
. (see the git documentation for more details) You’ll need to addJSCS_PATH
to your environment, pointing to wherejscs
lives. - Proceed to commit perfectly styled code!