I'm trying to enforce users to add JIRA ticket to git commit.
I used a pre-recieve hook but it is working only after push. I want it to work after commit so if the message format is incorrect, the commit will fail and the user will have the option to edit the commit.
this is my code example:
#!/usr/bin/env bash
# set this to your active development branch
#develop_branch="master"
#current_branch="$(git rev-parse --abbrev-ref HEAD)"
# only check commit messages on main development branch
#[ "$current_branch" != "$develop_branch" ] && exit 0
# regex to validate in commit msg
commit_regex='(#-[0-9]+|merge)'
error_msg="Aborting commit. Your commit message is missing either a JIRA Issue ('#-1111') '"
rm -rf fl.txt
echo $1 >> fl.txt
fil="fl.txt"
if ! grep -iE $commit_regex $fil; then
echo "$error_msg" >&2
exit 1
fi
rm -rf fl.txt
I was able to get this to work locally by:
<project directory>/.git/hooks/
.sample
from the commit-msg.sample
commit-msg
file in a text editor#!/usr/bin/sh
#
# An example hook script to check the commit log message.
# Called by "git commit" with one argument, the name of the file
# that has the commit message. The hook should exit with non-zero
# status after issuing an appropriate message if it wants to stop the
# commit. The hook is allowed to edit the commit message file.
#
# To enable this hook, rename this file to "commit-msg".
# Uncomment the below to add a Signed-off-by line to the message.
# Doing this in a hook is a bad idea in general, but the prepare-commit-msg
# hook is more suited to it.
#
# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
# grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1"
# This example catches duplicate Signed-off-by lines.
HOOK_FILE=$1
COMMIT_MSG=`head -n1 $HOOK_FILE`
PATTERN="^[A-Z][A-Z0-9]+-[0-9]+"
if [[ ! ${COMMIT_MSG} =~ $PATTERN ]]; then
echo ""
echo " ERROR! Bad commit message. "
echo " '$COMMIT_MSG' is missing JIRA Ticket Number."
echo " example: 'JIRA-1234: my commit'"
echo ""
exit 1
fi
afterward, you should be able to see the error upon every attempt to commit a message without a JIRA ticket.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With