15

net project for which I need to detect and parse changes made to a specific single text file in a repository between different pull requests.

I've been successfully able to access the pull requests and the commits using the Github API but I don't know how to retrieve the lines that changed in the last commit?

Is this possible using the API? What would be the best approach? If not should I try to read the last two file versions and implement a differ algorithm locally? Thanks!

3 Answers 3

23

A pull request contains a diff_url entry like

"diff_url": "https://github.com/octocat/Hello-World/pull/1347.diff"

You can do this for any commit. For example, to get the diff of commit 7fd1a60b01f91b3 on octocat's Hello-World it's https://github.com/octocat/Hello-World/commit/7fd1a60b01f91b314f59955a4e4d4e80d8edf11d.diff.

This also works for branches. Here's master on octocat's Hello-World. https://github.com/octocat/Hello-World/commit/master.diff.

The general form is:

https://github.com/<owner>/<repo>/commit/<commit>.diff
Sign up to request clarification or add additional context in comments.

4 Comments

For those who find this answer: I want to add that you need to specify the "Accept: application/vnd.github.v3.diff" header (patch also works). Source: github.community/t5/GitHub-API-Development-and/…
Only works for public repositories. Does not support authentication.
I just had to pass the header (as @Shersh mentioned). Didn't have to append the .diff. I'm also hitting a /commits endpoint and not /commit. So maybe things have changed since 2016.
I was able to get the diff string in node using the @oktokit/core package, and from a private repo, like this: const oktokit = new Octokit({ auth: 'optionalToken', }); oktokit.request( 'GET /repos/{owner}/{repo}/commits', { owner: 'repoOwner', repo: 'repoTitle', headers: { Accept: 'application/vnd.github.diff', }, } ) Latest github docs on the vnd header type: docs.github.com/en/rest/overview/…
3

For private repositories:

curl -H "Accept: application/vnd.github.v3.diff" https://<personal access token>:[email protected]/repos/<org>/<repo>/pulls/<pull request>

Also works with the normal cURL -u parameter.

See: https://docs.github.com/en/rest/reference/pulls#get-a-pull-request

Comments

3

The crux is in the requested media type. You can pass the Accept header with value

application/vnd.github.diff

see documentation. For full reference, a GET request with the above and Authorization header to https://api.github.com/repos/{orgName}/{repoName}/pulls/{prId} does the trick.

1 Comment

indeed - thanks for this. just the PR url, normal api auth and this header.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.