Search code examples
githubgithub-api

Using GitHub's API to get lines of code added/deleted per commit (on a branch)?


The following gets a raw list of commits for a project's master branch:

https://api.github.com/repos/<organization_name>/<repo_name/commits?page=0&per_page=30

Question 1: How can one get a similar list but for a specific <branchname>?

Question 2: The list of commits above doesn't include any data about the lines of code added/deleted per commit (i.e., a very rough productivity metric). Is there a way to get this data in the query?


Solution

  • You can fetch the specific branch with sha={branchname} param in the /commits params;

    sha string SHA or branch to start listing commits from. Default: the repository’s default branch (usually master).

    https://api.github.com/repos/<org_name>/<repo_name>/commits?sha=<branchName>&page=0&per_page=30
    

    To get per-file specific changes for each commit, you'd need to check url variable for each commit entity in the response of above URL. From that new endpoint call, you will get a more detailed information of that single commit. files variable in there will contain the changes contained in that commit. Both added & removed codes per file.

    An example with my repo;

    https://api.github.com/repos/buraequete/orikautomation/commits?sha=master&page=0&per_page=30

    If we get the first commits url;

    https://api.github.com/repos/buraequete/orikautomation/commits/89792e6256dfccc5e9151d81bf04145ba02fef8f

    Which contains the changes you want in files variable as a list.

    "files": [
        {
          "sha": "8aaaa7de53bed57fc2865d2fd84897211c3e70b6",
          "filename": "lombok.config",
          "status": "added",
          "additions": 1,
          "deletions": 0,
          "changes": 1,
          "blob_url": "https://github.com/buraequete/orikautomation/blob/89792e6256dfccc5e9151d81bf04145ba02fef8f/lombok.config",
          "raw_url": "https://github.com/buraequete/orikautomation/raw/89792e6256dfccc5e9151d81bf04145ba02fef8f/lombok.config",
          "contents_url": "https://api.github.com/repos/buraequete/orikautomation/contents/lombok.config?ref=89792e6256dfccc5e9151d81bf04145ba02fef8f",
          "patch": "@@ -0,0 +1 @@\n+lombok.accessors.chain = true"
        },
        ...
    ]
    

    Sorry but I don't think there is a way to get those per file changes in the original /commits endpoint call, you have to do multiple calls...