Last active
February 22, 2023 12:49
-
-
Save stevenharman/f5fece7fd39356e57ce3c710911f714f to your computer and use it in GitHub Desktop.
A Git Pre-Commit hook to run the Rubocop static code analyzer. I'm not saying this is a Good Idea™. In fact, it's a Bad Idea™; integrate linting/formatting with your editor/IDE instead. Use at your own risk. If it breaks, feel free to keep both pieces.
This file contains hidden or 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
#!/usr/bin/env bash | |
set -eu | |
RED='\033[0;31m' | |
GREEN='\033[0;32m' | |
YELLOW='\033[0;33m' | |
NO_COLOR='\033[0m' | |
CLEAR_LINE='\r\033[K' | |
printf "🚔 Linting with Rubocop..." | |
if ! command -v bin/rubocop > /dev/null; then | |
printf "${CLEAR_LINE}💀${RED} Install Rubocop and be sure it is available on your PATH${NO_COLOR}\n" | |
printf "ℹ️ Try 'gem install rubocop'\n" | |
exit -1 | |
fi | |
suspects="$(comm -12 <(git diff --cached --name-only --diff-filter=AMC | sort) <(rubocop --list-target-files | sort) | tr '\n' ' ')" | |
if [ -n "$suspects" ]; then | |
if [[ ! -f .rubocop.yml ]]; then | |
printf "${CLEAR_LINE}${YELLOW}⚠️ No .rubocop.yml config file.${NO_COLOR}\n" | |
fi | |
printf "${CLEAR_LINE}🚔 Linting files: ${suspects}" | |
# Run rubocop on the staged files | |
if ! bin/rubocop --parallel --format simple ${suspects} > /dev/null | |
then | |
printf "${CLEAR_LINE}${RED}💀 Rubocop found some issues. Fix, stage, and commit again${NO_COLOR}\n" | |
printf "ℹ️ Try 'bin/rubocop --display-cop-names --extra-details --auto-correct && git add -p'\n" | |
exit -1 | |
fi | |
fi | |
printf "${CLEAR_LINE}🎉${GREEN} Rubocop is appeased.${NO_COLOR}\n" | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is great!
Thanks for sharing it.
@stevenharman