![](/img/trans.png)
[英]Is it possible to save a git commit message to a file in a pre-commit hook?
[英]git pre receive hook to check commit message
我正在嘗試編寫一個預接收鈎子來使用 bash/shell 檢查提交消息的模式。
如果任何提交有問題,我想拒絕整個推送。 如何檢索提交消息?
在git docs中有一個完整的示例及其解釋,其中涵蓋了這一點。 鏈接到示例 。
大致翻譯一下ruby示例,我們有:
#!/bin/bash
set -eo pipefail
refname="$0"
oldrev="$1"
newrev="$2"
echo "Enforcing Policies..."
# Iterate over all the commits
for commit in $(git rev-list 538c33..d14fc7); do
git cat-file commit "${commit}" | sed '1,/^$/d' | your-validator
done
經過多次嘗試和修復問題和邊緣情況后,我以下一個結束:
#!/bin/bash
# regexp sample to validate commit messages
COMMIT_MSG_PATTERN="^olala[0-9]{3}"
refname="$1"
oldrev="$2"
newrev="$3"
# list of commits to validate
if echo "$oldrev" | grep -Eq '^0+$'; then
# list everything reachable from $newrev but not any heads
#commits=$(git rev-list $(git for-each-ref --format='%(refname)' refs/heads/* | sed 's/^/\^/') "$newrev")
# or shorter version that also get list of revisions reachable from $newrev but not from any branche
commits=$(git rev-list $newrev --not --branches=*)
else
commits=$(git rev-list ${oldrev}..${newrev})
fi
# Iterate over all the commits
for commit in $commits; do
#echo "commit=$commit"
MSG=$(git cat-file commit "${commit}" | sed '1,/^$/d')
if echo "$MSG" | grep -qvE "$COMMIT_MSG_PATTERN" ;then
echo "$MSG"
echo "Your commit message must match the pattern '$COMMIT_MSG_PATTERN'"
exit 1
fi
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.