I currently have a GitHub workflow that is triggered on push to main. This builds and deploys the artifact and so on. Now I want to log additional information with another action. I want to save the person who created the preceding pull request and the person who approved the pull request.
What is the best way to get this information? It feels like the execution of the workflow should remain on push. But to get this information I would have to start the workflow as soon as the PR has been approved & merged. What would be the best approach from a design point of view?
You need to use pull_request
trigger for your workflow and specify closed
as a type of the event. This trigger makes pull_request
event available to the workflow that indicates whether pull request was merged or not. You can use this flag to only run your workflow if a PR was merged.
To get creator and approver, you can use GitHHub CLI and call Get Pull Request API and then List Reviews for a Pull Request API
name: Pull Request Closed Workflow
on:
pull_request:
types:
- closed
jobs:
pr-merged:
if: github.event.pull_request.merged
runs-on: ubuntu-latest
steps:
- name: Extract creator and approver
run: |
# Get PR creator
gh api /repos/$GITHUB_REPOSITORY/pulls/${{ github.event.pull_request.number }} | jq -r '.user.login'
# Get PR approver
gh api /repos/$GITHUB_REPOSITORY/pulls/${{ github.event.pull_request.number }}/reviews | jq -r 'map(select(.state == 'APPROVED')) | .[0].user.login'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
7