# This workflow checks that there is either a 'pr/no-changelog' label applied to a PR
# or there is a .changelog/<pr number>.txt file associated with a PR for a changelog entry

on:
  pull_request:
    types: [opened, synchronize, labeled]
    # Runs on PRs to main and all release branches
    branches:
      - main
      - release/*

jobs:
  # checks that a .changelog entry is present for a PR
  changelog-check:
    # If there  a `pr/no-changelog` label we ignore this check. Also, we ignore PRs created by the bot assigned to `backport-assistant`
    if: "! ( contains(github.event.pull_request.labels.*.name, 'pr/no-changelog') || github.event.pull_request.user.login == 'hc-github-team-consul-core' )" 
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2
        with:
          ref: ${{ github.event.pull_request.head.sha }}
          fetch-depth: 0 # by default the checkout action doesn't checkout all branches
      - name: Check for changelog entry in diff
        run: |
          pull_request_base_main=$(expr "${{ github.event.pull_request.base.ref }}" = "main")

          # check if there is a diff in the .changelog directory
          # for PRs against the main branch, the changelog file name should match the PR number
          if [ pull_request_base_main ]; then
            enforce_matching_pull_request_number="matching this PR number "
            changelog_file_path=".changelog/${{ github.event.pull_request.number }}.txt"
          else
            changelog_file_path=".changelog/*.txt"
          fi

          changelog_files=$(git --no-pager diff --name-only HEAD "$(git merge-base HEAD "origin/main")" -- ${changelog_file_path})

          # If we do not find a file in .changelog/, we fail the check
          if [ -z "$changelog_files" ]; then
            # Fail status check when no .changelog entry was found on the PR
            echo "Did not find a .changelog entry ${enforce_matching_pull_request_number}and the 'pr/no-changelog' label was not applied. Reference - https://github.com/hashicorp/consul/pull/8387"
            exit 1
          else
            echo "Found .changelog entry in PR!"
          fi
