Skip to content

Instantly share code, notes, and snippets.

@mcascone
Created October 28, 2022 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mcascone/504a9c1560967efb35db668a23d1cb8c to your computer and use it in GitHub Desktop.
Save mcascone/504a9c1560967efb35db668a23d1cb8c to your computer and use it in GitHub Desktop.
Two Jira ID commit hooks

2 git-jira hook integration scripts

This gist contains two different implementations of automatically appending the Jira ID to the git commit message.

I don't know if one way is better than the other. Choose one and create a file in your repo. It must be named exactly: prepare-commit-msg (no extension) and placed in the <repo-name>/.git/hooks dir.

Very detailed discussion here: https://stackoverflow.com/questions/427207/can-git-hook-scripts-be-managed-along-with-the-repository

Also! Very important!

Make sure you save the file as UTF-8 (ASCII). Some editors (VSCode included) will guess at the encoding and save it as UTF-16. This makes the file not runnable.

#!/bin/sh
# This one has been working perfectly for @mcascone
# I don't know if one is better than the other.
# Automatically adds Jira key to commit message.
if [ -z "$BRANCHES_TO_SKIP" ]; then
BRANCHES_TO_SKIP=(master develop)
fi
BRANCH_NAME=$(git symbolic-ref --short HEAD)
BRANCH_NAME="${BRANCH_NAME##*/}"
BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -c "^$BRANCH_NAME$")
BRANCH_JIRA_KEY=$(echo $BRANCH_NAME | grep -E -o '^([A-Z]+-[0-9]+)')
if ! [[ $BRANCH_EXCLUDED -eq 1 ]] && ! [[ $(cat "$1") == "$BRANCH_JIRA_KEY"* ]] && ! [ -z "$BRANCH_JIRA_KEY" ]; then
echo "$BRANCH_JIRA_KEY $(cat "${1}")" > "$1"
fi
#!/bin/sh
COMMIT_FILE=$1
COMMIT_MSG=$(cat $1)
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
JIRA_ID=$(echo "$CURRENT_BRANCH" | grep -Eo "[A-Z0-9]{1,10}-?[A-Z0-9]+")
if [ ! -z "$JIRA_ID" ]; then
echo "$JIRA_ID $COMMIT_MSG" > $COMMIT_FILE
echo "JIRA ID '$JIRA_ID', matched in current branch name, prepended to commit message. (Use --no-verify to skip)"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment