简体   繁体   English

git commit-msg 钩子的正则表达式

[英]Regex for git commit-msg hook

I am trying to achieve following structure for git commit msg:我正在尝试为 git commit msg 实现以下结构:

X=Uppercase character
Y=Number 0-9
category=fix, chore, doc, etc...

XXXXY-YYY [category] XXXXX*

this is my commit-msg file这是我的 commit-msg 文件

MSG_FILE=$1
FILE_CONTENT="$(cat $MSG_FILE)"
# Initialize constants here
export REGEX="\D\D\D\D\d-\d\d\d \[(fix|poc|chore|feat|refactor|style|test)\] .*"
export ERROR_MSG="Commit message format must match regex \"${REGEX}\""
if [[ $FILE_CONTENT =~ $REGEX ]]; then
 echo "Nice commit!"
else
  echo "Bad commit \"$FILE_CONTENT\", check format."
 echo $ERROR_MSG
 exit 1
fi
exit 0

But all I get is:但我得到的只是:

    $ git commit -m "PBCL2-666 [fix] whatever"
Bad commit "PBCL2-666 [fix] whatever", check format.
Commit message format must match regex "\D\D\D\D\d-\d\d\d \[(fix|poc|chore|feat|refactor|style|test)\] .*"

Any ideas?有任何想法吗?

You are using the regex in Bash and thus using the POSIX ERE regex engine.您在 Bash 中使用正则表达式,因此使用 POSIX ERE 正则表达式引擎。

POSIX ERE does not recognize the \\D construct matching any non-digit char. POSIX ERE 无法识别匹配任何非数字字符的\\D构造。 Use [0-9] to match a digit (or [[:digit:]] ) and [^0-9] (or [^[:digit:]] ) to match a non-digit.使用[0-9]匹配数字(或[[:digit:]] )和[^0-9] (或[^[:digit:]] )匹配非数字。

However, you need [[:upper:]] to match any uppercase letter.但是,您需要[[:upper:]]来匹配任何大写字母。

FILE_CONTENT="PBCL2-666 [fix] whatever"
# ....
ERROR_MSG="Commit message format must match regex \"${REGEX}\""
REGEX="^[[:upper:]]{4}[0-9]-[0-9]{3} \[(fix|poc|chore|feat|refactor|style|test)] .*"
if [[ $FILE_CONTENT =~ $REGEX ]]; then
 echo "Nice commit!"
else
  echo "Bad commit \"$FILE_CONTENT\", check format."
 echo $ERROR_MSG
 exit 1
fi

See the online Bash demo .请参阅在线 Bash 演示

Note I added ^ at the start to make sure matching starts from the beginning of string only.注意我在开头添加了^以确保匹配仅从字符串的开头开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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