Search code examples
github-apipygithub

Github API: how to check if repository is empty?


I'm using pygithub3 library to parse user repositories, but from time to time, it crasshes on assertion after failed request. At first I suspected that I have hit rate limit, but soon I realized that I can 100% reproduce assertion on 'empty' repository (see example).

https://github.com/poelzi/vaultfs

How would I go around checking if repository is available? Simplified code snippet:

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

It works for in 99% cases, but when I run into empty repositories, it crashes and I couldn't find any way to 'detect' it.


Solution

  • Your question under PyGithub tag, so below one of possible ways to do it in that library.

    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.