Reputation: 639
I'm following this posts about git hooks and in one example there is a regular expresion to check the commit message.
The message should be match [XXX-123] My message
or [hotfix] My message
REGEX="^\[(hotfix|\w+\-[0-9]+)\]( \w+)+$"
But running the examples "[hotfix] Fixing unit-tests"
and "[PSBO-456] It's a valid one this time"
I get an error response from the bash script.
This is the script
#!/usr/bin/env bash
echo "Checking commit-message format..."
## the first arg is the path to the git commit temporary file
TEMPORARY_FILE_PATH=$1
## get commit-message from the temporary file
COMMIT_MSG=`head -n1 $TEMPORARY_FILE_PATH`
## init regex to match commit-message format
REGEX="^\[(hotfix|\w+\-[0-9]+)\]( \w+)+$"
## checking commit-message format
if ! [[ $COMMIT_MSG =~ $REGEX ]];then
echo -e "Your commit-message format is not valid:\n$COMMIT_MSG\n"
echo "Valid format examples:"
echo "[PSBO-123] My commit message"
echo "[hotfix] My commit message"
exit 1
else
echo "Well done! Your commit-message is valid."
exit 0
fi
Upvotes: 2
Views: 1883
Reputation: 627545
You forgot to support the '
and -
chars in your input string. Also, \w
is non-standard in this environment, you should be relying on POSIX character classes rathert than Perl-like shorthand character classes. E.g. \w
is [[:alnum:]_]
, \d
is [[:digit:]]
, \s
is [[:space:]]
.
I'd advise:
REGEX='^\[(hotfix|[[:alnum:]_]+-[0-9]+)]([[:blank:]]+[[:alnum:]_'"'"'-]+)+$'
See the regex demo (just to show how it is working, do not use regex101 to test POSIX ERE patterns validity).
Details
^
- start of string\[
- a [
char(hotfix|[[:alnum:]_]+-[0-9]+)
]
- a ]
char([[:blank:]]+[[:alnum:]_'-]+)+
- one or more occurrences of
[[:blank:]]+
- one or more horizontal whitespaces[[:alnum:]_'-]+
- one or more alphanumeric, _
, '
or -
chars$
- end of string.Upvotes: 4