Github Action to remove previous job PR comments
Here’s a Github Action that finds and removes PR comments based on a string identifier. This is useful for Github Action workflows that post comments to PRs, as it clears up out-of-date comments from earlier workflow runs.
name: Command & Comment
description: Run a bash command and comment failure output back to PR
inputs:
identifier:
description: Single word identifier for comments to remove
required: true
runs:
using: "composite"
steps:
- name: Remove previous job comments
uses: actions/github-script@v7
with:
script: |
const pr_comments = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
})
await Promise.all(
pr_comments.data.filter(
comment => comment.body?.startsWith("[${{inputs.identifier}}]")
).map(
comment => github.rest.issues.deleteComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
comment_id: comment.id,
})
)
)
It removes comments on the PR it is running against if the comment begins with
[{identifier}]
. If other comments happen to begin with that then they will
also be removed. More checks could be added to the filter to avoid this if it’s
a problem on a particular project.
The key part of the Github Action is the Github Script step:
const pr_comments = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
})
await Promise.all(
pr_comments.data.filter(
comment => comment.body?.startsWith("[${{inputs.identifier}}]")
).map(
comment => github.rest.issues.deleteComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
comment_id: comment.id,
})
)
)
You can call this action from another workflow like this:
# ...
jobs:
foobar:
steps:
- name: Remove previous foobar comments
uses: ./.github/actions/remove_comments
with:
identifier: foobar