name: Style

permissions:
  contents: read

on:
  push:
    branches:
      - 'main'
      - '*-stable'
    tags:
      - '!*' # Do not execute on tags
  pull_request:
    branches:
      - '*'
  # Allow manually triggering the workflow.
  workflow_dispatch:

# Cancels all previous workflow runs for the same branch that have not yet completed.
concurrency:
  # The concurrency group contains the workflow name and the branch name.
  group: "${{ github.workflow }}-${{ github.ref }}"
  cancel-in-progress: true

jobs:
  rubocop:
    if: "!contains(github.event.commits[0].message, '[ci skip]') && !contains(github.event.commits[0].message, '[skip ci]')"
    name: Style on ${{ matrix.ruby }}@current
    runs-on: ubuntu-latest
    env: # $BUNDLE_GEMFILE must be set at job level, so it is set for all steps
      BUNDLE_GEMFILE: ${{ github.workspace }}/Appraisal.root.gemfile
    strategy:
      fail-fast: false
      matrix:
        include:
          # Style
          - ruby: "ruby"
            appraisal: "style"
            exec_cmd: "rake rubocop_gradual:check"
            rubygems: latest
            bundler: latest

    steps:
      - name: Checkout
        uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
        with:
          persist-credentials: false

      - name: Setup Ruby & RubyGems
        uses: ruby/setup-ruby@d45b1a4e94b71acab930e56e79c6aa188764e7f9 # v1.316.0
        with:
          ruby-version: ${{ matrix.ruby }}
          rubygems: ${{ matrix.rubygems }}
          bundler: ${{ matrix.bundler }}
          bundler-cache: true

      - name: "[Attempt 1] Appraisal for ${{ matrix.ruby }}@${{ matrix.appraisal }}"
        id: bundleAppraisalAttempt1
        run: bundle exec appraisal ${{ matrix.appraisal }} install
        # Continue to the next step on failure
        continue-on-error: true

      # Effectively an automatic retry of the previous step.
      - name: "[Attempt 2] Appraisal for ${{ matrix.ruby }}@${{ matrix.appraisal }}"
        id: bundleAppraisalAttempt2
        # If bundleAppraisalAttempt1 failed, try again here; Otherwise skip.
        if: ${{ steps.bundleAppraisalAttempt1.outcome == 'failure' }}
        run: bundle exec appraisal ${{ matrix.appraisal }} install

      - name: Run ${{ matrix.appraisal }} checks via ${{ matrix.exec_cmd }}
        run: bundle exec appraisal ${{ matrix.appraisal }} bundle exec ${{ matrix.exec_cmd }}

      - name: Validate RBS Environment
        run: >-
          bundle exec appraisal ${{ matrix.appraisal }} bundle exec ruby -rrbs -rpathname -e
          'loader = RBS::EnvironmentLoader.new; loader.add(path: Pathname("sig")); RBS::Environment.from_loader(loader).resolve_type_names'
