Skip to content

Instantly share code, notes, and snippets.

@stansidel
Last active July 28, 2023 09:51
Show Gist options
  • Save stansidel/d3465e3c34f5817c687e5941b84ef507 to your computer and use it in GitHub Desktop.
Save stansidel/d3465e3c34f5817c687e5941b84ef507 to your computer and use it in GitHub Desktop.
Add ticket number from the branch to commit messages
#!/bin/sh
#
# Automatically adds branch name and branch description to every commit message.
# Skips this step if the commit message already starts with "[".
# Modified from the stackoverflow answer here: http://stackoverflow.com/a/11524807/151445
#
# Succeed on all merge messages, as evidenced by MERGE_MSG existing
[ -f $GIT_DIR/MERGE_MSG ] && exit 0
# Get branch name and description
NAME=$(git branch | grep '*' | sed 's/* //')
DESCRIPTION=$(git config branch."$NAME".description)
ticket="$(git rev-parse --abbrev-ref HEAD)"
[[ $ticket =~ (([[:alnum:]]{3,})-([[:digit:]]{3,})).* ]] && ticketID=${BASH_REMATCH[1]}
if [ -n "$ticketID" ]
then
# Debug:
# printf "%s\n" "$ticketID: "
# Don't apply this logic if we are in a 'detached head' state (rebasing, read-only history, etc)
# newlines below may need echo -e "\n\n: (etc.)"
if [ "$NAME" != "(no branch)" ] && [[ "$(cat $1)" != [* ]]; then
# Append branch name and optional description to COMMIT_MSG
# For info on parameters to githooks, run: man githooks
echo "[$ticketID] $(cat $1)" > "$1"
fi
fi
@stansidel
Copy link
Author

How to add the hook to your repos is described in this article.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment