# Decision #8 (override): auto-merge runtime CVE patches alongside dev/actions. See GIT_FLOW.md.
name: Dependabot auto-merge

on:
  pull_request_target:
    branches: [main]
    types: [opened, synchronize, reopened, ready_for_review]

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

# Read-only by default, so no workflow-level write exists to be inherited by a
# step that never needed one. The merge job grants itself what it needs below.
# OpenSSF Scorecard zeroes Token-Permissions on any workflow-level write; a
# job-level grant does not.
permissions:
  contents: read

jobs:
  automerge:
    runs-on: ubuntu-latest
    if: ${{ github.actor == 'dependabot[bot]' }}
    # `gh pr merge --auto` writes the merge and the PR state; nothing else here
    # writes anything.
    permissions:
      contents: write
      pull-requests: write
    steps:
      - name: Fetch Dependabot metadata
        id: meta
        uses: dependabot/fetch-metadata@25dd0e34f4fe68f24cc83900b1fe3fe149efef98 # v3
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}

      - name: Auto-merge eligible patches
        env:
          PR_URL: ${{ github.event.pull_request.html_url }}
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          UPDATE_TYPE: ${{ steps.meta.outputs.update-type }}
          DEP_TYPE: ${{ steps.meta.outputs.dependency-type }}
          ALERT_STATE: ${{ steps.meta.outputs.alert-state }}
          ECOSYSTEM: ${{ steps.meta.outputs.package-ecosystem }}
        run: |
          if [ "$UPDATE_TYPE" != "version-update:semver-patch" ]; then
            echo "Not a patch update ($UPDATE_TYPE). Skipping auto-merge."
            exit 0
          fi

          if [ "$DEP_TYPE" = "direct:development" ]; then
            echo "Dev dependency patch. Enabling auto-merge."
            gh pr merge --auto --squash "$PR_URL"
            exit 0
          fi

          # fetch-metadata reports the ecosystem with Dependabot's internal
          # spelling (`github_actions`), not the hyphenated one from
          # dependabot.yml. Comparing against the hyphen alone matched nothing,
          # so every Actions patch fell through to the no-rule-matched branch
          # and waited for a human. Normalize instead of picking one spelling.
          if [ "${ECOSYSTEM//_/-}" = "github-actions" ]; then
            echo "GitHub Actions patch. Enabling auto-merge."
            gh pr merge --auto --squash "$PR_URL"
            exit 0
          fi

          if [ "$ALERT_STATE" = "open" ]; then
            echo "Runtime CVE patch (alert-state=open). Enabling auto-merge."
            gh pr merge --auto --squash "$PR_URL"
            exit 0
          fi

          echo "Patch update but no auto-merge rule matched (dep-type=$DEP_TYPE, ecosystem=$ECOSYSTEM, alert-state=$ALERT_STATE). Skipping."
