Github API: 如何检查存储库是否为空?

Github API: how to check if repository is empty?

我正在使用 pygithub3 库来解析用户存储库,但有时它会在请求失败后因断言而崩溃。起初我怀疑我有命中率限制,但很快我意识到我可以 100% 重现 'empty' 存储库上的断言(参见示例)。

https://github.com/poelzi/vaultfs

我将如何检查存储库是否可用? 简化的代码片段:

for repo in gh.repos.list(user=author).all():
   ...
   contributors = repo.list_contributors(user=repo.owner.login, repo=repo.name).all()

它适用于 99% 的情况,但是当我 运行 进入空存储库时,它崩溃了,我找不到任何方法来 'detect' 它。

根据 this blog post,空存储库的贡献者端点响应代码是 204 No Content

这是一些相关的 curl 输出:

curl -v https://api.github.com/repos/poelzi/vaultfs/stats/contributors 
*   Trying 192.30.252.127...
* Connected to api.github.com (192.30.252.127) port 443 (#0)
* found 187 certificates in /etc/ssl/certs/ca-certificates.crt
* found 758 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
...
< HTTP/1.1 204 No Content
< Server: GitHub.com
< Date: Wed, 28 Oct 2015 20:10:10 GMT
< Status: 204 No Content
...

查看 pygithub 文档,我看到这已经是内置的:

Repository.get_stats_contributors()

Calls the GET /repos/:owner/:repo/stats/contributors end point.

This is the only method calling this end point.

This method returns None on empty repositories, and an empty list when stats have not been computed yet.

Return type: None or list of Repository.StatsContributor

也就是说,您必须检查 return 值。如果是 none,则存储库为空。

你的问题在 PyGithub 标签下,因此在该库中的一种可能方法下面。

import github
from github import GithubException

g = github.Github(token)

# or if you are using login and password g = github.Github(login, password)
repo = g.get_repo("poelzi/vaultfs")

try:
    # get repo content from root directory
    repo.get_contents("/")
except GithubException as e:
    print(e.args[1]['message']) # output: This repository is empty.