使用 pygit2 的 discover_repository 定位目录中的多个存储库

Using pygit2's discover_repository to locate multiple repositories in a directory

我有一个项目,我需要在其中访问裸 git 存储库的(本地)目录,以便从它们的历史记录中获取特定项目。我需要一个函数来遍历目录并执行类似的操作:

repo = pygit2.discover_repository("/path/to/repo")

但我需要能够在 for 循环中执行此操作。

每个存储库都用于一个不同的项目,通过在我的代码中的其他地方使用一些嵌套循环,它们的名称被定位并存储在一个列表中。

1) 如果我在整个代码中仅根据列表索引引用项目名称(或者我应该给每个回购协议),那么使用项目名称代替上面的 repo 是否有意义像 repo_n 这样的名称,其中 n 是一个整数,在发现存储库的循环的每次迭代中递增)?

2) 是否可以在 for 循环中发现这些存储库,以便我可以一次性全部获取它们,或者我需要一个一个地完成它们吗?

3) 如果 可以在循环中执行此操作,我该如何创建一个包含项目名称和新发现存储库对象?

最初我使用如下代码开始:

name = 'repo_'
i = 0
repo_list = {}
items = get_items() # defined elsewhere

for item in os.listdir(dirpath):
    i = i + 1 # this was just to add a custom name to the repos located
    repo_name = name + str(i)
    path_to_repo = os.path.join(dirpath, item)

    repo = pygit2.discover_repository(path_to_repo)
    repo_list[item] = repo

但这是返回 string 个对象的列表而不是 Repository 个对象的列表。原来 discover_repository() 函数 returns path 到存储库,而不是 Repository 对象。我不得不说,我在 pygit2 documentation, and I hadn't seen anyone use or talk about it until I found this SO question 中的任何地方都没有找到 discover_repository() 函数。但现在我知道了(我认为它对未来的读者也很有用):

pygit2's discover_repository(path) function returns a string representation of the path to the located repository. This is not a Repository object, which still must be instantiated.

所以在到处寻找答案后,我找到了 this snippet,其中包括我遗漏的一行:

    path_to_repo = os.path.join(dirpath, item)

    repo = pygit2.discover_repository(path_to_repo)
    repo_name = Repository(repo) # this line was missing
    repo_list[item] = repo_name

更近了,但有些地方不对劲。当然,这就是我想要的,但这不是有点多余吗?后来,在我的代码的不同部分工作之后,我最终得到了整个 for 循环:

for item in os.listdir(dirpath):
    i = i + 1
    repo_name = name+str(i)
    path_to_repo = os.path.join(dirpath, item)

    repo_name = Repository(path_to_repo)
    repo_list[item] = repo_name

这样就达到了预期的效果。我现在返回了一个看起来像这样的字典:

{'repo_1': [listOfRepositoryObjects], 'repo_2': [anotherListOfRepositoryObjects]}

所以我实际上根本不需要 pygit2.discover_repository() 函数,因为我包含了一些在 path_to_repo = os.path.join(dirpath, item) 中做同样事情的东西。由于他们最终返回的是同样的东西,我将继续使用我编写的函数,因为它似乎更符合我的项目要求。