2

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?

Ruchit Vithani
  • 331
  • 4
  • 12

2 Answers2

1

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 :)

Ruchit Vithani
  • 331
  • 4
  • 12
0

Take a look at this: https://docs.github.com/en/rest/reference/pulls#list-pull-requests-files

Have not tried, but pygithub does have a method for this called get_files to use this API call: https://pygithub.readthedocs.io/en/latest/github_objects/PullRequest.html#github.PullRequest.PullRequest.get_files

EDIT: Using requests:

import requests
username = 'astrochun'
repo = 'Zcalbase_gal'
pr = 84
response = requests.get(f"https://api.github.com/repos/{username}/{repo}/pulls/{pr}/files")
dict0 = response.json()
pr_files = [elem['filename'] for elem in dict0]
astrochun
  • 1,642
  • 2
  • 7
  • 18
  • `get_files` return `PaginatedList[File]`. Unfortunately, `File` object does not have anything like `get_contents` or similar. So, I guess I have to make another request to get the file contents, using `raw_url` of File object. – Ruchit Vithani Feb 11 '21 at 05:16
  • `curl -X GET https://api.github.com/repos///pulls//files` – astrochun Feb 11 '21 at 05:33
  • See my edit for a simple `requests.get` approach – astrochun Feb 11 '21 at 05:39