Skip to content

Instantly share code, notes, and snippets.

@jtbonhomme
Created July 20, 2019 17:58
Show Gist options
  • Save jtbonhomme/d576cc1bd0572f7b90de8fc522372919 to your computer and use it in GitHub Desktop.
Save jtbonhomme/d576cc1bd0572f7b90de8fc522372919 to your computer and use it in GitHub Desktop.
Gitlab pre-receive hook
#!/bin/bash
#
# pre-receive hook for Commit Check
#
COMPANY_EMAIL="mycorp.org"
readonly PROGNAME=$(basename $0)
readonly PROGDIR=$(readlink -m $(dirname $0))
check_single_commit()
{
#
# Put here any logic you want for your commit
#
# COMMIT_MESSAGE contains commit message
# COMMIT_AUTHOR contains commit author (without email)
#
# Set COMMIT_CHECK_STATUS to non zero to indicate an error
if [[ "$COMMIT_MESSAGE" =~ ^(refacto|feat|test|fix|style|docs|chore|perf):[[:space:]].*$ ]]
then
COMMIT_CHECK_STATUS=0
echo "Commit message is conform."
else
COMMIT_CHECK_STATUS=1
echo "Commit message \"$COMMIT_MESSAGE\" is not conform."
echo "The push has been refused by the server."
echo "You can change you commit message with the command: git commit --amend -m \"<NEW MESSAGE>\""
fi
}
check_all_commits()
{
if [ "$OLD_REVISION" = "0000000000000000000000000000000000000000" ]
then
OLD_REVISION=$NEW_REVISION
fi
REVISIONS=$(git rev-list $OLD_REVISION..$NEW_REVISION)
IFS='\n' read -ra LIST_OF_REVISIONS <<< "$REVISIONS"
for rid in "${!LIST_OF_REVISIONS[@]}"; do
REVISION=${LIST_OF_REVISIONS[rid]}
COMMIT_MESSAGE=$(git cat-file commit $REVISION | sed '1,/^$/d')
COMMIT_AUTHOR=$(git cat-file commit $REVISION | grep committer | sed 's/^.* \([^@ ]\+@[^ ]\+\) \?.*$/\1/' | sed 's/<//' | sed 's/>//' | sed 's/@$COMPANY_EMAIL//')
check_single_commit
if [ "$COMMIT_CHECK_STATUS" != "0" ]; then
echo "Commit validation failed for commit $REVISION ($COMMIT_AUTHOR)" >&2
exit 1
fi
done
}
# Get custom commit message format
while read OLD_REVISION NEW_REVISION REFNAME ; do
check_all_commits
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment