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

4
场景: 在使用git提交文件时,我想要在pre-commit hook中检查某一行是否已被修改。因此,我希望将修改后的文件中的某些部分与存储库中的相应部分进行比较。 背景: 我想要确保要提交的文件具有不同于已在存储库中的文件的版本号。用户应该强制为文件提供适当的版本号。自动增加版本号不是一个选项,因为我们使用多部分版本(1.0.0.0),用户必须修改版本字符串的正确部分... 问题: 在pre-commit hook中是否可以访问修改后的文件和存储库文件的文件内容?
1个回答

7
答案是肯定的。
但是,pre commit hook是客户端钩子,可以被删除或删除,这就是为什么最好使用服务器端钩子的原因。
这是一个检查所需文件是否已修改的示例钩子。一旦确定文件是否已提交,请使用以下操作:
# you have the commit id so you can checkout the given file
git show <commit id>:<full path to file>

完整的示例代码:

pre-receive钩子

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

1
据我所理解的建议答案,您只需要检查是否更改了专用文件。我的问题是关于检查文件中某行是否更改 - 因为文件可能包含许多其他更改... - hoppfrosch
这就是为什么我提到如何获取文件内容(使用show命令),现在你可以用sed、awk、grep等任何方式进行操作。这是一个完整的答案,但我不知道你要查找哪个字符串,这就是你需要做的全部。 - CodeWizard
1
我不仅给了你我正在使用的脚本,还详细解释了它是什么以及如何工作。 - CodeWizard
我明白了 - 我没有正确理解 "git show" 的含义。谢谢您的回复。我会尽快测试它。 - hoppfrosch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接