name: Go
on:
  push:
    branches:
      - main
  pull_request: {}

jobs:
  build-test:

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

    steps:
      - uses: actions/checkout@v2

      - uses: actions/setup-go@v4
        with:
          go-version: 1.x

      - run: go build -gcflags="-m" ./...

      - run: go test -v -race ./...

  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2

      - uses: actions/setup-go@v4
        with:
          go-version: 1.x

      - uses: dominikh/staticcheck-action@29e9b80fb8de0521ba4ed3fdf68fed5bbe82a2d2 # v1.1.0
        with:
          install-go: false

  vet:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2

      - uses: actions/setup-go@v4
        with:
          go-version: 1.x

      - run: go vet ./...

  fmt:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2

      - uses: actions/setup-go@v4
        with:
          go-version: 1.x

      - name: Run gofmt -d .
        run: |
            fmtvar="$(gofmt -d .)"
            echo "$fmtvar"
            test -z "$fmtvar"

  modtidy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2

      - uses: actions/setup-go@v4
        with:
          go-version: 1.x

      - name: Run go mod tidy
        run: |
            go mod tidy
            gitdiff="$(git diff -U0)"
            echo "$gitdiff"
            test -z "$gitdiff"

  vendor-diff:
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    steps:
    - uses: actions/setup-go@v4
      with:
        go-version: 1.x

    - name: Checkout base commit
      uses: actions/checkout@v3
      with:
        path: a
        ref: ${{ github.base_ref }}
    - name: Download dependencies of base commit
      run: go mod vendor
      working-directory: a

    - name: Checkout PR
      uses: actions/checkout@v3
      with:
        path: b
    - name: Download dependencies of PR
      run: go mod vendor
      working-directory: b

    - name: Diff of dependencies
      run: diff -ur --color=always a/vendor b/vendor || true
