如果检测到更改中的特定短语,如何防止git commit?
我注意到开发人员通常会采用的某些模式-例如在其中保留fdescribe
或fit
的情况下进行javascript测试(这意味着仅将运行一个测试/套件),通常是在审核阶段找到这种模式,但是早点抓那些小东西会很好.想知道是否有一种方法可以配置git以防止在更改中检测到某种模式时提交?
I noticed some patterns, that developers tend to do - like committing javascript tests with fdescribe
or fit
left in them (which means only one test/suite will be running), usually that is found in review phase, but it would be nice to catch those small things earlier. Wondering if there is a way to configure git to prevent commit if some pattern is detected within the changes?
这是git commit hooks(man githooks
)的经典工作;例如,从.git/hooks
中获得的标准脚本示例中,可以将脚本pre-push
添加到该文件夹(使其可执行!).
That's a classical job for git commit hooks (man githooks
); for example, from the standard script samples that you get in .git/hooks
, you can add a script pre-push
to that folder (make it executable!).
这个来自git项目的示例脚本仅检查提交名称,但是如果您替换了
This example script from the git project only checks the commit names, but if you replace the
git rev-list
使用类似
git diff $remote_sha $local_sha
和grep输入您可疑的字符串,例如
and grep for your suspcious strings, e.g.
git diff $remote_sha $local_sha|grep -E '^\+.*(fdescribe|fit)'
您可以根据自己的情况做到这一点.
you can make this happen for your case.
#!/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