Skip to main content
 首页 » 编程设计

python之通过 Python 中的 Git 钩子(Hook)更新 Git 存储库

2025年05月04日12linjiqin

我正在使用 python 编写一个接收后 Hook ,它有望用于自动部署我项目中的所有更新文件。本质上,每次推送“部署”分支时,它都会通过 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." 

包含这个钩子(Hook)的仓库是一个裸仓库。然后我在 /home/git/testrepo/ 下有另一个存储库,它是该存储库的克隆。

在此代码中,我尝试将我的工作目录更改为该存储库,然后启动 pull 。然而,这是行不通的。相反,当我推送并执行 Hook 时,我收到以下消息:“fatal: Not a git repository: '.'”。

关于如何成功 pull 到这个存储库,以便我可以将它的文件上传到我的其他服务器的任何想法?我尝试过的所有方法都失败了。

请您参考如下方法:

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

尝试 git --bare diff ... 或设置 $GIT_DIR。