# This workflow checks that all commits in the "master" branch are also in the
# "release" and "develop" branches, and that all commits in the "release" branch
# are also in the "develop" branch.
name: Check for missing commits

# This workflow can only be triggered by other workflows.
on: workflow_call

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

defaults:
  run:
    shell: bash

jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0
        with:
          fetch-depth: 0
      - name: Check for missing commits
        env:
          MESSAGE: |

            If you are reading this, then the commits indicated above are missing
            from the "develop" and/or "release" branch. Do a reverse-merge as soon
            as possible. See CONTRIBUTING.md for instructions.
        run: |
          set -o pipefail
          # Branches are ordered by how "canonical" they are. Every commit in one
          # branch should be in all the branches behind it.
          order=(master release develop)
          branches=()
          for branch in "${order[@]}"; do
            # Check that the branches exist so that this job will work on forked
            # repos, which don't necessarily have master and release branches.
            echo "Checking if ${branch} exists."
            if git ls-remote --exit-code --heads origin \
              refs/heads/${branch} > /dev/null; then
              branches+=(origin/${branch})
            fi
          done

          prior=()
          for branch in "${branches[@]}"; do
            if [[ ${#prior[@]} -ne 0 ]]; then
              echo "Checking ${prior[@]} for commits missing from ${branch}."
              git log --oneline --no-merges "${prior[@]}" \
                ^$branch | tee -a "missing-commits.txt"
              echo
            fi
            prior+=("${branch}")
          done

          if [[ $(cat missing-commits.txt | wc -l) -ne 0 ]]; then
            echo "${MESSAGE}"
            exit 1
          fi
