name: ecosystem-ci trigger

on:
  issue_comment:
    types: [created]

concurrency:
  group: ${{ github.workflow }}-${{ github.event.issue.number }}
  cancel-in-progress: true

permissions: {}

jobs:
  trigger:
    runs-on: ubuntu-latest
    name: Run Ecosystem CI Tests
    if: github.repository == 'vitest-dev/vitest' && github.event.issue.pull_request && startsWith(github.event.comment.body, '/ecosystem-ci run')
    permissions:
      issues: write # to add / delete reactions, post comments
      pull-requests: write # to read PR data, and to add labels
      actions: read # to check workflow status
      contents: read # to clone the repo
    steps:
      - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
        with:
          script: |
            const user = context.payload.sender.login
            console.log(`Validate user: ${user}`)

            let hasTriagePermission = false
            try {
              const { data } = await github.rest.repos.getCollaboratorPermissionLevel({
                owner: context.repo.owner,
                repo: context.repo.repo,
                username: user,
              });
              hasTriagePermission = data.user.permissions.triage
            } catch (e) {
              console.warn(e)
            }

            if (hasTriagePermission) {
              console.log('Allowed')
              await github.rest.reactions.createForIssueComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                comment_id: context.payload.comment.id,
                content: '+1',
              })
            } else {
              console.log('Not allowed')
              await github.rest.reactions.createForIssueComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                comment_id: context.payload.comment.id,
                content: '-1',
              })
              throw new Error('not allowed')
            }
      - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
        id: get-pr-data
        with:
          script: |
            console.log(`Get PR info: ${context.repo.owner}/${context.repo.repo}#${context.issue.number}`)
            const { data: pr } = await github.rest.pulls.get({
              owner: context.repo.owner,
              repo: context.repo.repo,
              pull_number: context.issue.number
            })
            return {
              num: context.issue.number,
              branchName: pr.head.ref,
              repo: pr.head.repo.full_name
            }
      - id: generate-token
        uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
        with:
          app-id: ${{ secrets.ECOSYSTEM_CI_GITHUB_APP_ID }}
          private-key: ${{ secrets.ECOSYSTEM_CI_GITHUB_APP_PRIVATE_KEY }}
          repositories: |
            vitest
            vitest-ecosystem-ci
          permission-actions: write
      - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
        id: trigger
        env:
          COMMENT: ${{ github.event.comment.body }}
          PR_DATA: ${{ steps.get-pr-data.outputs.result }}
        with:
          github-token: ${{ steps.generate-token.outputs.token }}
          result-encoding: string
          script: |
            const comment = process.env.COMMENT.trim()
            const prData = JSON.parse(process.env.PR_DATA)

            const suite = comment.split('\n')[0].replace(/^\/ecosystem-ci run/, '').trim()

            await github.rest.actions.createWorkflowDispatch({
              owner: context.repo.owner,
              repo: 'vitest-ecosystem-ci',
              workflow_id: 'ecosystem-ci-from-pr.yml',
              ref: 'main',
              inputs: {
                prNumber: '' + prData.num,
                branchName: prData.branchName,
                repo: prData.repo,
                suite: suite === '' ? '-' : suite
              }
            })
