通过git hook执行python子进程

2023-12-24

我在 Git 存储库上运行 Gitolite,并且我有用 Python 编写的 post-receive 挂钩。我需要在 git 存储库目录中执行“git”命令。有几行代码:

proc = subprocess.Popen(['git', 'log', '-n1'], cwd='/home/git/repos/testing.git' stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc.communicate()

在我进行新的提交并推送到存储库后,脚本会执行并显示

fatal: Not a git repository: '.'

If I run

proc = subprocess.Popen(['pwd'], cwd='/home/git/repos/testing.git' stdout=subprocess.PIPE, stderr=subprocess.PIPE)

正如预期的那样,它表示 git 存储库的正确路径(/home/git/repos/testing.git)

如果我从 bash 手动运行此脚本,它会正常工作并显示“git log”的正确输出。我做错了什么?


您可以尝试使用命令行开关设置 git 存储库:

proc = subprocess.Popen(['git', '--git-dir', '/home/git/repos/testing.git', 'log', '-n1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

--git-dir需要指向一个实际的 git 目录(.git在工作树中)。请注意,对于某些命令,您also需要设置一个--work-tree选项也。

设置目录的另一种方法是使用GIT_DIR环境变量:

import os
env = os.environ.copy()
env['GIT_DIR'] = '/home/git/repos/testing.git'
proc = subprocess.Popen((['git', 'log', '-n1', stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)

显然钩子已经设置好了GIT_DIR但显然这对于​​你的情况来说是不正确的(它可能是相对的);上面的代码将其设置为完整的显式路径。

See the git manpage https://www.kernel.org/pub/software/scm/git/docs/v1.7.10.1/git.html.

编辑:显然它只适用于指定 cwd 并覆盖的 OPGIT_DIR var:

import os
repo = '/home/git/repos/testing.git'
env = os.environ.copy()
env['GIT_DIR'] = repo
proc = subprocess.Popen((['git', 'log', '-n1', stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, cwd=repo)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过git hook执行python子进程 的相关文章

随机推荐