Running Rubocop as a pre-push hook

Posted . Visible to the public.

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.

  1. Store this snippet in .git/hooks/pre-push:
if [ -f ./.rubocop.yml ]; then                                                  
  echo 'Running Rubocop ...'                                                    
  bundle exec rubocop --parallel                                                
fi                                                                              
  1. 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.

  1. Configure your global Git hooks directory: git config --global core.hooksPath ~/.githooks
  2. Store the above snipptet to ~/.githooks/pre-push
  3. chmod +x ~/.githooks/pre-push
Dominik Schöler
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2024-11-22 14:24)