How to auto comment on GitHub Pull Requests

The GitHub API supports the ability to add comments to open Pull Requests. With this in mind, you can utilize environment variables and a cURL to automatically update/comment on a PR.

This could be utilized for reporting data collected during builds running on CircleCI, such as overall test coverage stats.

Instructions

The first step would be to set up a new personal token for a user who will be making the comments, this could be you (the admin on the account) or a new bot user. Then set the username of who will make comments and the personal token as project-level environment variables.

GH_USER and GH_TOKEN

Once that is complete you can add a new step that will check for an Open PR and post a comment to it:

- run:
name: Post Stats to GitHub PR
command: |
sudo apt-get install jq

pr_response=$(curl --location --request GET "https://api.github.com/repos/$CIRCLE_PROJECT_USERNAME/$CIRCLE_PROJECT_REPONAME/pulls?head=$CIRCLE_PROJECT_USERNAME:$CIRCLE_BRANCH&state=open" \
-u $GH_USER:$GH_TOKEN)

if [ $(echo $pr_response | jq length) -eq 0 ]; then
echo "No PR found to update"
else
pr_comment_url=$(echo $pr_response | jq -r ".[]._links.comments.href")
fi

curl --location --request POST "$pr_comment_url" \
-u $GH_USER:$GH_TOKEN \
--header 'Content-Type: application/json' \
--data-raw '{
"body": "This would be the data to add"
}'

The last step is to replace the "This would be the data to add" with the content you want to be added as a comment.

When this step runs it will add the data that you have defined automatically.

Was this article helpful?
19 out of 38 found this helpful

Comments

0 comments

Article is closed for comments.