Linting Code before Committing

Code review is probably a developers most frustrating task, and if we are doing it right, then we're doing it all the time. I was listening to episode 251, which talked about Automating Code Reviews using Pronto, a Ruby Gem to automate the most painful part of code reviewing: does the code adhere to the style guides.

I think this is awesome. I'm a big believer in automate the crap to enable the creative. What I don't like is waiting until my codes in a PR or even just a commit until I know if I broke style guides in some areas, which is the default approach that Pronto takes. This produces commits that are just things like Fixes code style. Nobody likes seeing a bunch of those commits in the logs.

I want to know when I try to commit my code if I'm breaking the style for the project, which is a feature that Pronto supports with pronto run --index.

Git is really powerful and with Git Hooks we can automate quite a bit. Using Pronto and a pre-commit hook, we can pretty have Pronto tell us if there's problems in our code before the commit is ever created, shortening our personal feedback loop:

#!/bin/bash

docker-compose run api bundle exec pronto run --index --exit-code  
code=$?

exec < /dev/tty 

if [ $code -gt 0 ]; then  
  echo ""
  echo "Pronto found errors in the code. Do you want to continue? (yes/no)"
  read input
  if [ "$input" == "no" ]; then
    exit 1
  fi
fi  

I use Docker for my development. If you don't, just change the first line from docker-compose ... to pronto run --index --exit-code.

Just drop the code above into .git/hooks/pre-commit and make the file executable with chmod a+x .git/hooks/pre-commit. Now whenever you try to commit, Pronto will check the code that you're about to commit and confirm if you'd like to move on.

Dave Long

Read more posts by this author.

Subscribe to Dave Long

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!