List all files in a pull request using GitHub Actions

At work we wanted to list all affected files in a pull request, to perform some additional tasks on them, using GitHub Actions. After trying (and failing) to do this with git itself, which turned out more complicated than it should be, we decided to use the GitHub API instead.

Fortunately there is an API call to do exactly this, called List pull request files. The method requires us to provide the repository name, owner, and the pull request number. Both owner and repository name is available as a default environment variable called $GITHUB_REPOSITORY , so that is straight forward to obtain. What about the pull request number? Apparently the best way seems to be to grab it from the webhook event file, which can be found by reading the value of the $GITHUB_EVENT_PATH variable.

That is all we need to use this. We used jq to filter out the raw pull request number as well as only the filenames from the actual API call.

$ API=https://api.github.com/
$ PR=$(jq --raw-output .pull_request.number "$GITHUB_EVENT_PATH")
$ URL=$API/repos/$GITHUB_REPOSITORY/pulls/$PR/files
$ curl -s $URL | jq -r '.[] | .filename'

This works well for public repositories, but what about private ones? For that purpose, GitHub provides an access token ready to use from actions, that goes into the Authorization header.

curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}"

With that, we have what we need to list all files that changed in a pull request, available to use in the action workflow. This is the full example in yaml format:

on: pull_request
jobs:
  job:
    steps:
     - name: List files in PR
       run: |
         API=https://api.github.com/
         PR=$(jq --raw-output .pull_request.number "$GITHUB_EVENT_PATH")
         URL=$API/repos/$GITHUB_REPOSITORY/pulls/$PR/files
         curl -H "Authorization: token ${{ secrets.GITHUB_TOKEN }} -s $URL | jq -r '.[] | .filename'

Leave a comment