Skip to content

Instantly share code, notes, and snippets.

@jmcazaux
Last active August 27, 2021 10:09
Show Gist options
  • Save jmcazaux/944cf12843b9358e0ffecf250f15c6f1 to your computer and use it in GitHub Desktop.
Save jmcazaux/944cf12843b9358e0ffecf250f15c6f1 to your computer and use it in GitHub Desktop.
Git commit-msg hook to append issue number to commit message
#!/bin/bash
# This hook both checks that the name of the branch matches a given convention
# and extracts the issue number from the branch name to add it to the commit message.
# If it is a multiline commit message the reference to the issue is added as a new line.
# In the case of a single line commit message, the reference is added at the end of the message.
BRANCH_NAME_REGEX="^(ci|docs|feature|fix|hotfix|perf|refactor|test)\/.*$"
ISSUE_NUMBER_REGEX="^.*\#([0-9]+)"
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)
echo $BRANCH_NAME
if ! [[ $BRANCH_NAME =~ $BRANCH_NAME_REGEX ]]; then
echo "*** Commit interupted ***"
echo "Your branch name does not match the naming convention."
echo "Branch names should follow \"$BRANCH_NAME_REGEX\"..."
exit 1
fi
if [[ $BRANCH_NAME =~ $ISSUE_NUMBER_REGEX ]]; then
ISSUE_NUMBER="#${BASH_REMATCH[1]}"
FILE=$1
if ! grep -q $ISSUE_NUMBER $FILE; then
if [[ $(wc -l < $FILE) -gt 1 ]]; then
# Multiline message, we add at the end of the file
echo "Refs $ISSUE_NUMBER" >> $FILE
else
# Single line message, we add at the end of the message
echo $(sed -e "s/$/ (refs $ISSUE_NUMBER)/" $FILE) > $FILE
fi
echo "Reference to issue \"$ISSUE_NUMBER\" was added to your commit message..."
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment