# This action runs lint checks and tests against the code.
name: Check and Test

# Controls when the action will run.
on:
  pull_request:

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:
  push:
    branches:
      - main

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
  check-and-test:
    name: Check and Test

    timeout-minutes: 45

    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest, macos-latest]

      fail-fast: false

    # The type of runner that the job will run on
    runs-on: ${{ matrix.os }}

    # Steps represent a sequence of tasks that will be executed as part of the job
    steps:
      - name: Sets env vars
        if: github.event_name == 'pull_request'
        run: echo "SINCE_REF=remotes/origin/main" >> $GITHUB_ENV

      # On main we run all the checks with changes since the last commit
      - name: Sets env vars (main)
        if: github.event_name != 'pull_request'
        run: echo "SINCE_REF=HEAD~1" >> $GITHUB_ENV

      - name: Install Deps Ubuntu
        if: ${{ runner.os == 'Linux' }}
        run: sudo apt-get -y install libkrb5-dev libsecret-1-dev net-tools libstdc++6 gnome-keyring

      # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
      - name: Checkout
        uses: actions/checkout@v2
        with:
          fetch-depth: 0

      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: 18.x
          cache: 'npm'

      - name: Install npm
        run: npm install -g npm@8

      - name: Install Dependencies
        run: |
          # Dependencies are included when installing as npm workspaces will
          # hoist every package in the repo and it's important that the
          # dependencies of packages we are planning to test are also prepared
          npm ci
          npm run bootstrap-ci -- --scope @mongodb-js/monorepo-tools --stream --include-dependencies
          npm run bootstrap-ci -- --stream --since ${SINCE_REF} --include-dependencies
        shell: bash

      - name: Info
        run: |
          LERNA_VERSION=$(npm ls lerna --json | jq -r .dependencies.lerna.version)
          echo "Packages changed since: ${SINCE_REF}"
          npx lerna@${LERNA_VERSION} ls --all --since ${SINCE_REF}
        shell: bash

      - name: Run Checks
        # We exclude dependents when running eslint and depchecks because
        # linting and dependency checking is relevant only for packages where
        # the source code was changed
        run: npm run check-ci -- --stream --since ${SINCE_REF} --exclude-dependents
        shell: bash

      - name: Run Tests
        run: npm run test-ci -- --stream --since ${SINCE_REF}
        shell: bash
