name: Publish to crates.io

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

env:
  CARGO_TERM_COLOR: always
  FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true

jobs:
  publish:
    name: Publish
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

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

      - name: Cache Rust dependencies
        uses: Swatinem/rust-cache@v2

      - name: Verify version matches tag
        run: |
          VERSION=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
          TAG="${GITHUB_REF_NAME#v}"
          if [ "$VERSION" != "$TAG" ]; then
            echo "::error::Cargo.toml version ($VERSION) does not match tag (v$TAG)"
            exit 1
          fi

      - name: Dry-run package
        run: cargo package --allow-dirty

      - name: Run tests
        uses: taiki-e/install-action@cargo-nextest
      - run: cargo nextest run --workspace

      - name: Publish to crates.io
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
        run: cargo publish
