从rep中的任何位置获取PyGit2中当前repo的路径

2024-04-29 14:33:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Pygit2在我正在处理的回购中运行某些操作。在

如果我的代码文件不在repo的根目录下,如何从repo中的任何位置获取repo的路径?在

如果从根目录调用函数,我可以执行以下操作,但是如果从存储库代码中的任何位置运行它,该怎么做呢?在

$ cd /home/test/Desktop/code/Project
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

$ ipython3

In [1]: import os, pygit2
In [2]: repo = pygit2.Repository(os.getcwd())

Tags: 文件代码intest路径masterbranchhome
1条回答
网友
1楼 · 发布于 2024-04-29 14:33:45

一种方法是简单地遍历父目录,直到找到.git目录:

import os
import pathlib
import pygit2

def find_toplevel(path, last=None):
    path = pathlib.Path(path).absolute()

    if path == last:
        return None
    if (path / '.git').is_dir():
        return path

    return find_toplevel(path.parent, last=path)

toplevel = find_toplevel('.')
if toplevel is not None:
  repo = pygit2.Repository(str(toplevel))

当然,这里有一些注意事项。你不一定会找到 .git目录,如果有人设置了GIT_DIR环境 变量。如果您有一个git工作树,那么.git是一个文件,而不是一个 目录,libgit2似乎无法处理此问题(从版本开始 0.24)。在

相关问题 更多 >