Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git hooks to enforce JIRA ticket number in commit message

Tags:

git

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
like image 330
sarit Avatar asked Nov 08 '22 01:11

sarit


1 Answers

I was able to get this to work locally by:

  1. cd into <project directory>/.git/hooks/
  2. removing the extension .sample from the commit-msg.sample
  3. open the commit-msg file in a text editor
  4. copy & paste the following code into that file.
#!/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.

like image 61
derpdewp Avatar answered Nov 15 '22 04:11

derpdewp