DEV Community

Cover image for Automatically Adding a Jira Ticket ID to a Github Commit
John Pereira
John Pereira

Posted on

Automatically Adding a Jira Ticket ID to a Github Commit

We use Jira at work to track tasks. So, anytime you make changes to code,
the commit message usually includes the ticket ID in the message.

It goes something like this:

[ISSUE-123] I understand that it's an antipattern, but it's convenient.
Enter fullscreen mode Exit fullscreen mode

This is useful when you're looking at a busy repository and going through
the history to find a specific commit.

Of course, you can add this manually every time you commit. Or you can add
this tiny script as a Github pre-commit hook so that it's automatically
added.

#!/bin/bash

# This way you can customize which branches should be skipped when
# prepending commit message.
if [ -z "$BRANCHES_TO_SKIP" ]; then
  BRANCHES_TO_SKIP=(master)
fi

BRANCH_NAME=$(git symbolic-ref --short HEAD)

ISSUE_NUMBER=$(printf "${BRANCH_NAME}" | sed -n
's/.*\(ISSUE-[0-9]*\).*$/\1/p')
ISSUE_NUMBER="${ISSUE_NUMBER##*/}" # Strip out everything except ID

BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -c
"^$BRANCH_NAME$")
ISSUE_NUMBER_IN_COMMIT=$(grep -c "\[$ISSUE_NUMBER\]" $1)

if [ -n "$BRANCH_NAME" ] && ! [[ $BRANCH_EXCLUDED -eq 1 ]] && ! [[
$ISSUE_NUMBER_IN_COMMIT -ge 1 ]]; then
  sed -i.bak -e "1s/^/[$ISSUE_NUMBER] /" $1
fi
Enter fullscreen mode Exit fullscreen mode

To use this script:

  1. Navigate to your <repository>/.git/hooks/
  2. Create a file named prepare-commit-msg and put the script inside it
  3. Make it executable by running chmod +x prepare-commit-msg

Now, you might have noticed that the regex specifically looks for the word
ISSUE in the branch name. That's because it's the project code that we
work with. You can simply adjust it to match the naming scheme of your
project.

I'm not any good at scripting so I just cobbled this together using chatGPT. There are plenty of options that will let you automate this. Find one that fits your workflow and go nuts!

Top comments (0)