Skip to content

Instantly share code, notes, and snippets.

@dfop02
Created March 8, 2023 13:45
Show Gist options
  • Save dfop02/c330247eeb5fc0c0f7870a9da67e3df6 to your computer and use it in GitHub Desktop.
Save dfop02/c330247eeb5fc0c0f7870a9da67e3df6 to your computer and use it in GitHub Desktop.
A pre-commit bin file to execute on your Rails application at any moment with few hooks that I frequently use.
#!/usr/bin/env sh
# Where go this file? Rails.root/bin/pre-commit
# How use? Just run "bin/pre-commit install" or "bin/pre-commit uninstall"
# This will execute the file "lib/pre-commits/pre-commit", who will install
# ALL files added on "HOOKS" variable.
current_pre_commit=$(cat .git/hooks/pre-commit 2>/dev/null | sed -n 's/PRE_COMMIT_INSTALLED=//p')
if [[ $1 = 'install' ]]; then
if [[ -z $current_pre_commit ]]; then
for file in lib/pre-commits/*; do
chmod +x $file
cp "$file" ".git/hooks/$(basename $file)"
done
echo Pre-commit successfuly instaled.
else
echo Pre-commit already instaled.
fi
elif [[ $1 = 'uninstall' ]]; then
if [[ $current_pre_commit = 'y' ]]; then
for file in .git/hooks/pre-commit*; do
rm $file
done
echo Pre-commit successfuly removed.
else
echo Pre-commit is not currently instaled.
fi
fi
#!/usr/bin/env sh
# Where go this file? Rails.root/lib/pre-commits/pre-commit
# pre-commit runner, who will set which pre-commits we will use on HOOKS variable.
PRE_COMMIT_INSTALLED=y
HOOKS="pre-commit-rubocop pre-commit-safe-master"
for hook in $HOOKS; do
if [ -f "$PWD/.git/hooks/$hook" ]; then
"$PWD/.git/hooks/$hook"
if [ $? != 0 ]; then
exit 1
fi
else
echo "Error: file $hook not found."
exit 1
fi
done
#!/bin/bash
# Where go this file? Rails.root/lib/pre-commits/pre-commit-rubocop
# This will run the rubocop and commit only if there is no offensives there, with a pretty response.
red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
NC='\033[0m'
echo -e "${green}[RUBOCOP] -->${NC} Init (wait a second)"
FAILS=`bundle exec rubocop | grep -o '[a-zA-Z0-9]\+ offenses detected' | awk '{print $1}'`
if [ "$FAILS" == "no" ]; then
echo -e "${green}[RUBOCOP] --> 👍 approved.${NC}"
exit 0
else
echo -e "${green}[RUBOCOP] -->${NC} ${red}✋ You've $FAILS offenses!!!${NC}"
exit 1
fi
#!/bin/bash
# Where go this file? Rails.root/lib/pre-commits/pre-commit-safe-master
# Stops accidental commits to master/main/develop
BRANCH=`git rev-parse --abbrev-ref HEAD`
if [[ "$BRANCH" =~ ^(master|main|develop)$ ]]; then
echo "You are on branch $BRANCH. Are you sure you want to commit to this branch?"
echo "If so, commit with -n to bypass this pre-commit hook or uninstall pre-commit temporarily."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment