Skip to content

Instantly share code, notes, and snippets.

@petitJAM
Last active August 3, 2023 17:43
Show Gist options
  • Save petitJAM/313991abf4bbcadec09fdfc3b4d43217 to your computer and use it in GitHub Desktop.
Save petitJAM/313991abf4bbcadec09fdfc3b4d43217 to your computer and use it in GitHub Desktop.
Git hook for preparing commit message with ticket ID from branch name

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment