Search code examples
githubpygithub

How to get contents of file in pull request from pygithub?


I'm not able to find how to get contents of file present in pull request on github. Is there any way to do this using pygithub?

For repository, we can do this using

contents = repo.get_contents(filename)

However, I did not find such api for pull request object. Is there any way to do this?


Solution

  • I have found a nice workaround to this. We can not get contents from File objects, however, it is possible to get them from repository, at any version. I did this like following :

    This works irrespective of PR is open/closed/merged.

    (1) Grab commits from PR.
    (2) Grab files from commits.
    (3) Use Repository object to get the contents of file at reference corresponding the sha of commit in PR.

    Example :

    
    github = Github(login_or_token=my_github_token)
    repo = github.get_repo(repo_name, lazy=False)
    
    # Grab PR
    pull_number = 20
    pr = repo.get_pull(pull_number)
    
    commits = pr.get_commits()
    
    for commit in commits:
        files = commit.files
        for file in files:
            filename = file.filename
            contents = repo.get_contents(filename, ref=commit.sha).decoded_content
    
            # Now do whatever you want to do with contents :)