Skip to content

Instantly share code, notes, and snippets.

@bkiahstroud
Last active April 19, 2024 19:19
Show Gist options
  • Save bkiahstroud/c1a42f6ecc81cfc2d8a6c3f52f5c2680 to your computer and use it in GitHub Desktop.
Save bkiahstroud/c1a42f6ecc81cfc2d8a6c3f52f5c2680 to your computer and use it in GitHub Desktop.
Run rubocop via Docker Compose as a git pre-commit hook
#!/bin/sh
# Get a list of all staged Ruby (.rb) files
RUBY_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '\.rb$')
# If there are no Ruby files, skip the check
if [ -z "$RUBY_FILES" ]; then
exit 0
fi
# Run Rubocop on the staged Ruby files
echo "Running Rubocop on staged Ruby files..."
docker compose exec -T web bundle exec rubocop -P $RUBY_FILES
# Check if Rubocop passed
if [ $? -ne 0 ]; then
echo "Rubocop detected problems, aborting commit."
exit 1
fi
# If we got here, everything is OK
echo "Rubocop checks passed."
exit 0
@bkiahstroud
Copy link
Author

Instructions

Setup

  1. cd your/repo
  2. touch .git/hooks/pre-commit
  3. chmod +x .git/hooks/pre-commit
  4. Copy the contents of the pre-commit file below into .git/hooks/pre-commit

Test

  1. docker compose up web
  2. Make a change in a .rb file that causes a rubocop warning
  3. git add the file
  4. git commit -m "test"

You should see the output of rubocop and it should prevent the commit from going through

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