如何从pygithub获取拉取请求中的文件内容?

问题描述

我无法找到如何在 github 上的拉取请求中获取文件内容。有没有办法使用 pygithub 来做到这一点?

对于存储库,我们可以使用

contents = repo.get_contents(filename)

然而,我没有找到这样的pull request对象的api。有没有办法做到这一点?

解决方法

我找到了一个很好的解决方法。我们无法从 File 对象中获取内容,但是,可以从任何版本的存储库中获取它们。我这样做如下:

无论 PR 是否打开/关闭/合并,这都有效。

(1) 从 PR 抓取提交。
(2) 从提交中抓取文件。
(3) 使用Repository对象获取PR中commit的sha对应的reference中的文件内容。

示例:


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

,

看看这个:https://docs.github.com/en/rest/reference/pulls#list-pull-requests-files

没试过,但 pygithub 确实有一个方法叫做 get_files 来使用这个 API 调用:https://pygithub.readthedocs.io/en/latest/github_objects/PullRequest.html#github.PullRequest.PullRequest.get_files

编辑:使用 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]