name: Publish Action

on:
  push:
    branches:
      - master
      - next
      - alpha
      - beta
      # N.x (maintenance release branches)
      - '[0-9]+.x'

jobs:
  build:
    name: Release
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest]
        node-version: [14.x]
    steps:
      - name: Checkout Code
        uses: actions/checkout@v2.3.4

      - name: Use Node.js ${{ matrix.node-version }} on ${{ matrix.os }}
        uses: actions/setup-node@v2.4.0
        with:
          node-version: ${{ matrix.node-version }}

      - name: Configure Package Manager
        run: |
          echo Configuring NPM_READ_TOKEN globally for .npmrc
          npm config set '//registry.npmjs.org/:_authToken' ${{ secrets.NPM_PUBLISH_TOKEN }}
          npm whoami

      - name: Get yarn cache directory path
        id: yarn-cache-dir-path
        run: echo "::set-output name=dir::$(yarn cache dir)"

      - uses: actions/cache@v2.1.6
        # Use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
        id: yarn-cache
        with:
          path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
          key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
          restore-keys: |
            ${{ runner.os }}-yarn-

      - name: Install Dependencies
        run: yarn install --frozen-lockfile

      - name: Lint
        run: yarn lint

      - name: Test
        run: yarn test --coverage --silent

      - uses: codecov/codecov-action@v2.0.2
        with:
          fail_ci_if_error: true

      - name: Semantic Release
        uses: cycjimmy/semantic-release-action@v2
        id: semantic
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}

      - name: Push updates to branch for major version
        # If a new version is published, i.e. v1.2.3 then this step will update
        # branch "v1" to this commit.
        # https://github.com/reside-eng/workflow-status-slack-notification/branches
        if: steps.semantic.outputs.new_release_published == 'true'
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          git push https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git HEAD:refs/heads/v${{steps.semantic.outputs.new_release_major_version}}
