Git has the concept of hooks: bash scripts that are invoked at certain points in the Git lifecycle. One handy use is a pre-push hook that runs Rubocop. It will prevent pushing code that Rubocop finds fault with.
Configuring the hook
Git hooks are normally stored locally with a repository. They are not committed.
- Store this snippet in .git/hooks/pre-push:
if [ -f ./.rubocop.yml ]; then
echo 'Running Rubocop ...'
bundle exec rubocop --parallel
fi
chmod +x .git/hooks/pre-push
The snippet only executes Rubocop if it finds a .rubocop.yml file. Which makes it suited for a global Git hook:
Global Git hooks
Starting from Git 2.9, you can choose to configure your Git hooks globally.
- Configure your global Git hooks directory:
git config --global core.hooksPath ~/.githooks
- Store the above snippet to
~/.githooks/pre-push
chmod +x ~/.githooks/pre-push
Execution
Whenever you push, Rubocop will automatically run, and prevent the push if unsuccessful.
Note that Rubocop has some kind of caching, i.e. subsequent runs will be orders of magnitude faster than the first.
Should you want to skip that pre-push hook, push with --no-verify
.
Posted by Dominik Schöler to makandra dev (2024-11-22 14:24)