name: '/canary-release'
on:
  issue_comment:
    types: [ created ]

permissions:
  contents: read # for checkout
  pull-requests: write  # for comments
  packages: write # for publish

jobs:
  canary-release:
    name: canary-release
    runs-on: ubuntu-latest
    if: |
      github.event_name == 'issue_comment' &&
      (github.event.comment.author_association == 'MEMBER' || github.event.comment.author_association == 'OWNER' || github.event.comment.author_association == 'CONTRIBUTOR') &&
      startsWith(github.event.comment.body, '/canary-release')
    steps:
      - name: get pr information
        uses: actions/github-script@v4
        id: pr
        with:
          script: |
            const request = {
              owner: context.repo.owner,
              repo: context.repo.repo,
              pull_number: context.issue.number
            }
            core.info(`Getting PR #${request.pull_number} from ${request.owner}/${request.repo}`)
            try {
              const result = await github.pulls.get(request)
              core.info(`Got PR: ${JSON.stringify(result.data)}`)
              return result.data
            } catch (err) {
              core.setFailed(`Request failed with error ${err}`)
            }
      - name: checkout
        uses: actions/checkout@v2
        with:
          ref: ${{ fromJSON(steps.pr.outputs.result).head.ref }}
          repository: ${{ fromJSON(steps.pr.outputs.result).head.repo.full_name }}
          fetch-depth: 0
      - name: setup Node
        uses: actions/setup-node@v2
        with:
          node-version: 16.x
          registry-url: 'https://registry.npmjs.org'
      - name: install
        run: yarn
      - name: Publish
        run: yarn run release:canary
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          NODE_AUTH_TOKEN: ${{ secrets.TOKEN }}
      - uses: actions/github-script@v4
        with:
          github-token: ${{secrets.GITHUB_TOKEN}}
          script: |
            github.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: '🎉 Canary Release. You can install canary version via `npm install package@next`'
            })
