name: release

# Publish to crates.io when a GitHub Release is published. GitHub-hosted runner
# only. Reads the crates.io API token from the org Actions secret
# SECRET_DEPLOY_CRATEIO (visibility: all repositories).
on:
  release:
    types: [published]

permissions:
  contents: read

env:
  CARGO_TERM_COLOR: always

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: dtolnay/rust-toolchain@stable
      - uses: Swatinem/rust-cache@v2

      # Refuse to publish a version that doesn't match the release tag.
      - name: verify tag matches crate version
        env:
          TAG: ${{ github.event.release.tag_name }}
        run: |
          crate_ver=$(grep -m1 '^version = ' Cargo.toml | sed -E 's/version = "(.*)"/\1/')
          echo "release tag: $TAG   crate version: $crate_ver"
          if [ "${TAG#v}" != "$crate_ver" ]; then
            echo "::error::release tag ($TAG) does not match Cargo.toml version ($crate_ver)"
            exit 1
          fi

      - name: test
        run: cargo test --locked

      - name: publish
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.SECRET_DEPLOY_CRATEIO }}
        run: cargo publish --locked
