Dahab
Dahab

Reputation: 514

Git commit-msg hook: prefix commit based on part of branch name

My branch name pattern is as following ticketId_ticketDescription e.g MIT-1018-make-goto-redirection-smarter

so i want each commit to be prefixed by ticketId in this case it is [MIT-1018]

So if i commit

git commit -am"This is a commit message" so message should be "MIT-1018: This is a commit message"

This is my try

#!/bin/bash
ticket=`git rev-parse --abbrev-ref HEAD | sed -e 's/MIT-[0-9]+//'`
echo $ticket
comment=`cat $1`
search=`grep "$ticket" $1`
if [ -n "$ticket" ] && [ -z "$search" ]
then
echo "$ticket: $comment" > $1
fi

but this add the whole branch name as a prefix not the TicketId only

Upvotes: 0

Views: 650

Answers (1)

Inian
Inian

Reputation: 85683

You can use regex in bash with character classes, [[:alnum:]] and [[:digit:]] to extract the ticket identifier as you need.

$ ticket="$(git rev-parse --abbrev-ref HEAD)"
$ commitMessage="This is a commit message"

# Assuming the variable has the string "MIT-1018-make-goto-redirection-smarter"
# ticket="MIT-1018-make-goto-redirection-smarter"

$ [[ $ticket =~ (([[:alnum:]]{3})-([[:digit:]]{3,})).* ]] && ticketID=${BASH_REMATCH[1]}
$ printf "%s\n" "$ticketID: $commitMessage"
MIT-1018: This is a commit message

Upvotes: 1

Related Questions