Skip to content

Instantly share code, notes, and snippets.

@the-spectator
Last active November 2, 2019 05:07
Show Gist options
  • Save the-spectator/b2d8a9d668ca89eb8875617eed73b761 to your computer and use it in GitHub Desktop.
Save the-spectator/b2d8a9d668ca89eb8875617eed73b761 to your computer and use it in GitHub Desktop.
Git Pre-Commit Hook For Rubocop
# Linux Echo colours
red='\033[0;31m'
nc='\033[0m'
black='\033[0;30m'
dark_grey='\033[1;30m'
light_red='\033[1;31m'
green='\033[0;32m'
lgreen='\033[1;32m'
orange='\033[0;33m'
yellow='\033[1;33m'
blue='\033[0;34m'
lblue='\033[1;34m'
purple='\033[0;35m'
lPurple='\033[1;35m'
cyan='\033[0;36m'
lcyan='\033[1;36m'
lGray='\033[0;37m'
white='\033[1;37m'
bold='\033[1m'
#!/bin/bash
source ~/colours.sh
#########################################################################################
# HOW to use it
# 1. Copy pre-commit.sh to your projects .git/hooks
# 2. make sure it is executable, else make it by `sudo chmod +x .git/hooks/pre-commit.sh`
# 3. Copy colours.sh to $HOME directory
# 4. Reload the environment
##########################################################################################
# Array containing all checks/tasks we want to run in hook
hooks=(
rubocop_hook
)
# Function corresponding to check/task in hooks array
function rubocop_hook() {
local status length
# Get all the staged files except deleted files
files=$(git diff --name-only --cached --diff-filter=d)
# Get word-length of files
length=${#files}
# Run rubocop hook only when length is "not equal" to 0
if [[ length -ne 0 ]]; then
echo $files | xargs bundle exec rubocop --extra-details --parallel --force-exclusion
fi
}
function thanks_hook() {
echo "Thank YOU"
}
# Run hooks only when SKIP environment variable is not set
if [[ -z "$SKIP" ]]
then
printf "\n${cyan}${bold}Running pre-commit hooks${nc}\n"
for hook in "${hooks[@]}"; do
${hook}
# Get exit status of command executed
status=$?
# Status is 0 when command exit status when successfully executed
if [[ $status -eq 0 ]]
then
printf "\n${cyan}Check ${bold}$hook${nc} ................................ ${nc}${green}${bold}Passed ✓${nc}\n"
else
printf "\n${cyan}Check ${bold}$hook${nc} ................................ ${nc}${red}${bold}Failed ✗${nc}\n"
fi
done
else
printf "\n${red}${bold}⚠ Skipping pre-commit hooks${nc}\n"
fi
printf "\n\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment