Automatic issue tags in Git commit messages

If you’re working on a project, chances are you’re also using some kind of issue tracker (like Jira or Trac). Most modern issue trackers allow integration with version control systems such as Git, so that it’s possible to view any commits attached to a certain issue. This works by the issue tracker parsing the commit message and looking for certain patterns corresponding to issues.

Jira for example identifies it’s issues through the pattern “FOO-n”, where “n” is a number and “FOO” is a project specific tag. For example “FOO-432”.

It quite quickly becomes tiresome to always have to enter the name of the current issue into the commit message. Git however has some really excellent “hooks”. These are a couple of optional files (found in .git/hooks) which, if present, are run at various times in the Git workflow. They provide a powerful mechanism through which one can automate some of the more tedious tasks.

The following is such a script, which when installed into “.git/hooks/prepare-commit-msg” will be run each time you commit something (make sure you also make it executable!). It will first look at the current branch name, and see if it contains a valid issue tag. If so, this issue tag will be inserted into the commit message (at a line of your choosing).

This allow you to create branches such as “FOO-434_fix_nasty_bug” or “fix_nasty_bug_FOO-434” and then have Git automatically insert “FOO-434” into your commit messages. Just copy and paste it into a .git/hooks/prepare-commit-msg file, make the file executable and alter the ISSUE_PREFIX value to fit your project.

Nifty!

 

Update 2016-02-25: added check for amend commits

This Post Has 2 Comments

  1. Hi Erik,

    Thanks. I have done this for many years, but somehow have never bothered writing a git hook for it. Along came you :)
    I do, however, work on several different jira projects at one time, so I have modified your script a tiny bit:
    I have changed the line starting with ISSUE_NAME to read:

    ISSUE_NAME=echo $BRANCH_NAME | egrep -o "[A-Z]+-[0-9]+"

    Note that this heuristic will break if you are in the habit of naming your branch things like
    “MY-FINE-1-BRANCH-referring-jira-issue-PT-150”

  2. On a windows machine, the “grep -o” won’t work.

    If you instead replace the grep with this:

    ISSUE_NAME=echo $BRANCH_NAME | grep "${ISSUE_PREFIX}[0-9]*"
    ISSUE_NAME_CUT=echo $ISSUE_NAME | cut -d"_" -f 1

    And of course use the $ISSUE_NAME_CUT variable instead.

    I adds the constraint that you have to name your branches BG-1234_more_text. Which means less freedom, but at least it will work.

    For some reason the issue number isn’t prefixed, but added as a new line above the commit message. I don’t know if this is related to the Windows implementation of sed.

Leave a Reply

Close Menu