name: Comment benchmark results on a PR
on:
  workflow_run:
    workflows: ["benchmark"]
    types:
      - completed
jobs:
  comment:
    runs-on: ubuntu-latest
    permissions:
      # list and download artifact
      actions: read
      # post benchmark results
      pull-requests: write
    steps:
      - uses: actions/github-script@v4.1
        with:
          script: |
            var artifacts = await github.actions.listWorkflowRunArtifacts({
               owner: context.repo.owner,
               repo: context.repo.repo,
               run_id: ${{github.event.workflow_run.id }},
            });
            var matchArtifact = artifacts.data.artifacts.filter((artifact) => {
              return artifact.name == "benchmark-comment"
            })[0];
            var download = await github.actions.downloadArtifact({
               owner: context.repo.owner,
               repo: context.repo.repo,
               artifact_id: matchArtifact.id,
               archive_format: 'zip',
            });
            var fs = require('fs');
            fs.writeFileSync('${{github.workspace}}/benchmark-comment.zip', Buffer.from(download.data));
      - id: unpack
        run: |
          mkdir -p benchmark-comment
          unzip -d benchmark-comment benchmark-comment.zip
          echo "::set-output name=pr-number::$(cat benchmark-comment/pr-number)"
          COMMENT=$(cat benchmark-comment/benchstat.txt)
          COMMENT="${COMMENT//'%'/'%25'}"
          COMMENT="${COMMENT//$'\n'/'%0A'}"
          COMMENT="${COMMENT//$'\r'/'%0D'}"
          echo "::set-output name=comment::$COMMENT"
      - name: post benchmark results
        uses: marocchino/sticky-pull-request-comment@v2
        with:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          header: Benchmark Results
          number: ${{ steps.unpack.outputs.pr-number }}
          message: |
            ## Benchmark Result
            <details><summary>Benchmark diff with base</summary>

            ```
            ${{ steps.unpack.outputs.comment }}
            ```
            </details>
