Automatic linking of git branch to jira issue with git-hook help

 To make the agile process in a team more organized and transparent - we could configure mandatory binding of version control system (git in our case) with a bug-tracking system (Jira in our case). And definitely, it is cool when it happens automatically! Let's do it👌

The main idea is - if in commit comment (description) presents jira issue key, then in the jira issue description occurs a link on this git branch.


Part I  Configure Jira to support git

This could be done in the Jira admin panel (if you have no access, contact your Jira administrator). The process should be like it's described in this article https://confluence.atlassian.com/bitbucket/connect-bitbucket-and-jira-813891605.html

Part II Configure git-hook

The main goal of this article was to show how to configure git-hook and with the use of bash commands to configure validation rules. So how git-hook operates: in your local directory 'C:\git\repo-name\.git\hooks' create file pre-commit (by default pre-commit.sample already exists there) with script inside:

#!/bin/sh
#
# Pre-commit hook for adding Jira number to commit comment
#
BRANCH_NAME=$(git symbolic-ref --short HEAD)
JIRA=$( echo $BRANCH_NAME | grep -hE "[[:alpha:]][A-Z]+-[0-9]+" | tr '/' '\n' | grep -hE "[A-Z]+-[0-9]+" | sort | uniq | head -n1 )
JIRA_LAST=$( echo $BRANCH_NAME | grep -hE "[[:alpha:]][A-Z]+-[0-9]+" | tr '/' '\n' | grep -hE "[A-Z]+-[0-9]+" | sort | uniq | tail -n1 )
if [[ "$JIRA" == "" ]]; then
echo "Branch name should contain JIRA issue ref, for ex: KEY-123456 "
exit 1
fi
if [[ "$JIRA" != "$JIRA_LAST" ]]; then
echo "Branch name should contain one and only JIRA issue ref, but found many: "
echo "$( echo $BRANCH_NAME | grep -E "[A-Z]+-[0-9]+" | uniq)"
exit 1
fi
exit 0;

After this, if we create a branch without jira key in name, when doing the commit, we'll get an error:

and no committing will happen.

But to make a branch to be linked with Jira ticket, the commit comment must contain Jira key at the beginning, so for this we need to configure one more file. We have to add file prepare-commit-msg (by default prepare-commit-msg.sample already exists there) with the script:

#!/bin/sh
BRANCH_NAME=$(git symbolic-ref --short HEAD)
JIRA=$( echo $BRANCH_NAME | grep -hE "[[:alpha:]][A-Z]+-[0-9]+" | tr '/' '\n' | grep -hE "[A-Z]+-[0-9]+" | head -n1 )
JIRA_S=$( echo $JIRA | sed -r "s/^[A-Z]+-[0-9]+$/& /" )
sed -r -i "s/$JIRA//" $1
sed -i "1s;^;$JIRA_S;" $1

And that's it. Now if you create a new branch with Jira ticket in name, by added rule, then commit will be done successfully: 

And at the beginning of the commit description will be added Jira key KEY-123.

Advantages: transparent process control - each commit linked to it's task, and from task you could see source code; quick search of code and task.

Difficulties: each and every branch should be linked with jira ticket.