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.

The first step would be to setup 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_API)

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_API \
--header 'Content-Type: application/json' \
--data-raw '{
"body": "This would be the data to add"
}'

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

Was this article helpful?
3 out of 6 found this helpful

Comments

0 comments

Please sign in to leave a comment.