# This workflow runs on pull requests to ensure that the snapshots produced by
# the equivalence tests are consistent with the snapshots that are checked in.
#
# If there is an inconsistency, it is the responsibility of the committer to
# review it, ensure that any changes are intentional, and then commit the new
# snapshots.
name: Snapshots

on:
  pull_request:

permissions:
  contents: read

jobs:
  fileschanged:
    name: List files changed for pull request
    runs-on: ubuntu-latest
    steps:
      - name: "Fetch source code"
        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
      - id: diff
        env:
          BASE_REF: ${{ github.event.pull_request.base.ref }}
        run: |
          echo "Comparing to base_ref $BASE_REF"
          git fetch --no-tags --prune --no-recurse-submodules --depth=1 origin "$BASE_REF"
          echo "go=$(git diff --name-only origin/"$BASE_REF" | grep '\.go' | wc -l)" | tee -a "$GITHUB_OUTPUT"
    outputs:
      go: ${{ steps.diff.outputs.go }}

  compare:
    name: Compare
    runs-on: ubuntu-latest
    needs: fileschanged
    if: ${{ needs.fileschanged.outputs.go != 0}}

    steps:
      - name: Checkout
        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2

      - name: Set up Go
        uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0
        with:
          go-version-file: 'go.mod'

      - name: Get the equivalence test binary
        run: |
          ./.github/scripts/equivalence-test.sh download_equivalence_test_binary \
            0.4.0 \
            ./bin/equivalence-testing \
            linux \
            amd64

      - name: Build the OpenTofu binary
        run: |
          go build -o ./bin/tofu ./cmd/tofu

      - name: Run the equivalence tests
        run: |
          ./bin/equivalence-testing update \
            --tests=testing/equivalence-tests/tests \
            --goldens=testing/equivalence-tests/outputs \
            --rewrites=testing/rewrites.jsonc \
            --binary=./bin/tofu \

      - name: Ensure there is no diff
        shell: bash
        run: |
          changed=$(git diff --quiet -- testing/equivalence-tests/outputs || echo true)
          if [[ "$changed" == "true" ]]; then
            echo "Found changes, please commit the new golden files."
            git diff -- testing/equivalence-tests/outputs
            exit 1
          else
            echo "Found no changes."
          fi
