这是为想要找到以前解决方案的替代品的人的更新。
现在有很多资源可以使用 git pre-commit hook 检查内容。
最“有名”的大概是https://pre-commit.com/
Git 钩子有时难以维护和共享(即使 git 2.9 引入了core.hooksPath
使其更容易的配置)。
我主要使用 JavaScript,我发现了一个名为Husky的流行模块,它通过项目管理可共享的钩子。我喜欢它,因为它通过我的package.json
.
我还试图找到一个补充模块来在提交之前检查我的内容,但我发现没有什么令人满意的。我想要类似于这样的共享配置(in package.json
)的东西:
"precommit-checks": [
{
"filter": "\\.js$",
"nonBlocking": "true",
"message": "You’ve got leftover `console.log`",
"regex": "console\\.log"
},
{
"message": "You’ve got leftover conflict markers",
"regex": "/^[<>|=]{4,}/m"
},
{
"message": "You have unfinished devs",
"nonBlocking": "true",
"regex": "(?:FIXME|TODO)"
}
]
我终于做了自己的:git-precommit-checks。如果你愿意,你可以尝试一下,否则你仍然可以寻找替代品(尤其是如果你不使用 JS)。
如果您仍想使用 bash 脚本检查您的内容,您可以尝试更通用的方法并循环遍历应该停止提交的搜索模式数组。
#! /bin/bash
# If you encounter any error like `declare: -A: invalid option`
# then you'll have to upgrade bash version to v4.
# For Mac OS, see http://clubmate.fi/upgrade-to-bash-4-in-mac-os-x/
# Hash using its key as a search Regex, and its value as associated error message
declare -A PATTERNS;
PATTERNS['^[<>|=]{4,}']="You've got leftover conflict markers";
PATTERNS['focus:\s*true']="You've got a focused spec";
# Declare empty errors array
declare -a errors;
# Loop over staged files and check for any specific pattern listed in PATTERNS keys
# Filter only added (A), copied (C), modified (M) files
for file in $(git diff --staged --name-only --diff-filter=ACM --no-color --unified=0); do
for elem in ${!PATTERNS[*]} ; do
{ git show :0:"$file" | grep -Eq ${elem}; } || continue;
errors+=("${PATTERNS[${elem}]} in ${file}…");
done
done
# Print errors
# author=$(git config --get user.name)
for error in "${errors[@]}"; do
echo -e "\033[1;31m${error}\033[0m"
# Mac OS only: use auditable speech
# which -s say && say -v Samantha -r 250 "$author $error"
done
# If there is any error, then stop commit creation
if ! [ ${#errors[@]} -eq 0 ]; then
exit 1
fi