Use branch name to automatically add Jira issue ID to the commit message.
Use the following shell script as commit-msg
hook (.git/hooks/commit-msg
executable file).
#!/usr/bin/env bash # Automatically add JIRA issue ID to the git commit message # Supported project keys PROJECT_KEYS=(JIRA SMART BLOG) # Commit message separator between issue number and commit message COMMIT_MESSAGE_SEPARATOR=": " # Get current branch BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null) if [ "$?" -gt "0" ]; then exit 0 fi # Get file with current commit message COMMIT_MESSAGE_FILE=$1 if [ "$#" -ne "1" ] || [ ! -f "$COMMIT_MESSAGE_FILE" ]; then exit 1 fi # Iterate over project key until it is found, break the loop afterwards for PROJECT in "${PROJECT_KEYS[@]}"; do # Check if commit message contains project key # for example: # "feature/SMART-1344" -> does SMART-1344 contains project key? echo $BRANCH | awk -F/ '{print $NF}' | grep --silent --ignore-case $PROJECT if [ "$?" -eq "0" ]; then # Extract issue id from branch name ISSUE="$(echo $BRANCH | awk -F/ '{print toupper($NF)}')" head -1 $COMMIT_MESSAGE_FILE | grep --silent --ignore-case ^${ISSUE} # Does it start with a task number corresponding to the branch name? (case insensitive) if [ "$?" -eq "0" ]; then # Yes, but is it uppercase? head -1 $COMMIT_MESSAGE_FILE | grep --silent ^${ISSUE} if [ "$?" -ne "0" ]; then sed -i "1s/^[a-Z]*/\U&\E/" $COMMIT_MESSAGE_FILE fi else # No, so insert issue id sed -i "1s/^/${ISSUE}${COMMIT_MESSAGE_SEPARATOR}/" $COMMIT_MESSAGE_FILE fi break fi done
Create the initial commit – do not add an issue id.
$ git commit -m "first commit" --allow-empty [master (root-commit) 6d28860] first commit
Create the second commit on a supported branch – add an issue id.
$ git checkout -b "SMART-5000" Switched to a new branch 'SMART-5000'
$ git commit -m "second commit" --allow-empty [SMART-5000 4ace356] SMART-5000: second commit
Create the third commit on a supported branch – do not add an issue id as it is already present.
$ git commit -m "SMART-5000: third commit" --allow-empty [SMART-5000 739784f] SMART-5000: third commit
Create the fourth commit on a supported branch – do not add an issue id as it is already present, but convert the project key to uppercase.
$ git commit -m "Smart-5000: fourth commit" --allow-empty [SMART-5000 482026b] SMART-5000: fourth commit
The main reason I wrote this blog post is that I am continually writing SMAR<strong>t</strong>-5000
and it annoys me.