name: CI

on:
  push:
    branches: [main]
  pull_request:
    branches: [main, 'next-major-release/**']

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

env:
  NX_CLOUD_DISTRIBUTED_EXECUTION: true
  NX_VERBOSE_LOGGING: false

jobs:
  create_nx_run_group:
    name: Create NX_RUN_GROUP
    runs-on: ubuntu-latest
    outputs:
      nx_run_group: ${{ steps.set_nx_run_group.outputs.nx_run_group }}
    steps:
      - name: Set NX_RUN_GROUP based on $GITHUB_RUN_ID and a uuid
        id: set_nx_run_group
        run: |
          NX_RUN_GROUP="$GITHUB_RUN_ID--$(uuidgen)"
          echo "::set-output name=nx_run_group::$NX_RUN_GROUP"

  primary:
    name: Primary
    needs: [create_nx_run_group]
    runs-on: ubuntu-latest
    steps:
      - name: Set NX_RUN_GROUP based on the output of the create_nx_run_group job
        run: echo "NX_RUN_GROUP=${{ needs.create_nx_run_group.outputs.nx_run_group }}" >> $GITHUB_ENV

      - uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - name: Derive appropriate SHAs for base and head for `nx affected` commands
        uses: nrwl/nx-set-shas@v2

      - name: Install node and npm based on the volta config in our package.json
        uses: volta-cli/action@v1

      - name: Get yarn cache directory path and node version for cache key and NX_CLOUD_ENV_NAME
        id: yarn-cache-dir-path
        run: |
          echo "::set-output name=dir::$(yarn cache dir)"
          echo "::set-output name=node_version::$(node --version)"

          # Added the - at the end to function as a separator to improve readability in the PR comment from the Nx cloud app
          echo "NX_CLOUD_ENV_NAME=Node $(node --version) -" >> $GITHUB_ENV

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

      - name: Install dependencies (skipping postinstall)
        # We use --ignore-scripts to skip automatic postinstall and give us more control over distributing build tasks
        run: |
          yarn --ignore-engines --frozen-lockfile --prefer-offline --ignore-scripts
          yarn check-clean-workspace-after-install

      - name: Check code formatting (not distributable)
        run: NX_CLOUD_DISTRIBUTED_EXECUTION=false yarn format-check

      - name: Run parallel distributed tasks for build, typecheck, check-rule-docs, lint and test targets
        uses: jameshenry/parallel-bash-commands@v1
        with:
          # Note that the typecheck target *also* typechecks tests and tools,
          # whereas the build only checks src files
          cmd1: yarn typecheck
          cmd2: yarn build
          cmd3: yarn check-rule-docs
          cmd4: yarn lint
          cmd5: yarn test --codeCoverage

      - name: Run distributed integration tests with independent local registries
        run: npx nx run-many --target=integration-test --all --withRegistry

      - name: Publish code coverage report
        uses: codecov/codecov-action@v3
        with:
          files: coverage/packages/**/lcov.info
          flags: unittest
          name: codecov

      - name: Stop all running agents for this CI run
        # It's important that we always run this step, otherwise in the case of any failures in preceding non-Nx steps, the agents will keep running and waste billable minutes
        if: ${{ always() }}
        run: npx nx-cloud stop-all-agents

  agents:
    name: Nx Distributed CI Agents
    needs: [create_nx_run_group]
    runs-on: ubuntu-latest
    timeout-minutes: 60
    strategy:
      matrix:
        agent: [1, 2, 3, 4, 5, 6]
    steps:
      - name: Set NX_RUN_GROUP based on the output of the create_nx_run_group job
        run: echo "NX_RUN_GROUP=${{ needs.create_nx_run_group.outputs.nx_run_group }}" >> $GITHUB_ENV

      - uses: actions/checkout@v3

      - name: Install node and npm based on the volta config in our package.json
        uses: volta-cli/action@v1

      - name: Get yarn cache directory path and node version for cache key
        id: yarn-cache-dir-path
        run: |
          echo "::set-output name=dir::$(yarn cache dir)"
          echo "::set-output name=node_version::$(node --version)"

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

      - name: Install dependencies (skipping postinstall)
        # We use --ignore-scripts to skip automatic postinstall and give us more control to distribute tasks
        run: yarn --ignore-engines --frozen-lockfile --prefer-offline --ignore-scripts

      - name: Start Nx Agent ${{ matrix.agent }}
        run: npx nx-cloud start-agent

  unit_tests_on_other_node_versions:
    name: Unit tests on other supported Node versions
    needs: [create_nx_run_group]
    runs-on: ubuntu-latest
    strategy:
      matrix:
        # Additionally supported node versions taken from:
        # https://gist.github.com/LayZeeDK/c822cc812f75bb07b7c55d07ba2719b3
        node: ['^14.15.5']
    steps:
      - name: Set NX_RUN_GROUP based on the output of the create_nx_run_group job
        run: echo "NX_RUN_GROUP=${{ needs.create_nx_run_group.outputs.nx_run_group }}" >> $GITHUB_ENV

      - uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - name: Derive appropriate SHAs for base and head for `nx affected` commands
        uses: nrwl/nx-set-shas@v2

      - uses: volta-cli/action@v1
        with:
          # The Node.js version to configure
          node-version: ${{ matrix.node }}

      - name: Get yarn cache directory path and node version for cache key and NX_CLOUD_ENV_NAME
        id: yarn-cache-dir-path
        run: |
          echo "::set-output name=dir::$(yarn cache dir)"
          echo "::set-output name=node_version::$(node --version)"

          # Added the - at the end to function as a separator to improve readability in the PR comment from the Nx cloud app
          # NOTE: We are intentionally not using matrix.node here because that does not contain the full semver value
          echo "NX_CLOUD_ENV_NAME=Node $(node --version) -" >> $GITHUB_ENV

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

      - name: Install dependencies (skipping postinstall)
        # We use --ignore-scripts to skip automatic postinstall and give us more control to distribute tasks
        run: yarn --ignore-engines --frozen-lockfile --prefer-offline --ignore-scripts

      - name: Run build targets on Node ${{ matrix.node }} (not distributable)
        env:
          # We cannot distribute these because the agents are set up to run the primary node version, not this alternative we are testing
          NX_CLOUD_DISTRIBUTED_EXECUTION: false
        run: yarn build

      - name: Run test targets on Node ${{ matrix.node }} (not distributable)
        env:
          # We cannot distribute these because the agents are set up to run the primary node version, not this alternative we are testing
          NX_CLOUD_DISTRIBUTED_EXECUTION: false
        run: yarn test

  publish_canary_version:
    name: Publish the latest code as a canary version
    runs-on: ubuntu-latest
    needs: [create_nx_run_group, primary, unit_tests_on_other_node_versions]
    if: github.ref == 'refs/heads/main'
    steps:
      - name: Set NX_RUN_GROUP based on the output of the create_nx_run_group job
        run: echo "NX_RUN_GROUP=${{ needs.create_nx_run_group.outputs.nx_run_group }}" >> $GITHUB_ENV

      - uses: actions/checkout@v3

      # Fetch all history for all tags and branches in this job because lerna needs it
      - run: git fetch --prune --unshallow

      - name: Install node and npm based on the volta config in our package.json
        uses: volta-cli/action@v1

      - name: Get yarn cache directory path and node version for cache key
        id: yarn-cache-dir-path
        run: |
          echo "::set-output name=dir::$(yarn cache dir)"
          echo "::set-output name=node_version::$(node --version)"

      - name: Apply version resolved by volta to standard Node action make authenticated npm publish easier
        uses: actions/setup-node@v3
        with:
          node-version: ${{ steps.yarn-cache-dir-path.outputs.node_version }}
          registry-url: https://registry.npmjs.org/

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

      - name: Install dependencies (skipping postinstall)
        # We use --ignore-scripts to skip automatic postinstall and give us more control to distribute tasks
        run: yarn --ignore-engines --frozen-lockfile --prefer-offline --ignore-scripts

      - name: Run build ahead of publishing
        # We cannot distribute this because the agents have already been stopped by this point
        # but it should not matter because this should be a full cloud cache hit
        run: NX_CLOUD_DISTRIBUTED_EXECUTION=false yarn build

      - name: Publish all packages to npm
        run: npx lerna publish --loglevel=verbose --canary --exact --force-publish --yes
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
