name: Run Tests

on:
  push:
    branches:
      - master
  pull_request:
    branches:
      - master
  workflow_dispatch:

permissions:
  contents: read #  to fetch code (actions/checkout)

env:
  # run coverage and benchmarks only with the latest Go version
  LATEST_GO_VERSION: "1.23"

jobs:
  test:
    strategy:
      matrix:
        os: [ubuntu-latest, macos-latest, windows-latest]
        # Each major Go release is supported until there are two newer major releases. https://golang.org/doc/devel/release.html#policy
        # Echo tests with last four major releases (unless there are pressing vulnerabilities)
        # As we depend on `golang.org/x/` libraries which only support last 2 Go releases we could have situations when
        # we derive from last four major releases promise.
        go: ["1.20", "1.21", "1.22", "1.23"]
    name: ${{ matrix.os }} @ Go ${{ matrix.go }}
    runs-on: ${{ matrix.os }}
    steps:
      - name: Checkout Code
        uses: actions/checkout@v4

      - name: Set up Go ${{ matrix.go }}
        uses: actions/setup-go@v5
        with:
          go-version: ${{ matrix.go }}

      - name: Run Tests
        run: go test -race --coverprofile=coverage.coverprofile --covermode=atomic ./...

      - name: Upload coverage to Codecov
        if: success() && matrix.go == env.LATEST_GO_VERSION && matrix.os == 'ubuntu-latest'
        uses: codecov/codecov-action@v3
        with:
          token:
          fail_ci_if_error: false

  benchmark:
    needs: test
    name: Benchmark comparison
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Code (Previous)
        uses: actions/checkout@v4
        with:
          ref: ${{ github.base_ref }}
          path: previous

      - name: Checkout Code (New)
        uses: actions/checkout@v4
        with:
          path: new

      - name: Set up Go ${{ matrix.go }}
        uses: actions/setup-go@v5
        with:
          go-version: ${{ env.LATEST_GO_VERSION }}

      - name: Install Dependencies
        run: go install golang.org/x/perf/cmd/benchstat@latest

      - name: Run Benchmark (Previous)
        run: |
          cd previous
          go test -run="-" -bench=".*" -count=8 ./... > benchmark.txt

      - name: Run Benchmark (New)
        run: |
          cd new
          go test -run="-" -bench=".*" -count=8 ./... > benchmark.txt

      - name: Run Benchstat
        run: |
          benchstat previous/benchmark.txt new/benchmark.txt
