name: Publish to crates.io

on:
  push:
    tags:
      - "v*"

env:
  CARGO_TERM_COLOR: always

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
      - uses: Swatinem/rust-cache@v2
      - name: Verify version matches tag
        run: |
          TAG="${GITHUB_REF#refs/tags/v}"
          CARGO_VERSION=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
          if [ "$TAG" != "$CARGO_VERSION" ]; then
            echo "Tag v$TAG does not match Cargo.toml version $CARGO_VERSION"
            exit 1
          fi
      - name: Publish
        run: cargo publish
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
