name: Go mod tidy check

on:
  workflow_dispatch:
  push:
    branches:
      - main
      - "release/**"
    paths:
      - "**.go"
      - "**/go.mod"
      - "**/go.sum"
  pull_request:
    paths:
      - "**.go"
      - "**/go.mod"
      - "**/go.sum"

jobs:
  gotidycheck:
    name: Go mod tidy check
    runs-on: ubuntu-22.04
    steps:
      - name: Checkout
        uses: actions/checkout@755da8c3cf115ac066823e79a1e1788f8940201b # v3.2.0
        with:
          ref: ${{ !github.event.pull_request.head.repo.fork && github.head_ref || '' }}
          # No token available for forks, so we can't push changes
          token: ${{ !github.event.pull_request.head.repo.fork && secrets.TIDY_RENOVATE_PUSH || '' }}

      - name: Setup Go environment
        uses: actions/setup-go@6edd4406fa81c3da01a34fa6f6343087c207a568 # v3.5.0
        with:
          go-version: "1.19.4"

      - name: Get Go submodules
        id: submods
        shell: bash
        run: |
          mods=$(go list -f '{{.Dir}}' -m | xargs)
          echo "Found mods: $mods"
          echo "submods=${mods}" >> "$GITHUB_OUTPUT"

      - name: Go tidy check
        id: tidycheck
        uses: katexochen/go-tidy-check@45731e0013a976d5d616d79007c7ba52de6ce542 # tag=v1.0.2
        with:
          modules: ${{ steps.submods.outputs.submods }}

      # The following steps are only executed if the previous tidy check failed
      # and the action runs on an renovat branche. In this case, we tidy all
      # modules again and commit the changes, so the user doesn't need to do it.

      - name: Tidy modules on renovate branches
        if: |
          failure() &&
          (steps.tidycheck.conclusion == 'failure') &&
          startsWith(github.head_ref, 'renovate/') &&
          !github.event.pull_request.head.repo.fork
        shell: bash
        run: |
          mods="${{ steps.submods.outputs.submods }}"
          for mod in $mods; do
            (cd $mod; go mod tidy)
          done

      - name: Push changes
        if: |
          failure() &&
          (steps.tidycheck.conclusion == 'failure') &&
          startsWith(github.head_ref, 'renovate/') &&
          !github.event.pull_request.head.repo.fork
        shell: bash
        run: |
          git config --global user.name "renovate[bot]"
          git config --global user.email "29139614+renovate[bot]@users.noreply.github.com"
          git commit -am "[bot] Tidy all modules"
          git push
