Last active
May 7, 2021 00:29
-
-
Save ggaona/1958f80e8495938f4cb9880b5239e874 to your computer and use it in GitHub Desktop.
Rubocop pre-commit git hook
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/bash | |
# Execute Rubocop before committing; aborts commit if any offense is found. | |
# By ggaona | |
# Get files to be analyzed (all staged files with '.rb' or '.rake' extension; | |
# ignores 'schema.rb', migrations and deleted files) | |
STAGED_FILES=$(git diff --name-status --cached | grep -E '\.rb|\.rake' | grep -Ev 'D|schema.rb|migrate') | |
# Get total count of files to be analyzed | |
FILE_COUNT=$(printf "%s" "$STAGED_FILES" | grep -c "^") | |
# Continue to commit if there are no files to analyze | |
if [[ $FILE_COUNT -eq 0 ]]; then | |
exit 0 | |
fi | |
# Get new and modified files | |
FILES=$(printf "$STAGED_FILES" | grep -E 'A|M' | awk '{print $2}') | |
# Add renamed files | |
FILES="$FILES $(printf "$STAGED_FILES" | grep -E 'R' | awk '{print $3}')" | |
# Execute rubocop | |
echo "[RuboCop]" | |
rubocop --color $FILES | |
# Abort commit if offenses are found | |
if [ $? -ne 0 ]; then | |
echo "Commit aborted" | |
exit 1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment