githubgithub-api

How to list all changed files in git commit using Github API


I want to use the Github API to list all files that were modified in a particular commit. This is for a public repo for which I do not have write permission.

I do not want to get all files submitted as a part of that commit because it may (I don't know if this is true or not) contain unchanged files and it certainly contains names of created and deleted files which I specifically do not want in my list.

Worst case, I will be fine if I can get the list of new, modified, deleted files with markers identifying their status so that I filter them after the API call, on the calling side.

Suggestions?


Solution

  • You can get a single commit using GET /repos/:owner/:repo/commits/:sha, and then you can process it using jq, for example this will print the modified files as a flat list:

    curl -s https://api.github.com/ENDPOINT | jq -r '.files | .[] | select(.status == "modified") | .filename'
    

    There's an important caveat though: this filters the result of the GET query, which contains the entire content of the commit, which could be a lot of data. I don't know if that's a concern to you. I looked for a way to filter the returned fields to avoid using unnecessary bandwidth, but I couldn't find in the API.

    You could get more details if you're interested in it, in JSON format, like this:

    curl -s https://api.github.com/ENDPOINT | jq '[.files | .[] | select(.status == "modified")]'
    

    This will produce output like this:

    [
      {
        "sha": "564324525eb706f7cc2756ceef8b82cdfeaf270c",
        "filename": "README.md",
        "status": "modified",
        "additions": 1,
        "deletions": 0,
        "changes": 1,
        "blob_url": "https://github.com/janosgyerik/test1/blob/41885b6c8183de3ab5be02884fdcc37d920e41b9/README.md",
        "raw_url": "https://github.com/janosgyerik/test1/raw/41885b6c8183de3ab5be02884fdcc37d920e41b9/README.md",
        "contents_url": "https://api.github.com/repos/janosgyerik/test1/contents/README.md?ref=41885b6c8183de3ab5be02884fdcc37d920e41b9",
        "patch": "@@ -1,3 +1,4 @@\n test1\n =====\n nothing special\n+Sat May 13 00:16:02 CEST 2017"
      },
      {
        "sha": "37a26e04e6bdc55935e00f2a092d936240771aca",
        "filename": "index.html",
        "status": "modified",
        "additions": 1,
        "deletions": 0,
        "changes": 1,
        "blob_url": "https://github.com/janosgyerik/test1/blob/41885b6c8183de3ab5be02884fdcc37d920e41b9/index.html",
        "raw_url": "https://github.com/janosgyerik/test1/raw/41885b6c8183de3ab5be02884fdcc37d920e41b9/index.html",
        "contents_url": "https://api.github.com/repos/janosgyerik/test1/contents/index.html?ref=41885b6c8183de3ab5be02884fdcc37d920e41b9",
        "patch": "@@ -55,3 +55,4 @@\n </div>\n </body>\n </html>\n+"
      }
    ]