我正在尝试commit-msg
为我的git
项目编写一个钩子,用于检查提交消息是否符合特定的样式指南。然而,关于正则表达式,似乎有些东西的工作方式有所不同bash
。我怎样才能实现我的目标?
#!/usr/bin/env bash
read -r -d '' pattern << EOM
(?x) # Enable comments and whitespace insensitivity.
^ # Starting from the very beginning of the message
(feat|fix|docs|style|refactor|test|chore) # should be a type which might be one of the listed,
:[ ] # the type should be followed by a colon and whitespace,
(.{1,50})\n # then goes a subject that is allowed to be 50 chars long at most,
(?:\n((?:.{0,80}\n)+))? # then after an empty line goes optional body each line of which
# may not exceed 80 characters length.
$ # The body is considered everything until the end of the message.
EOM
message=$(cat "${1}")
if [[ ${message} =~ ${pattern} ]]; then
exit 0
else
error=$(tput setaf 1)
normal=$(tput sgr0)
echo "${error}The commit message does not accord with the style guide that is used on the project.${normal}"
echo "For more details see https://udacity.github.io/git-styleguide/"
exit 1
fi
我还尝试在 oneline 中编写此正则表达式,如下所示:
pattern="^(feat|fix|docs|style|refactor|test|chore):[ ](.{1,50})\n(?:\n((?:.{0,80}\n)+))?$"
甚至尝试替换\n
为$'\n'
但没有帮助。
答案1
Bash 支持 POSIX 扩展正则表达式 (ERE),而不支持 Perl 兼容正则表达式 (PCRE)。特别地,(?x)
和(?:...)
是PCRE。
(?:...)
快速浏览一下,如果您只是替换为 ,单行版本应该可以工作(...)
。 Perlx
修饰符提供的“忽略空格”功能在扩展正则表达式中不可用。