I assume you understand Git well enough to use it to version control your projects.

If you've worked in a team and happened to do code reviews regularly, you may surely have felt the pain of writing comments on PR commits without referencing to a Jira ticket. I have initially thought of using build task in CI to enforce the code quality but found out there is very powerful but not so well known feature called Git hooks. In a very simplest term to explain hooks, is a plugin system for Git.

Git provides a native mechanism, hooks to trigger custom scripts that can be used to enforce policy on repositories.

There are two different types of hooks, 1) Client-side hooks and 2) Server-side hooks which trigger for certain native events like pre-commit, post-update, pre-receive etc.

Client-side hooks

Client-side hook scripts are stored and executed on committers local machine. They reside in .git/hooks folder/directory.

Server-side hook scripts are executed on the server that receives the pushes. They store on server in .git/hooks folder/directory.

Below is pre-receive hook script to check for JIRA issue number and merge keyword.

Pre-Receive Server-side hook

#!/usr/bin/env bash

commit_format="(JIRA|PROJECTKEY|MULE|ECOM|SAP|XLR-[1-9]+Merge)"
zero_commit="0000000000000000000000000000000000000000"

# Do not traverse over commits that are already in the repository 
# (e.g. in a different branch) 
# This prevents funny errors if pre-receive hooks got enabled after some 
# commits got already in and then somebody tries to create a new branch 
# If this is unwanted behavior, just set the variable to empty 
excludeExisting="--not --all" 
error_msg="Aborting commit. Your commit message is missing a JIRA Issue ('For example, SAP-111, MULE-111') "

while read oldrev newrev refname; do 
  # branch or tag get deleted 
  if [ "$newrev" = "$zero_commit" ]; then 
    continue 
  fi 
  # Check for new branch or tag 
  if [ "$oldrev" = "$zero_commit" ]; then 
    span=`git rev-list $newrev $excludeExisting` 
  else 
    span=`git rev-list $oldrev..$newrev $excludeExisting` 
  fi 
  for COMMIT in $span; 
   do
        COMMIT_MESSAGE=`git log --format=%B -n 1 ${COMMIT}`
        if ! [[ $COMMIT_MESSAGE =~ $commit_format ]]; then
        echo "$error_msg" >&2
        exit 1
    fi;
    done 
done 
exit 0