After a pull request is merged to a branch, how can I obtain the details/info about that newly-merged PR (the PR number, message, merge time, etc.) using the Github CLI?
If you want to obtain info (such as a PR number, message, etc.) about the pull request that was most recently merged to a branch, you can leverage the github CLI to get a list of PRs that have reached the merge state using gh pr list
and then filter for the most recent:
The following allows you to obtain a list of all merged PRs for a given branch:
gh pr list --state merged --base <branch_name>
// You can omit --base if you want to search through all PR merges for the whole repo
Then, you can strip this list into a more data-oriented fashion by pulling the timestamps of when each PR was merged and the attribute(s) you're wanting to get. For example, say I want the PR number:
gh pr list --state merged --base <branch_name> --json number,mergedAt
// You can see the available --json attributes by running the command with no value for --json and it will show them
// This returns a JSON list of all the PRs and the time they were merged like:
[
{
"mergedAt": "2021-01-3T00:00:000Z",
"number": 24
},
{
"mergedAt": "2021-01-2T00:00:000Z",
"number": 23
},
{
"mergedAt": "2021-01-04T00:00:00Z",
"number": 22
}
]
You can then use a jq
string to sort the list of PRs by their mergedAt
time, sort this list asc (reverse) to move the latest-merged PR to position 0, and then dissect the JSON object at index 0 to get the attribute you're looking for:
gh pr list --state merged --base <branch_name> --json number,mergedAt --jq 'sort_by(.mergedAt) | reverse | .[0].number'
// returns '22' in this case, the PR number of the latest merged PR
Hopefully someone gets some help out of this! I was having a mental workout trying to find out how to do this so I could obtain the most recent PR number inside of a Github action/workflow (and it doesn't help that the GH CLI doc doesn't mention half of this functionality)