通过Python在Git Hook中更新Git仓库

2 投票
1 回答
879 浏览
提问于 2025-04-17 09:06

我正在用Python写一个“后接收钩子”,希望能自动部署我项目中所有更新的文件。简单来说,每次“deploy”分支被推送时,它会通过FTP把更改的文件上传到我的服务器上。

这是我目前的进展:

def deploy(old, new):
        fileList = subprocess.Popen(['git', 'diff', '--name-only', old, new], stdout=subprocess.PIPE)
        files = fileList.stdout.read().split('\n')[:-1]

        # Switch to the regular repository and pull to it.
        os.chdir("/home/git/testrepo")
        subprocess.Popen(['git', 'pull'], cwd="/home/git/testrepo")

        for file in files:
                print file

for line in sys.stdin.xreadlines():
        old, new, ref = line.strip().split(' ')
        if ref == "refs/heads/deploy":
                print "Deploying the new commits now."
                deploy(old, new)
        else:
                print "No need to deploy."

包含这个钩子的代码库是一个裸库。然后我在 /home/git/testrepo/ 下有另一个库,它是这个库的克隆。

在这段代码中,我试图把工作目录切换到那个库,然后进行拉取操作。但是,这个方法不奏效。每次我推送并执行钩子时,都会收到这样的消息:“fatal: Not a git repository: '.'”。

有没有什么办法可以让我成功地从这个库拉取文件,这样我就可以把它们上传到我的其他服务器上?我尝试的每种方法都失败了。

1 个回答

0

git diff ... 命令失败了,因为它不知道你正在一个裸仓库里。

你可以试试 git --bare diff ...,或者设置一下 $GIT_DIR

撰写回答