name: Publish to crates.io

on:
  push:
    tags: ["v*"]

permissions:
  id-token: write   # mint the OIDC token for crates.io Trusted Publishing
  contents: read

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7

      - name: Check tag matches Cargo.toml version
        env:
          TAG_NAME: ${{ github.ref_name }}
        run: |
          set -eu
          tag="${TAG_NAME#v}"
          crate="$(cargo metadata --no-deps --format-version=1 | jq -r '.packages[0].version')"
          if [ "$tag" != "$crate" ]; then
            echo "tag $tag != Cargo.toml version $crate" >&2
            exit 1
          fi

      - name: Authenticate to crates.io (Trusted Publishing)
        uses: rust-lang/crates-io-auth-action@v1
        id: auth

      - name: Publish
        env:
          CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }}
        run: cargo publish
