# From https://github.com/anatawa12/AvatarOptimizer/blob/ccb863243433019f323c23a3a2e24b27e15b2f6c/.github/workflows/changelog-check.yml
# Copyright 2022 anatawa12
# MIT license.

# this workflow checks CHANGELOG.md & CHANGELOG-SNAPSHOTS.md is updated correctly
# to skip this check, include `NO-CHANGELOG` for CHANGELOG.md
# and `NO-CHANGELOG-PRERELEASE` for CHANGELOG-PRERELEASE.md in tags of PR.
# also, this action ignores `dependencies` pull requests (expected to be generated by dependabot)

name: CHANGELOG check

on:
  pull_request_target:
    branches: [ main, main-* ]
    types: [ opened, synchronize, reopened, ready_for_review, labeled, unlabeled ]

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
  releasenote-check:
    if: ${{ ! github.event.pull_request.draft }}
    runs-on: ubuntu-latest
    
    strategy:
      matrix:
        file: [CHANGELOG.md, CHANGELOG-jp.md, CHANGELOG-PRERELEASE.md, CHANGELOG-PRERELEASE-jp.md]

    env:
      NO_CHANGELOG: ${{
        contains(github.event.pull_request.labels.*.name, 'NO-CHANGELOG')
        || contains(github.event.pull_request.labels.*.name, 'documentation')
        || contains(github.event.pull_request.labels.*.name, 'localization')
        || contains(github.event.pull_request.labels.*.name, 'ci')
        || contains(github.event.pull_request.labels.*.name, 'refactor')
        || startsWith(github.event.pull_request.head.label, 'bdunderscore:dependabot/')
        || '' }}
      SNAPSHOT_ONLY: ${{ contains(github.event.pull_request.labels.*.name, 'PRERELEASE-ONLY') || '' }}
    # Steps represent a sequence of tasks that will be executed as part of the job
    steps:
      - name: Dump GitHub context
        env:
          GITHUB_CONTEXT: ${{ toJson(github) }}
        run: echo "$GITHUB_CONTEXT"
      - name: Fetch pull_request info
        env:
          GH_REPO: ${{ github.repositoryUrl }}
          GH_TOKEN: ${{secrets.GITHUB_TOKEN}}
          PR_NUM: ${{ github.event.number }}
        run: |
          gh pr view $PR_NUM --json=files | jq --raw-output '.files[].path' > files.txt
      - name: Changelog check for ${{ matrix.file }}
        if: always() && !env.NO_CHANGELOG && (startsWith(matrix.file, 'CHANGELOG-PRERELEASE') || !env.SNAPSHOT_ONLY)
        run: |
          if ! grep -e '^${{ matrix.file }}$' < files.txt > /dev/null; then
            echo "::error::An entry in ${{ matrix.file }} is required for this PR."
            echo "If this change is only relevant between snapshot versions: Add the label 'PRERELEASE-ONLY' to this PR." >> $GITHUB_STEP_SUMMARY
            echo "If this change does not warrant any release notes: Add the label 'NO-CHANGELOG' to this PR." >> $GITHUB_STEP_SUMMARY
            exit 1
          fi