name: Release-plz

on:
  push:
    branches:
      - main
  pull_request:
    types:
      - closed
    branches:
      - main
  workflow_dispatch:

jobs:
  release-plz-release:
    name: Release-plz release
    if: >
      github.event_name == 'pull_request' &&
      github.event.pull_request.merged == true &&
      startsWith(github.event.pull_request.head.ref, 'release-plz-')
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          persist-credentials: false

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable

      - name: Pin macros dependency for publish
        shell: bash
        run: |
          VERSION="$(cargo metadata --format-version 1 --no-deps | jq -r '.packages[] | select(.name=="ownable-std") | .version')"
          sed -i -E "s#^ownable-std-macros = \\{.*\\}\$#ownable-std-macros = { version = \"=${VERSION}\", path = \"macros/ownable-std-macros\", optional = true }#" Cargo.toml
          grep '^ownable-std-macros = ' Cargo.toml

      - name: Run release-plz (release)
        uses: release-plz/action@v0.5
        with:
          command: release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_API_TOKEN }}

  release-plz-pr:
    name: Release-plz PR
    if: github.event_name == 'push'
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
    concurrency:
      group: release-plz-${{ github.ref }}
      cancel-in-progress: false
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          persist-credentials: false

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable

      - name: Run release-plz (release-pr)
        uses: release-plz/action@v0.5
        with:
          command: release-pr
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_API_TOKEN }}
