git precommit-hook:检查行内容是否已更改

时间:2016-03-31 07:56:48

标签: git pre-commit-hook pre-commit

Szenario:在使用git进行文件提交时,我想在预提交挂钩内检查某条线是否已被修改。因此,我想比较修改后的文件中的部分行与存储库中相应的linepart。

后台:我想确保要提交的文件的版本号不是存储库中已有的文件。应强制用户为文件提供适当的版本号。这里不能自动增加提交时的版本号,因为我们使用多部分版本(1.0.0.0),用户必须修改版本字符串的正确部分......

问题:是否可以在预提交挂钩中访问已修改的文件内容以及存储库文件?

1 个答案:

答案 0 :(得分:5)

答案是肯定的。

但是 - pre commit hook是一个客户端钩子,可以删除o删除,这就是为什么用服务器端钩子做它更好

这是一个示例钩子,用于检查是否修改了所需的文件。 一旦你知道文件是否已提交,请使用:

# you have the commit id so you can checkout the given file
git show <commit id>:<full path to file>

完整的示例代码:

pre-receive hook

#!/bin/sh

# Check to see if this is the first commit in the repository or not
if git rev-parse --verify HEAD >/dev/null 2>&1
then
    # We compare our changes against the previous commit
    against=HEAD^
else
    # Initial commit: diff against an empty tree object
    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

# Redirect output to screen.
exec 1>&2

# Check to see if we have updated the given file
if [ $(git diff-tree -r --name-only $against | grep <ANY FILE YOU WANT TO FIND OUT HERE> ) ];
then

    # you have the commit id so you can checkout the given file
    # the commit is: git rev-parse HEAD
    git show <commit id>:<full path to file>

    # personal touch :-)
    echo "                                         "
    echo "                   |ZZzzz                "
    echo "                   |                     "
    echo "                   |                     "
    echo "      |ZZzzz      /^\            |ZZzzz  "
    echo "      |          |~~~|           |       "
    echo "      |        |-     -|        / \      "
    echo "     /^\       |[]+    |       |^^^|     "
    echo "  |^^^^^^^|    |    +[]|       |   |     "
    echo "  |    +[]|/\/\/\/\^/\/\/\/\/|^^^^^^^|   "
    echo "  |+[]+   |~~~~~~~~~~~~~~~~~~|    +[]|   "
    echo "  |       |  []   /^\   []   |+[]+   |   "
    echo "  |   +[]+|  []  || ||  []   |   +[]+|   "
    echo "  |[]+    |      || ||       |[]+    |   "
    echo "  |_______|------------------|_______|   "
    echo "                                         "
    echo "                                         "
    echo "      You have just committed code       " 
    echo "      Your code is bad.!!!               "
    echo "      Do not ever commit again           "
    echo "                                         "
fi;

# set the exit code to 0 or 1 based upon your needs
# 0 = good to push
# 1 = exit without pushing.
exit 0;