# This workflow exists to make sure that we know when the protos and the generated code
# are out of sync. In this workflow we generate code from the protos and make sure it
# matches what is checked in.

# To make this much faster we don't use our own rust setup script. There is no need
# right now because the packages we're installing work fine with the latest version
# of Rust, at least at the time of writing. Famous last words of course, it's possible
# that the preinstalled version of the toolchain will break this at some point, but
# that probably won't happen for quite a while.

name: "Check Protos"
on:
  pull_request:
    types: [labeled, opened, synchronize, reopened, auto_merge_enabled]
  push:
    branches:
      - main

# Cancel redundant builds.
concurrency:
  # For push and workflow_dispatch events we use `github.sha` in the concurrency group and don't really cancel each other out/limit concurrency.
  # For pull_request events newer jobs cancel earlier jobs to save on CI etc.
  group: ${{ github.workflow }}-${{ github.event_name }}-${{ (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.sha || github.head_ref || github.ref }}
  cancel-in-progress: true

jobs:
  check:
    runs-on: ubuntu-latest
    if: | # Only run on each PR once an appropriate event occurs
      (
        github.event_name == 'workflow_dispatch' ||
        github.event_name == 'push' ||
        contains(github.event.pull_request.labels.*.name, 'CICD:run-e2e-tests') ||
        github.event.pull_request.auto_merge != null
      )
    steps:
      - uses: actions/checkout@v4

      # Install buf, which we use to generate code from the protos for Rust and TS.
      - name: Install buf
        uses: bufbuild/buf-setup-action@v1.24.0
        with:
          version: 1.28.1

      - uses: pre-commit/action@v3.0.0

      # Install protoc itself.
      - name: Install Protoc
        uses: arduino/setup-protoc@v2
        with:
          version: "25.x"

      # Set up pnpm.
      - uses: pnpm/action-setup@v4

      # Set up Poetry.
      - name: Install Python deps for generating code from protos
        uses: ./.github/actions/python-setup
        with:
          pyproject_directory: ./protos/python

      # Install the Rust, TS, and Python codegen deps.
      - name: Install deps for generating code from protos
        run: cd protos && ./scripts/install_deps.sh

      # Finally, generate code based on the protos.
      - name: Generate code
        run: cd protos && ./scripts/build_protos.sh

      # Confirm that nothing has changed.
      - name: Confirm that nothing has changed
        run: git diff --exit-code