Skip to content

Instantly share code, notes, and snippets.

@mpawelski
Last active August 29, 2018 20:27
Show Gist options
  • Save mpawelski/4dfb6d68b803b60e86599ffbb36d8558 to your computer and use it in GitHub Desktop.
Save mpawelski/4dfb6d68b803b60e86599ffbb36d8558 to your computer and use it in GitHub Desktop.
Git hook to append Jira issue number to commit message basing on branch name
#! /bin/bash
# This hook checks if git commit message (first line) contains Jira
# ticket (for example TEST-123) and if not prepends it to commit message
# based on current branch name (for example from bugfix/TEST-123-quickfix
# branch name we'll prepend "TEST-123:" to git commit message)
# This script is 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.
# source: https://gist.github.com/mpawelski/4dfb6d68b803b60e86599ffbb36d8558
# heavily based on: https://gist.github.com/chonton/d7a48828642ea763b8b84141ead40e64/
# Get the name of the current branch.
branchName=$(git symbolic-ref HEAD --short)
branchRegex="(^|[^A-Z])([A-Z]{3,6}-[0-9]{1,5})([^0-9]|$)"
if [[ $branchName =~ $branchRegex ]]; then
# Grab the jira ticket from the branch name
jiraTicket="${BASH_REMATCH[2]}"
jiraRegex="(^|[^A-Z])${jiraTicket}([^0-9]|$)"
firstLineOfCommitMessage=$(head -n 1 $1)
if [[ $firstLineOfCommitMessage =~ ^fixup!* ]]; then
# Special case for commit starting witch 'fixup!...'.
# This commit is probably from "git commit --fixup=<commit>" command
# and you probably want to squash it later with "git rebase -i --autosquash"
# We do nothing. ':' is null bash command (required if you want "empty" then clasue)
:
else
# If the message already contains jiraTicket, do not change the commit message.
if [[ $firstLineOfCommitMessage =~ $jiraRegex ]]; then
:
else
# prepend the jira ticket
echo "$jiraTicket: $(cat $1)" > $1
fi
fi
else
:
# I allow having branches without jira issue in name. Just for experimenting.
# But if you want to be stricter then you can uncomment
# below code to prevent commiting and show message why:
#echo "Branch name does not correspond to JIRA ticket. Try one of the following"
#echo "git checkout -b JIRA-number"
#echo "git branch -m JIRA-number"
#exit 254
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment