name: benchmark
on:
  push:
    tags:
      - v*
    branches:
      - main
  pull_request:
env:
  GO111MODULE: "on"
  GOPROXY: https://proxy.golang.org

permissions:
  # none-all, which doesn't exist, but
  # https://docs.github.com/en/actions/reference/authentication-in-a-workflow#using-the-github_token-in-a-workflow
  # implies that the token still gets created.  Elsewhere we learn that any
  # permission not mentioned here gets turned to `none`.
  actions: none

jobs:
  benchmark:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/setup-go@v2
        with:
          go-version: '^1.x'
      - uses: actions/checkout@v2
      - uses: actions/cache@v2.1.6
        id: cache
        with:
          path: |
            ~/go/pkg/mod              # Module download cache
            ~/.cache/go-build         # Build cache (Linux)
            ~/Library/Caches/go-build # Build cache (Mac)
            '%LocalAppData%\go-build' # Build cache (Windows)
          key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
          restore-keys: |
            ${{ runner.os }}-go-
      - name: install deps
        if: steps.cache.output.cache-hit != 'true'
        run: make --debug install_deps
      - name: restore base benchmark result
        uses: actions/cache@v2.1.6
        with:
          path: |
            test-results/benchmark-results-main.txt
          # Use base sha for PR, or new commit hash when in a push on main, in benchmark result key.
          key: ${{ runner.os }}-bench-${{ (github.event.pull_request.base.sha != github.event.after) && github.event.pull_request.base.sha || github.event.after }}
      - name: run benchmark
        run: |
          # If on a pull_request(_target) then GITHUB_HEAD_REF else strip all
          # but last part of GITHUB_REF (i.e. on a push to branch)
          BENCH_COUNT=5 HEAD_REF=${GITHUB_HEAD_REF:-${GITHUB_REF##*/}} make --debug benchstat
          ls -al test-results
          mkdir -p benchmark-comment
          cp test-results/benchstat.txt benchmark-comment
          echo ${{ github.event.number }} > benchmark-comment/pr-number
      - uses: actions/upload-artifact@v2
        if: always ()
        with:
          name: benchmark-comment
          path: benchmark-comment/
