Automate Pull Request Comments with GitHub Actions

When working with Pull Requests (PRs) in GitHub, it is often helpful to provide immediate feedback or relevant information directly in the conversation view. Whether it is a deployment preview URL, code coverage results, or a summary of changes, having this information automatically posted as a comment saves time and improves collaboration.

In this post, I will show you how to use GitHub Actions to automatically add or update a comment on a PR. We will use the marocchino/sticky-pull-request-comment action, which is excellent for maintaining a single, up-to-date comment rather than spamming the PR with new comments for every run.

The Use Case: Cloudflare Preview URLs

A common scenario is deploying a preview version of your site for every Pull Request. Services like Cloudflare Pages generate a unique URL for each deployment. To make it easy for reviewers to access this preview, we can post the URL directly to the PR.

The Workflow

We will use the marocchino/sticky-pull-request-comment action. This action allows you to specify a header, which acts as a unique identifier. If a comment with that header already exists, the action updates it; otherwise, it creates a new one.

Here is an example configuration that posts a Cloudflare deployment URL:

 1- name: Add/Update PR Comment
 2  uses: marocchino/sticky-pull-request-comment@v2
 3  if: github.event_name == 'pull_request'
 4  with:
 5    header: cloudflare-preview
 6    message: |
 7      ### ✅ Deploy Complete!
 8      
 9      |  Name | Link |
10      |---------------------------------|------------------------|
11      | <span aria-hidden="true">🔨</span> Latest Commit | ${{ github.sha }} |
12      | <span aria-hidden="true">😎</span> Deployment URL | [${{ steps.cloudflare.outputs.deployment-url }}](${{ steps.cloudflare.outputs.deployment-url }}) |

Key Components

  1. if: github.event_name == 'pull_request': This ensures the step only runs for Pull Request events. It prevents the action from failing or running unnecessarily on push events to the main branch.

  2. header: cloudflare-preview: This is the crucial part for the “sticky” behavior. The action searches for a comment with this hidden header. This ensures that subsequent runs update the existing comment instead of creating a new one, keeping the PR conversation clean.

  3. message: This is the content of the comment. It supports Markdown, so you can format it with tables, links, and headers. In the example above, we create a neat table displaying the commit SHA and the clickable deployment URL.

Conclusion

Automating PR comments is a simple yet powerful way to enhance your development workflow. By providing relevant context directly in the PR, you reduce friction for reviewers and ensure that important information like preview URLs is always accessible and up-to-date.


Comments

Twitter Facebook LinkedIn WhatsApp