git pre receive hook 来检查提交信息

Posted

技术标签:

【中文标题】git pre receive hook 来检查提交信息【英文标题】:git pre receive hook to check commit message 【发布时间】:2017-01-18 01:32:24 【问题描述】:

我正在尝试编写一个预接收挂钩来使用 bash/shell 检查提交消息的模式。

如果任何提交有问题,我想拒绝整个推送。如何检索提交消息?

【问题讨论】:

【参考方案1】:

在 git 文档中有一个完整的示例和解释,涵盖了这一点。 Link to the example.

大致翻译 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

【讨论】:

【参考方案2】:

经过几次尝试并修复了问题和边缘情况,我以下一个结尾:

#!/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

【讨论】:

以上是关于git pre receive hook 来检查提交信息的主要内容,如果未能解决你的问题,请参考以下文章

在gitlab中新建项目,push的时候提示“pre-receive hook declined”

json 使用pre-commit git hook检查PHPCS的PSR-2验证。

json 使用pre-commit git hook检查PHPCS的PSR-2验证。

gitlab 使用原始的hooks同步到某一个目录

再谈git的http服务-权限控制hooks版

post-receive in Windows---git hooks trigger Jenkins to build artifcat