pythongit-forkgithub3.py

Can github3.py be used to find the parent/upstream of a forked repo?


Given a forked repo, how can I use github3.py to find the parent or upstream repo that it was forked from? This is fairly easy with requests but I can not figure out how to do it in github3.py.

With requests:

for repo in gh.repositories_by(username):  # github3.py provides a user's repos
  if repo.fork:                            # we only care about forked repos
    assert 'parent' not in repo.as_dict()  # can't find parent using github3.py
    repo_info = requests.get(repo.url).json()  # try with requests instead
    assert 'parent' in repo_info, repo_info    # can find parent using requests
    print(f'{repo_info["url"]} was forked from {repo_info["parent"]["url"]}')
    # https://github.com/username/repo was forked from
    # https://github.com/parent/repo

This use case is similar to How can I find all public repos in github that a user contributes to? but we also need to check the parent/upstream repo that the user's repo was forked from.


Solution

  • The documentation shows that this is stored as repo.parent, that however, is only available on Repository objects. repositories_by returns ShortRepository objects.

    This would look like:

    for short_repo in gh.repositories_by(username):
        repo = short_repo.refresh()
        if repo.fork:
            parent = repo.parent