Skip to content

Instantly share code, notes, and snippets.

@StephaneTrebel
Last active October 21, 2022 06:01
Show Gist options
  • Save StephaneTrebel/cea01e261b6e21a22b138b642a435e59 to your computer and use it in GitHub Desktop.
Save StephaneTrebel/cea01e261b6e21a22b138b642a435e59 to your computer and use it in GitHub Desktop.
git commitmsg hook: Idempotently add ticket number in the footer part of a commit message
#!/bin/bash
#
# DESCRIPTION:
# Add the ticket identifier found in the branch name in the footer part of
# the commit message. This action is idempotent (meaning if the ticket is already
# in the message, it will not be added again).
# Please note that this apply to «git commit» and its variations
# (most notably «--amend»). Il will not apply to «reword» actions during an
# interactive rebase, for instance.
#
# REQUIREMENTS:
# - The branch is presumed to follow a gitflow style («type/ticket-id-and-other-things»)
# - The ticket identifier is presumed to be of the form: uppercase letters
# followed by a dash, and then a number (e.g ABC-1234, F-9, JIRA-3823787483)
#
# HOW TO USE:
# - Copy this file in any .git/hooks directory you want it to be applied
# - Commit away !
#
# EXAMPLES:
# Here are some branch samples and the computed ticket identifier that will be added
# in the commit message footer:
# « foo/bar-1 » -> bar-1
# « feature/ABC-1234-rest-of-the-branch-name » -> ABC-1234
# « bugfix/XYZ-456 » -> XYZ-456
# « ABC-1234 » -> <nothing added>
# « my-awesome-branch » -> <nothing added>
TICKET=$(git symbolic-ref HEAD | rev | cut -d/ -f1 | rev | grep -o -E "[A-Z]+-[0-9]+")
if [[ -n "${TICKET}" ]]; then
grep -qe "^${TICKET}$" ${1}
SHOULD_ADD_TICKET=$?
if [[ ${SHOULD_ADD_TICKET} != 0 ]]; then
echo -e "\n${TICKET}" >> ${1}
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment