简体   繁体   中英

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

My branch name pattern is as following ticketId_ticketDescription eg 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM