最初我从如下代码开始:
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()
函数返回存储库的路径,而不是 Repository 对象。我不得不说,我在pygit2 文档discover_repository()
中的任何地方都没有找到一个函数,在我找到这个 SO question之前,我还没有看到任何人使用或谈论它。但现在我知道了(我认为这对未来的读者也很有用):
pygit2 的discover_repository(path)
函数返回一个字符串表示的路径到所定位的存储库。这不是一个 Repository 对象,它仍然必须被实例化。
因此,在到处寻找答案后,我找到了这个片段,其中包括我错过的一行:
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)
. 由于他们最终返回了相同的东西,我将使用我编写的函数,因为它似乎更适合我的项目要求。