name: Benchmark - CLI

on:
  pull_request:
    branches:
      - '*'
    paths:
      - lib/**
      - workspaces/**/lib/**
  issue_comment:
    types:
      - created
      - edited

jobs:
  trigger-benchmark:
    runs-on: ubuntu-latest
    steps:
      - name: Incoming Pull Request
        if: |
          (
            github.event_name == 'pull_request' &&
            github.event.pull_request.head.repo.full_name == 'npm/cli' 
          ) || (
            github.event_name == 'issue_comment' &&
            github.event.issue.pull_request &&
            github.event.issue.state == 'open' &&
            startsWith(github.event.comment.body, '@npm-cli-bot benchmark this')
          )
        uses: actions/github-script@v6
        with:
          github-token: ${{ secrets.BENCHMARK_DISPATCH_TOKEN }}
          script: |
            const {
              payload,
              eventName,
              repo: { owner, repo },
              issue: { number },
            } = context
          
            if (eventName === 'issue_comment') {
              const res = await github.rest.repos.getCollaboratorPermissionLevel({
                owner,
                repo,
                username: payload.comment.user.login,
              })
              if (res.data.permission !== 'admin') {
                core.info(`Commenter is not an admin, exiting`)
                return
              }
          
              // add emoji to comment if user is an admin to signal benchmark is running
              await github.rest.reactions.createForIssueComment({
                owner,
                repo,
                comment_id: payload.comment.node_id,
                content: 'rocket',
              })
            }
          
            const pullRequest = payload.pull_request || await github.rest.pulls.get({
              owner,
              repo,
              pull_number: number,
            }).then(r => r.data)

            core.info(`Pull request: ${pullRequest.number}`)
            core.info(`Base ref: ${pullRequest.base.ref}`)
          
            const matchesRelease = pullRequest.base.ref.match(/^release\/v(\d+)$/)
            const targetSpec = matchesRelease ? matchesRelease[1] : 'latest'
            core.info(`Target spec: ${targetSpec}`)

            const eventType = `"${eventName} ${owner}/${repo}#${pullRequest.number}"`
            core.info(`Event type: ${eventType}`)
          
            await github.rest.repos.createDispatchEvent({
              owner: 'npm',
              repo: 'benchmarks',
              event_type: eventType,
              client_payload: {
                owner,
                repo,
                pr_id: number,
                target_spec: targetSpec,
              },
            })
