Last active
January 24, 2025 17:47
-
-
Save mckeed/baa6ce5d85b28ef5690bfa025890fb0d to your computer and use it in GitHub Desktop.
Run rubocop on only staged files in git pre-commit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
STAGED_FILES=$(git diff-index HEAD --name-only --cached) | |
if [[ -z $STAGED_FILES ]] | |
then | |
exit # no staged files, no need to run rubocop | |
fi | |
# Checks if any staged files have unstaged changes | |
# otherwise rubocop isn't running on what is actually | |
# going to be committed. | |
WARN_FILES=$(git diff-files --stat -- $STAGED_FILES) | |
if [[ -n $WARN_FILES ]] | |
then | |
echo 'There are unstaged changes to files (git stash --keep-index to commit safely):' | |
echo "$WARN_FILES\n" | |
exit 1 | |
fi | |
echo "Running rubocop..." | |
exec git diff --cached --name-only --relative --diff-filter=ACMR | xargs \ | |
bundle exec rubocop --force-exclusion \ | |
--autocorrect-all --fail-level A \ | |
--format simple \ | |
--parallel --cache true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that this applies RuboCop's unsafe autocorrect (
-A
) option, but still prevents the commit if all the offenses were corrected. The changes it makes won't be staged in git yet, so it should be easy to undo them if it isn't what you wanted.Change
bundle exec rubocop
tobin/rubocop
or justrubocop
if you don't want to usebundle exec
.