# Publish to crates.io
name: Publish
on:
  push:
    tags:
      - 'v*'
permissions:
  contents: read
env:
  CARGO_TERM_COLOR: always
jobs:
  publish:
    name: Publish to crates.io
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6
      - name: Install Rust toolchain
        uses: actions-rust-lang/setup-rust-toolchain@v1
      - name: Verify version
        run: |
          TAG="${{ github.ref_name }}"
          TAG="${TAG#v}"
          CARGO=$(grep '^version' Cargo.toml | head -1 | cut -d'"' -f2)
          if [ "$TAG" != "$CARGO" ]; then
            echo "::error::Version mismatch: tag=$TAG, Cargo.toml=$CARGO"
            exit 1
          fi
      - name: Check not published
        run: |
          STATUS=$(curl -s -o /dev/null -w "%{http_code}" "https://crates.io/api/v1/crates/grpctestify/${{ github.ref_name }}")
          if [ "$STATUS" = "200" ]; then
            echo "::error::Version already published"
            exit 1
          fi
      - name: Build and test
        run: |
          cargo build --release --all-targets
          cargo test --release
      - name: Publish
        run: cargo publish --token ${{ secrets.CARGO_REGISTRY_TOKEN }}
