如何在post接收钩子中使用GIT访问存储库文件

如何在post接收钩子中使用GIT访问存储库文件,git,git-post-receive,Git,Git Post Receive,我对GIT有这样一个场景: 我想在推送过程中更改特定文件时对其“执行某些操作”。 例如,如果.sql文件发生更改,则必须将其转储到数据库中 我在GIT中使用“post receive”钩子,并使用如下语句: while read oldrev newrev refname; do if [ "$refname" = "refs/heads/master" ]; then # definitely updating master; $oldrev and $newrev e

我对GIT有这样一个场景:

我想在推送过程中更改特定文件时对其“执行某些操作”。 例如,如果.sql文件发生更改,则必须将其转储到数据库中

我在GIT中使用“post receive”钩子,并使用如下语句:

while read oldrev newrev refname; do
    if [ "$refname" = "refs/heads/master" ]; then
        # definitely updating master; $oldrev and $newrev encompass the changes
        if git diff-tree --name-only -r -z $oldrev $newrev dump.sql; then
            # dump.sql changed...
        fi
    fi
done
DUMP=$(git diff tree--name only-r-z master DUMP.sql);
如果[-n“$DUMP”];然后
//使用新的dump.sql
fi

如何访问刚刚从钩子中推出的新dump.sql?

您可以使用以下命令从修订版$rev检索文件dump.sql:

git cat-file blob $rev:dump.sql
post接收钩子也被称为用于除推主。。。希望您在某个地方检查您正在处理更新的master ref。作为样式问题,我将使用传递给钩子的新修订值,而不是直接从钩子中引用master

通常我写一个post接收钩子,如下所示:

while read oldrev newrev refname; do
    if [ "$refname" = "refs/heads/master" ]; then
        # definitely updating master; $oldrev and $newrev encompass the changes
        if git diff-tree --name-only -r -z $oldrev $newrev dump.sql; then
            # dump.sql changed...
        fi
    fi
done

重要的是,这还可以处理一次推送向master发送多个提交的问题——您在问题中显示的命令只查看了master上的最后一次提交。

非常感谢!有没有办法确保所引用的“分支”更新为master而不是任何其他分支?@随机化post receive hook会在stdin上传递一些信息。。。我将通过编辑答案来说明,它将更易于阅读哇!再次感谢!最后一个问题:通过谷歌搜索,我发现关于编写钩子的文档太笼统了。你知道有什么好的网站或书籍能正确地解释如何编写钩子、定义的环境变量等吗?除了githooks手册页(标准参考文档的一部分)之外,我不知道其他任何文档。老实说,我主要是通过查看示例来了解它们的——post-receive和pre-receive是最流行的,因为它们被用作其他系统的服务器端触发器。因此,接收后电子邮件和各种访问控制预接收脚本等示例非常有用;然后或者可能会出现“致命:参数不明确…”错误。