Place the following in .git/hooks/prepare-commit-msg
and mark it as executable (chmod +x .git/hooks/prepare-commit-msg
).
#!/bin/bash
is_amend=$(ps -ocommand= -p $PPID | grep -e '--amend')
if [ -n "$is_amend" ]; then
exit 0
fi
file=$1
message=$(cat $file)
branch=$(git rev-parse --abbrev-ref HEAD)
ticket=$(echo $branch | grep -Eo '^(\w+/)?(\w+[-_])?[0-9]+' | grep -Eo '(\w+[-])?[0-9]+' | tr "[:lower:]" "[:upper:]")
ticket_na="TICKET-NA"
lower_ticket_na="$(echo $ticket_na | tr '[:upper:]' '[:lower:]')"
lower_branch="$(echo $branch | tr '[:upper:]' '[:lower:]')"
# ${var,,} converts $var to lowercase
if [[ $ticket == "" && "$lower_branch" =~ "$lower_ticket_na" ]]; then
ticket="$ticket_na"
fi
if [[ $ticket == "" || "$message" == "$ticket"* ]]; then
exit 0
fi
echo "$ticket $message" > $file
https://betterprogramming.pub/how-to-automatically-add-the-ticket-number-in-git-commit-message-bda5426ded05