从回购中的任何地方获取 PyGit2 中当前回购的路径

Get path of the current repo in PyGit2 from anywhere within the repo

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

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

如果从 root 调用该函数,我可以执行以下操作,但是如果我 运行 从存储库代码中的任何位置调用该函数,该怎么办?

$ 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())

一种选择是遍历父目录,直到找到 .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).

pygit2 确实有一种机制可以做到这一点,来自 libgit2:

from pygit2 import Repository, discover_repository


def get_repo(path: str) -> Repository:
    repo_path = discover_repository(path)
    if not repo_path:
        raise ValueError(f"No repository found at '{path}' and its parents")
    return Repository(repo_path)

https://www.pygit2.org/repository.html?highlight=discover#pygit2.discover_repository