Git Commit Message Hook for JIRA Issue Keys

Programming994

Overview

Credits to this StackOverflow answer: https://stackoverflow.com/a/53669975/1800854

Follow these steps to set up a global commit message hook that will extract the issue key from your branch id and prepend it to your commit messages automatically. This allows other team members to easily track down who wrote what code.

Steps

  1. Make sure you have a variant of grep installed that supports PCRE
    1. On Mac you can do this using: brew install ggrep
  2.  Create folder somewhere on disk for global git hooks
    mkdir -p ~/git/hooks
  3. Make a file here called commit-msg with the following content. File is also available here.
    NOTE: Replace grep with ggrep if needed (for Mac)
    #!/bin/bash
    # The script below adds the branch name automatically to
    # every one of your commit messages. The regular expression
    # below searches for JIRA issue key's. The issue key will
    # be extracted out of your branch name
    # 
    # A variant of grep support the -P flag for PCRE is required
    #
    REGEX_ISSUE_ID="((?!([A-Z0-9a-z]{1,10})-?$)[A-Z]{1}[A-Z0-9]+-\d+)"
    
    # Find current branch name
    BRANCH_NAME=$(git symbolic-ref --short HEAD)
    
    if [[ -z "$BRANCH_NAME" ]]; then
        echo "No branch name... "; exit 1
    fi
    
    # Extract issue id from branch name
    ISSUE_ID=$(echo "$BRANCH_NAME" | LC_ALL=en_US.utf8 grep -o -P "$REGEX_ISSUE_ID")
    
    # Prepend issue id if it was found
    if [[ -z "$ISSUE_ID" ]]; then
        echo $(cat "$1") > "$1"
    else
        echo "$ISSUE_ID"': '$(cat "$1") > "$1"
    fi
  4. Make this file executable
    chmod +x commit-msg
  5. Configure git to globally use this folder as the global hook folder
    git config --global core.hooksPath ~/git/hooks

Example

Jira Issue Git Commit Prehook Example

Notes

The regexp used will match:

  • ✔️ TASK-100
  • ✔️ JAVA-1-is-the-best
  • ✔️ ROBOT-777-LETS-get-it-done-2
  • ✔️ issues/EASY-42-its-too-easy-baby

Works but be careful with:

  • ⚠️ DEJAVU-1-DEJAVU-2-maybe-dont-do-this

Will not match:

  • test-500-lowercase-wont-work
  • TEST100-nope-not-like-this

Warning: Global hooks will override local repository hooks if the projects you are using utilises them.


Leave a comment

(required)(will not be published)(required)

Comments

Showing 4 comments from 3 commenters.

  • Display picture for Tyler G
    Tyler G

    The list under "Will not match:" is the same as the list under ~"Will match:"

    Copy/paste error?

    Reply
    • Display picture for Mo Beigi
      Mo Beigi

      Hi Tyler, yeah it was a copy and paste error. Fixed now. Thank you!

      Reply
  • Display picture for Andy
    Andy

    what if the branch is not named with Jira key and we want to check the message for the key and enforce that?

    Reply
    • Display picture for Mo Beigi
      Mo Beigi

      Right now this hook is based on the branch name being set correctly first.

      Reply