如果检测到更改中的特定短语,如何防止 git commit?

Gie*_*ius 5 git bitbucket-server atlassian-sourcetree

我注意到一些模式,开发人员倾向于这样做 - 比如提交 javascript 测试,fdescribe或者fit留在其中(这意味着只有一个测试/套件将运行),通常在审查阶段发现,但抓住那些小事情更早。想知道如果在更改中检测到某些模式,是否有办法配置 git 以防止提交?

Mar*_*ler 5

这是 git commit hooks ( man githooks)的经典工作;例如,从您获得的标准脚本示例中.git/hooks,您可以将脚本添加pre-push到该文件夹​​(使其可执行!)。

这个来自 git 项目的示例脚本只检查提交名称,但如果你替换

git rev-list
Run Code Online (Sandbox Code Playgroud)

符合类似的东西

git diff $remote_sha $local_sha
Run Code Online (Sandbox Code Playgroud)

并为您的可疑字符串grep,例如

git diff $remote_sha $local_sha|grep -E '^\+.*(fdescribe|fit)'
Run Code Online (Sandbox Code Playgroud)

你可以为你的情况做到这一点。

#!/bin/sh

# An example hook script to verify what is about to be pushed.  Called by "git
# push" after it has checked the remote status, but before anything has been
# pushed.  If this script exits with a non-zero status nothing will be pushed.
#
# This hook is called with the following parameters:
#
# $1 -- Name of the remote to which the push is being done
# $2 -- URL to which the push is being done
#
# If pushing without using a named remote those arguments will be equal.
#
# Information about the commits which are being pushed is supplied as lines to
# the standard input in the form:
#
#   <local ref> <local sha1> <remote ref> <remote sha1>
#
# This sample shows how to prevent push of commits where the log message starts
# with "WIP" (work in progress).

remote="$1"
url="$2"

z40=0000000000000000000000000000000000000000

while read local_ref local_sha remote_ref remote_sha
do
    if [ "$local_sha" = $z40 ]
    then
        # Handle delete
        :
    else
        if [ "$remote_sha" = $z40 ]
        then
            # New branch, examine all commits
            range="$local_sha"
        else
            # Update to existing branch, examine new commits
            range="$remote_sha..$local_sha"
        fi

        # Check for WIP commit
        commit=`git rev-list -n 1 --grep '^WIP' "$range"`
        if [ -n "$commit" ]
        then
            echo >&2 "Found WIP commit in $local_ref, not pushing"
            exit 1
        fi
    fi
done

exit 0
Run Code Online (Sandbox Code Playgroud)