name: Commit hygiene

on:
  pull_request:
    types: [opened, edited, synchronize, reopened]

permissions:
  contents: read
  pull-requests: read

jobs:
  check:
    name: Title, body, branch and commits
    if: >-
      github.event.pull_request.user.login != 'dependabot[bot]' &&
      github.event.pull_request.user.login != 'github-actions[bot]'
    runs-on: ubuntu-latest
    steps:
      # Untrusted text reaches the shell only through environment variables.
      - name: Check the PR title, body, branch name and commit messages
        env:
          GH_TOKEN: ${{ github.token }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
          PR_TITLE: ${{ github.event.pull_request.title }}
          PR_BODY: ${{ github.event.pull_request.body }}
          PR_BRANCH: ${{ github.head_ref }}
        run: |
          set -euo pipefail
          trailer='(?i)^(Co-authored-by|Signed-off-by|Claude-Session|Generated-by|Assisted-by|Reviewed-by):'
          # Standard identifiers such as CVE-2024-1234, SHA-256, UTF-8, ISO-8601, PEP-8, RFC-9110 and HTTP-2 are not tracker keys.
          tracker='\b(?!(?:CVE|GHSA|SHA|UTF|ISO|PEP|RFC|HTTP)-)[A-Z]{2,10}-[0-9]+\b'
          # Attribution phrases only: product names such as Claude or OpenAI stay allowed.
          attribution='(?i)(\bgenerated (with|by) (claude|chatgpt|copilot|openai|gemini|an? ai)\b|\bai-generated\b|noreply@anthropic\.com)'
          conventional='^((fix|feat|perf)\([a-z][a-z0-9-]*\)|(build|chore|ci|docs|refactor|revert|style|test)(\([a-z][a-z0-9-]*\))?)!?: \S'
          failed=0

          # Every printed line starts with a label, so text from the PR cannot start a workflow command.
          check() { # $1: where, $2: pattern, $3: rule; the text is on stdin
            local hits
            if hits=$(grep -nP -- "$2" | sed 's/^/  line /'); then
              echo "$1 has $3:"
              echo "$hits"
              failed=1
            fi
          }
          scan() { # $1: where; the text is on stdin
            local text
            text=$(cat)
            check "$1" "$trailer" "a trailer line" <<<"$text"
            check "$1" "$tracker" "an issue tracker key" <<<"$text"
            check "$1" "$attribution" "an AI attribution" <<<"$text"
          }

          if ! grep -qP -- "$conventional" <<<"$PR_TITLE"; then
            echo "PR title is not a Conventional Commit: type(scope)!: subject, with type one of build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test. fix, feat and perf need a lowercase scope, for example fix(crawl): subject."
            failed=1
          fi
          scan "PR title" <<<"$PR_TITLE"
          scan "PR body" <<<"$PR_BODY"
          scan "Branch name" <<<"$PR_BRANCH"
          # Read the commits first, so a failed API call fails the check instead of scanning nothing.
          commits=$(gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER/commits" \
            --jq '.[] | "\(.sha[0:12]) \(.commit.message | @base64)"')
          [ -n "$commits" ] || { echo "::error::The PR has no commits to check."; exit 1; }
          while read -r sha message; do
            scan "Commit $sha" < <(base64 -d <<<"$message")
          done <<<"$commits"

          if [ "$failed" -ne 0 ]; then
            echo "::error::Fix the PR title, body, branch name or commit messages listed above."
            exit 1
          fi
          echo "The PR title, body, branch name and commit messages are clean."
