name: Release

on:
  push:
    branches: [master, 1.x]

jobs:
  build-and-test:
    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [12.x, 14.x, 16.x]

    steps:
      - uses: actions/checkout@v2
        with:
          fetch-depth: 0
      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v1
        with:
          node-version: ${{ matrix.node-version }}
      - name: Install dependencies
        run: npm ci
      - name: Check commit messages
        run: npx commitlint --from origin/master
      - name: Check linting
        run: npm run lint
      - name: Build the project
        run: npm run build --if-present
      - name: Run the tests
        run: npm run test

  release:
    runs-on: ubuntu-latest
    needs: build-and-test
    steps:
      - name: Checkout
        uses: actions/checkout@v2
        with:
          fetch-depth: 0
          persist-credentials: false
      - name: Install
        run: npm ci
      - name: Set project name
        run: echo "SEMANTIC_RELEASE_PACKAGE=$(jq -r '.name' package.json)" >> $GITHUB_ENV
      - name: Get release version if there is one
        run: echo "RELEASE_VERSION=$(npx semantic-release --dry-run | grep -oE 'Published release [0-9\.]+ on \w+ channel' | grep -oE '[0-9\.]+')" >> $GITHUB_ENV
        env:
          GH_TOKEN: ${{ secrets.GH_TOKEN }}
          NPM_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          SLACK_WEBHOOK: ${{ secrets.SLACK_SEMANTIC_RELEASE_WEBHOOK }}
          NPM_CONFIG_REGISTRY: https://npm.pkg.github.com
      - name: Release to github registry
        run: npx semantic-release
        env:
          GH_TOKEN: ${{ secrets.GH_TOKEN }}
          NPM_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          SLACK_WEBHOOK: ${{ secrets.SLACK_SEMANTIC_RELEASE_WEBHOOK }}
          NPM_CONFIG_REGISTRY: https://npm.pkg.github.com
      - name: Set npm registry to npm
        run: npm config set @avallone-io:registry https://registry.npmjs.org
      - name: Npm registry authentication
        run: npm set //registry.npmjs.org/:_authToken ${{ secrets.NPM_TOKEN }}
      - name: Release to NPM
        if: ${{ env.RELEASE_VERSION != '' }}
        run: npm publish --access public
