Skip to content

Instantly share code, notes, and snippets.

@jtbonhomme
Last active April 13, 2021 10:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtbonhomme/b88cfc3eda108fae75059ae83129d9cb to your computer and use it in GitHub Desktop.
Save jtbonhomme/b88cfc3eda108fae75059ae83129d9cb to your computer and use it in GitHub Desktop.
gitlab pre-receive custom 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
@jtbonhomme
Copy link
Author

jtbonhomme commented Mar 14, 2019

To be installed in /home/git/data/repositories/<GROUP>/<SUBGROUP>/<REPOS>.git/custom_hooks

# curl -o pre-receive https://gist.githubusercontent.com/jtbonhomme/b88cfc3eda108fae75059ae83129d9cb/raw/61f1d87eb5954c143a1d9147a45514d2e1307d83/pre-receive
# chown git:git pre-receive
# chmod 755 pre-receive

@fafucoder
Copy link

good

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