# check for uneeded header includes of modified files
# False positives can be avoided with
# #include "some_include.h"  // IWYU pragma: keep

name: IWYU Check

on:
  pull_request:
    branches: [ main ]
    paths:
      - '**.cpp'
      - '**.hpp'
      - '**.c'
      - '**.h'

jobs:
  iwyu-check:
    name: Include What You Use Check
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
        with:
          fetch-depth: 0

      - name: Install IWYU
        run: |
          sudo apt-get update
          sudo apt-get install -y iwyu

      - name: Get changed files
        id: changed-files
        run: |
          git fetch origin ${{ github.base_ref }}
          base_commit=$(git merge-base FETCH_HEAD ${{ github.event.pull_request.head.sha }})
          changed_files=$(git diff --name-only $base_commit HEAD | grep -E '\.(cpp|hpp|c|h)$' || true)
          echo "files=$changed_files" >> $GITHUB_OUTPUT

      - name: Run IWYU checks on changed files
        if: steps.changed-files.outputs.files != ''
        run: |
          echo "${{ steps.changed-files.outputs.files }}" | while read -r file; do
            if [ -f "$file" ]; then
              echo "Checking $file..."
              iwyu -Xiwyu --mapping_file=iwyu.imp "$file" 2>&1 || true
            fi
          done | tee iwyu_output.txt
          if grep -q "should add these lines:" iwyu_output.txt || \
             grep -q "should remove these lines:" iwyu_output.txt; then
            echo "IWYU checks failed. Please fix the includes in the affected files."
            exit 1
          fi
