name: Publish to crates.io

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

jobs:
  publish:
    name: cargo publish
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
      - uses: Swatinem/rust-cache@v2
      - name: Verify Cargo.toml version matches tag
        run: |
          TAG=${GITHUB_REF_NAME#v}
          CARGO=$(grep -m1 '^version' Cargo.toml | cut -d'"' -f2)
          if [ "$TAG" != "$CARGO" ]; then
            echo "::error::tag $TAG does not match Cargo.toml version $CARGO"
            exit 1
          fi
      - name: Dry-run publish
        run: cargo publish --dry-run --allow-dirty
      - name: Publish to crates.io
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
        run: cargo publish --allow-dirty
