在一个 python 脚本中,我希望能够从 git 存储库工作树中的某个任意位置执行,在某个任意 git 存储库中,并且我想使用 GitPython 提取有关所述存储库的一些信息。
我可以从Repo对象中获取我需要的信息,但是我不知道如何打开一个Repo对象,但是Repo构造函数需要一个到repo-root的路径。
有没有办法构造一个 Repo 对象,该对象具有到存储库中某个位置的路径,而不仅仅是存储库根位置? 或者有没有办法查询给定路径的存储库根目录的位置?
我正在寻找类似的东西:
import git
r = git.Repo('whatever repo the cwd is in')
以下方法可行,但我发现它非常笨拙:
import git
import subprocess
rtpath = subprocess.check_output(["git", "rev-parse", "--show-toplevel"])
repo = git.Repo(rtpath.strip())
一种选择是实现与
git
内部实现相同的搜索语义...例如,查找 .git
目录,如果不存在,则 chdir
上一级,再次检查,等等。 :
import os
import git
lastcwd=os.getcwd()
while not os.path.isdir('.git'):
os.chdir('..')
cwd=os.getcwd()
if cwd == lastcwd:
raise OSError('no .git directory')
lastcwd=cwd
r = git.Repo('.')
上面的代码比较简单;例如,
git
不会在默认配置中遍历文件系统边界,而上面的代码将始终迭代到/
。
我只是来这里寻找同样的东西。看来如果您设置
search_parent_directories=True
的参数 git.Repo()
您不需要指定存储库的根文件夹,但可以使用任何子目录,例如如果您对文件夹结构中更深层的某些文件使用 os.path.dirname(os.path.realpath(__file__))