name: release-plz

on:
  push:
    branches:
      - master

permissions:
  # Needed for release-plz to open / update the release PR and to create
  # GitHub Releases.
  contents: write
  pull-requests: write
  # Needed for crates.io trusted publishing (OIDC); release-plz exchanges
  # this for a short-lived registry token instead of using a long-lived
  # CARGO_REGISTRY_TOKEN secret.
  id-token: write
  # Needed for the `gh workflow run release-binaries.yml` dispatch below;
  # workflow_dispatch requires `actions: write` even with GITHUB_TOKEN.
  actions: write

# Don't run two release-plz jobs in parallel.
concurrency:
  group: release-plz-${{ github.ref }}
  cancel-in-progress: false

jobs:
  release-plz-release:
    name: release-plz release
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6
        with:
          fetch-depth: 0
      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable
      - name: Run release-plz
        id: release-plz
        uses: release-plz/action@v0.5
        with:
          command: release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      # release-plz creates the GitHub Release with the workflow's
      # GITHUB_TOKEN. GitHub deliberately suppresses downstream workflow
      # triggers for GITHUB_TOKEN-originated events to prevent recursion,
      # so `release: published` doesn't fire. workflow_dispatch is the
      # exception — chain into release-binaries explicitly per release.
      - name: Trigger release-binaries for each new release
        if: ${{ steps.release-plz.outputs.releases_created == 'true' }}
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          RELEASES: ${{ steps.release-plz.outputs.releases }}
        run: |
          # release-plz emits `.releases[].tag` (not `.tag_name`); see
          # https://release-plz.dev/docs/github/output for the schema.
          echo "$RELEASES" | jq -r '.[].tag' | while read -r tag; do
            if [ -z "$tag" ] || [ "$tag" = "null" ]; then
              continue
            fi
            echo "Dispatching release-binaries for $tag"
            gh workflow run release-binaries.yml -f tag="$tag"
          done

  release-plz-pr:
    name: release-plz PR
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6
        with:
          fetch-depth: 0
      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable
      - name: Run release-plz
        uses: release-plz/action@v0.5
        with:
          command: release-pr
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
