name: Checkpatch

on:
  pull_request:
    types: [opened, synchronize, reopened]
    branches:
      - master

jobs:
  checkpatch:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
      with:
        fetch-depth: 0
    - name: Install dependencies
      run: |
        sudo apt-get update
        sudo apt-get install -y perl
    - name: Run checkpatch.pl
      run: |
        if [ -z "${{ github.base_ref }}" ]; then
          echo "Not a pull request, skipping checkpatch"
          exit 0
        fi
        git fetch origin ${{ github.base_ref }}
        base_commit=$(git merge-base origin/${{ github.base_ref }} HEAD)
        echo "Base commit: $base_commit"
        echo "Running checkpatch.pl on all commits in the PR:"
        git rev-list --reverse $base_commit..HEAD | while read commit; do
          # Skip dependabot commits - we do not have control over it
          if git log -1 --format='%ae' $commit | grep -q "dependabot"; then
            echo "Skipping dependabot commit: $commit"
            continue
          fi
          subject=$(git log -1 --format=%s $commit)
          echo "Checking commit: $commit - $subject"
          if !  .github/workflows/run-checkpatch.sh $commit; then
            echo "checkpatch.pl found issues in commit $commit - $subject"
            exit 1
          fi
        done
