name: nf-core branch protection
# This workflow is triggered on PRs to `main`/`master` branch on the repository
# It fails when someone tries to make a PR against the nf-core `main`/`master` branch instead of `dev`
on:
  pull_request:
    branches:
      - main
      - master

permissions: {}

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      # PRs to the nf-core repo main/master branch are only ok if coming from the nf-core repo `dev` or any `patch` branches
      - name: Check PRs
        if: github.repository == 'nf-core/scdownstream'
        env:
          HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}
        run: |
          { [[ "$HEAD_REPO" == nf-core/scdownstream ]] && [[ $GITHUB_HEAD_REF == "dev" ]]; } || [[ $GITHUB_HEAD_REF == "patch" ]]

      # If the above check failed, build a comment to be posted by the shared poster workflow
      - name: Build PR comment
        if: failure()
        env:
          PR_NUMBER: ${{ github.event.pull_request.number }}
          BASE_REF: ${{ github.event.pull_request.base.ref }}
          HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}
          PR_USER: ${{ github.event.pull_request.user.login }}
        run: |
          mkdir -p pr-comment
          echo "$PR_NUMBER" > pr-comment/pr_number.txt
          echo "branch" > pr-comment/header.txt
          cat > pr-comment/comment.md <<EOF
          ## This PR is against the \`${BASE_REF}\` branch :x:

          * Do not close this PR
          * Click _Edit_ and change the \`base\` to \`dev\`
          * This CI test will remain failed until you push a new commit

          ---

          Hi @${PR_USER},

          It looks like this pull-request is has been made against the [${HEAD_REPO}](https://github.com/${HEAD_REPO}) ${BASE_REF} branch.
          The ${BASE_REF} branch on nf-core repositories should always contain code from the latest release.
          Because of this, PRs to ${BASE_REF} are only allowed if they come from the [${HEAD_REPO}](https://github.com/${HEAD_REPO}) \`dev\` branch.

          You do not need to close this PR, you can change the target branch to \`dev\` by clicking the _"Edit"_ button at the top of this page.
          Note that even after this, the test will continue to show as failing until you push a new commit.

          Thanks again for your contribution!
          EOF

      - name: Upload PR comment artifact
        if: failure()
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
        with:
          name: pr-comment
          path: pr-comment/
