name: Post mypy_primer comment

on:
  workflow_run:
    workflows:
      - Run mypy_primer
    types:
      - completed

permissions:
  contents: read
  pull-requests: write

jobs:
  comment:
    name: Comment PR from mypy_primer
    runs-on: ubuntu-latest
    steps:
      - name: Download diffs
        uses: actions/github-script@v5
        with:
          script: |
            const fs = require('fs');
            const artifacts = await github.rest.actions.listWorkflowRunArtifacts({
               owner: context.repo.owner,
               repo: context.repo.repo,
               run_id: ${{ github.event.workflow_run.id }},
            });
            const [matchArtifact] = artifacts.data.artifacts.filter((artifact) =>
              artifact.name == "mypy_primer_diffs");

            const download = await github.rest.actions.downloadArtifact({
               owner: context.repo.owner,
               repo: context.repo.repo,
               artifact_id: matchArtifact.id,
               archive_format: "zip",
            });
            fs.writeFileSync("diff.zip", Buffer.from(download.data));

      - run: unzip diff.zip
      - run: |
          cat diff_*.txt | tee fulldiff.txt

      - name: Post comment
        id: post-comment
        uses: actions/github-script@v5
        with:
          github-token: ${{secrets.GITHUB_TOKEN}}
          script: |
            const fs = require('fs')
            let data = fs.readFileSync('fulldiff.txt', { encoding: 'utf8' })
            // posting comment fails if too long, so truncate
            if (data.length > 30000) {
              data = data.substring(0, 30000) + `\n\n... (truncated ${data.length - 30000} chars) ...\n`
            }

            let body
            if (data.trim()) {
              body = 'Diff from [mypy_primer](https://github.com/hauntsaninja/mypy_primer), showing the effect of this PR on open source code:\n```diff\n' + data + '```'
            } else {
              body = 'According to [mypy_primer](https://github.com/hauntsaninja/mypy_primer), this change has no effect on the checked open source code. 🤖🎉'
            }

            const prNumber = parseInt(fs.readFileSync("pr_number.txt", { encoding: "utf8" }))
            await github.rest.issues.createComment({
              issue_number: prNumber,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body
            })
            return prNumber

      - name: Hide old comments
        # v0.3.0
        uses: kanga333/comment-hider@bbdf5b562fbec24e6f60572d8f712017428b92e0
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          leave_visible: 1
          issue_number: ${{ steps.post-comment.outputs.result }}
