Last Updated: July 25, 2019
·
3.173K
· angelbotto

pre-commit hooks

Pre-commit by @bottico

v0.0.1

I need hooks in git for run rspec and rubocop before commit, for this reason i create this scripts and share with you :)

Pre commit

run all scripts based in variable $HOOKS

#!/bin/sh
HOOKS="pre-commit-rspec pre-commit-rubocop pre-commit-prevent-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

pre-commit-prevent-master

Prevent commit in master

#!/bin/bash

echo -e "[PREVENT] --> init (wait a second)"
BRANCH=`git rev-parse --abbrev-ref HEAD`

if [ $BRANCH == master ]; then
    echo -e "[PREVENT] --> Non shall commit to master!"
    exit 1
else
    echo -e "[PREVENT] --> Prevent commit  approved"
    exit 0
fi

pre-commit-rspec

Run all rspec test.

#!/bin/bash
echo -e "[RSPEC] --> init (wait a second)"

FAILS=`bundle exec rspec --format progress | grep -E '(\d*) failure(s?)' -o | awk '{print $1}'`

if [ $FAILS -ne 0 ]; then
    echo -e "[RSPEC] --> ✋ Can't commit! You've broken $FAILS tests!!!"
    exit 1
else
    echo -e "[RSPEC] --> 👍 Commit approved."
    exit 0
fi

pre-commit-rubocop

Run robocop.

#!/bin/bash
echo -e "[RUBOCOP] --> Init (wait a second)"

FAILS=`bundle exec rubocop | grep 'no offenses detected' -o | awk '{print $1}'`

if [ "$FAILS" == "no" ]; then
    echo -e "[RUBOCOP] --> 👍 approved."
    exit 0
else
    echo -e "[RUBOCOP] --> ✋ You've $FAILS offenses!!!"
    exit 1
fi

Todo

  • better documentation