【发布时间】:2021-02-11 04:48:03
【问题描述】:
我无法找到如何获取 github 上的拉取请求中存在的文件内容。有没有办法使用pygithub做到这一点?
对于存储库,我们可以使用
contents = repo.get_contents(filename)
但是,我没有为拉取请求对象找到这样的 api。有没有办法做到这一点?
【问题讨论】:
我无法找到如何获取 github 上的拉取请求中存在的文件内容。有没有办法使用pygithub做到这一点?
对于存储库,我们可以使用
contents = repo.get_contents(filename)
但是,我没有为拉取请求对象找到这样的 api。有没有办法做到这一点?
【问题讨论】:
我找到了一个很好的解决方法。我们无法从 File 对象中获取内容,但是,可以从任何版本的存储库中获取它们。我这样做如下:
无论 PR 是打开/关闭/合并,这都能正常工作。
(1) 从 PR 中获取提交。
(2) 从提交中抓取文件。
(3) 使用Repository 对象获取在PR 中commit 的sha 对应的引用文件的内容。
例子:
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]
【讨论】:
get_files 返回PaginatedList[File]。不幸的是,File 对象没有类似get_contents 或类似的东西。所以,我想我必须使用 File 对象的raw_url 发出另一个请求来获取文件内容。
curl -X GET https://api.github.com/repos/<username>/<repo>/pulls/<pr_num>/files
requests.get 方法