Skip to content

Instantly share code, notes, and snippets.

@mckeed
Last active April 15, 2024 23:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mckeed/baa6ce5d85b28ef5690bfa025890fb0d to your computer and use it in GitHub Desktop.
Save mckeed/baa6ce5d85b28ef5690bfa025890fb0d to your computer and use it in GitHub Desktop.
Run rubocop on only staged files in git pre-commit
#!/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
@mckeed
Copy link
Author

mckeed commented Oct 6, 2023

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 to bin/rubocop or just rubocop if you don't want to use bundle exec.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment