GitHub ActionsでPull Requestのコメントを更新する

概要

GitHub Actionsでコメントを更新する方法をまとめる
サードパーティアクションはなるべく使わない

一つのコメントを更新する

gh pr commentの--edit-lastを使う

gh --version
gh version 2.49.2 (2024-05-13)
https://github.com/cli/cli/releases/tag/v2.49.2

https://cli.github.com/manual/gh_pr_comment

--edit-last Edit the last comment of the same author

実装例

GitHub Actionsで下記のように書けば

  • 初回はコメントを書く
  • すでにコメントがあったらアップデートする

という処理がかける

      - name: Update comment
        continue-on-error: true
        id: update-comment
        run: gh pr comment ${{ github.event.pull_request.number }} -b "updated" --edit-last
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Add comment
        if: steps.update-comment.outcome == 'failure'
        run: gh pr comment ${{ github.event.pull_request.number }} -b "first comment"
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

制限事項

Edit the last comment of the same author

なので、github-actions botなどで処理をすると1つのコメントしか更新できない。
matrix strategy内で実行するとコメントが上書きされる

複数のコメントを更新する

https://github.com/actions/github-script を使う

実装例

      - name: add or update comment
        uses: actions/github-script@v7.0.1
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            const comment = `${{ matrix.value }}`
            const { data: comments } = await github.rest.issues.listComments({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
            })
            const botComment = comments.find(comment => {
              return comment.user.type === 'Bot' && comment.body.includes("${{ matrix.value }}")
            })
            if (botComment) {
            github.rest.issues.updateComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              comment_id: botComment.id,
              body: output
            })
            } else {
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: output
            })
            }

これによりMatrix strategyを利用しているときもコメントを更新できる

参考

https://github.com/orgs/community/discussions/38895