Skip to content

Instantly share code, notes, and snippets.

@stevenharman
Last active February 22, 2023 12:49
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stevenharman/f5fece7fd39356e57ce3c710911f714f to your computer and use it in GitHub Desktop.
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.
#!/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
@davidauza-engineer
Copy link

This is great!

Thanks for sharing it.

@stevenharman

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