简体   繁体   中英

Git hook commit-msg to ensure the commit message contains a string that conforms to a regex

I'm trying to make bash script to be used as a git commit-msg hook. Essentially I want to ensure that the commit message contains a string which matches the regex. My regex is correct, but i'm not sure how to check if the message contained in .git/COMMIT_EDITMSG matches the regex.

#!/bin/sh
#
# This hook verifies that the commit message contains a reference to a tfs item

RED=$(tput setaf 1)
NORMAL=$(tput sgr0)
# Regex to validate a string contains "#" followed by 4 or 5 digits anywhere in the commit message
regex="#[0-9]{4,5}($|[^0-9])"

# I NEED TO FIGURE OUT HOW TO READ THE CONTENTS OF THIS FILE AND ENSURE IT MATCHES THE REGEX
echo "MSG = $1" # This prints "MSG = .git/COMMIT_EDITMSG"

# If the commit message does not match the regex
if ! [[ $1 =~ $regex ]]; then
  echo "${RED}ERROR - Missing tfs item in commmit message.$NORMAL"
  exit 1
else
  echo "MESSAGE IS GOOD?"
fi

exit 0

I figured it out with this:

#!/bin/sh
#
# This hook verifies that the commit message contains a reference to a tfs item

RED=$(tput setaf 1)
NORMAL=$(tput sgr0)
# Regex to validate a string contains "#" followed by 4 or 5 digits anywhere in the commit message
regex="#[0-9]{4,5}($|[^0-9])"
file=`cat $1` # The file that contains the commit message

# If the commit message does not match the regex
if ! [[ $file =~ $regex ]]; then
  echo "${RED}ERROR - Missing tfs item in commmit message.$NORMAL"
  exit 1
else
  echo "MESSAGE IS GOOD?"
fi

exit 0

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