This article was something I wrote for our team in an internal wiki a few years ago, the code is not pretty but it does the job.
Linting is good, right. Keeps the code consistent and catches trivial mistakes early. The Ruby go-to linter is called RuboCop. It’s used in many OSS project as in in-house projects. Some like it and some don’t, on whatever side you are on the usage will often result in commit histories like this:
It’s not only cluttering the commit history but many minutes are spent weekly fixing failed CI pipelines because the trivial things RuboCop is whining about. In the worst case running a rubocop -A
will not fix the issue but you need to start changing the implementation (or disabling some RuboCop rules) and when you’re done with the fixes you probably forgot what you actually were doing.
A cure to all this context switching is to commit often and run RuboCop before committing. This article will present a way to automate the linting to every commit you do.
Global git commit hook executing RuboCop (or any other linter out there)
Start by creating a folder for your local pre-commit hooks.
In there create two files.
~/dot_files/git-hooks/pre-commit The file that git calls every time a commit is about to happen
~/dot_files/git-hooks/pre-commit.rubocop The file that executes RuboCop on all the staged files
To allow the hooks to get executed we need to make the files executable
The last step of the game is to configure a global hooks folder for git
Now RuboCop will be executed on the files you changed on each commit. If for some reason you want to commit something that is violating the rules the pre-commit hooks can be skipped with the --no-verify
parameter to the commit command.