name: Merge change log to main
on:
  workflow_dispatch:

jobs:
  create-pull-request:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          # this workflow is run against the release branch (see usage of GITHUB_REF_NAME below)
          # but it is creating a pull request against main
          ref: main
          # history is needed to run format-patch below
          fetch-depth: 0

      - name: Set git user
        run: .github/scripts/set-git-user.sh

        # this will fail if there have been conflicting change log updates introduced in main
      - name: Create pull request against main
        env:
          # not using the default GITHUB_TOKEN because pull requests generated by it do not run any workflows
          GITHUB_TOKEN: ${{ secrets.BOT_TOKEN }}
        run: |
          message="Merge change log updates from $GITHUB_REF_NAME"
          body="Merge change log updates from \`$GITHUB_REF_NAME\`."
          branch="merge-change-log-updates-from-${GITHUB_REF_NAME//\//-}"

          # perform a 3-way merge of a single file
          git format-patch --stdout HEAD..origin/$GITHUB_REF_NAME CHANGELOG.md | git apply --3way

          git commit -a -m "$message"
          git push origin HEAD:$branch
          gh pr create --title "$message" \
                       --body "$body" \
                       --head $branch \
                       --base main
