name: Turborepo Compare Cache Item

on:
  workflow_dispatch:
    inputs:
      version:
        description: Turborepo release to test.
        type: string
        default: "canary"

jobs:
  generate_cache_artifact:
    strategy:
      matrix:
        os: [macos-latest, ubuntu-latest, windows-latest]
    runs-on: ${{ matrix.os }}

    steps:
      - name: Setup Node
        uses: ./.github/actions/setup-node

      - name: create-turbo
        run: |
          npm install -g pnpm turbo@${{ inputs.version }}
          pnpm dlx create-turbo@${{ inputs.version }} my-turborepo pnpm

      - name: Run build
        run: |
          cd my-turborepo
          turbo run build --filter=docs --filter=web --summarize --skip-infer -vvv

      - name: Grab Turborepo artifacts
        uses: actions/upload-artifact@v4
        with:
          name: cache-item-${{ matrix.os }}-${{ inputs.version }}
          path: |
            my-turborepo/node_modules/.cache/turbo
            my-turborepo/.turbo/runs
          retention-days: 1

  use_cache_artifact:
    needs: generate_cache_artifact
    strategy:
      fail-fast: false
      matrix:
        os: [macos-latest, ubuntu-latest, windows-latest]
        cache_os: [macos-latest, ubuntu-latest, windows-latest]
    runs-on: ${{ matrix.os }}

    steps:
      - name: Setup Node
        uses: ./.github/actions/setup-node

      - name: create-turbo
        run: |
          npm install -g pnpm turbo@${{ inputs.version }}
          pnpm dlx create-turbo@${{ inputs.version }} my-turborepo pnpm

      - name: Download cache artifacts
        uses: actions/download-artifact@v4
        with:
          name: cache-item-${{ matrix.cache_os }}-${{ inputs.version }}
          path: my-turborepo

      - name: Check for cache hit
        run: |
          cd my-turborepo
          rm .turbo/runs/*.json
          turbo run build --filter=docs --filter=web --summarize --skip-infer -vvv
          cat .turbo/runs/*.json | jq -e '.execution.cached == 2'

      - name: Check for functional server
        run: |
          curl https://raw.githubusercontent.com/vercel/turbo/main/scripts/server.js -O
          node server.js my-turborepo/apps/docs
