name: Release

on:
  push:
    tags:
      - "v*.*.*"

env:
  CARGO_TERM_COLOR: always

permissions:
  contents: write

jobs:
  validate:
    name: Validate Release
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - name: Ensure tag points to main
        run: |
          # `actions/checkout` is typically shallow; ensure we have enough `origin/main`
          # history for an accurate ancestry check.
          if git rev-parse --is-shallow-repository | grep -q true; then
            git fetch --no-tags --prune --unshallow origin main
          else
            git fetch --no-tags --prune origin main
          fi
          git merge-base --is-ancestor "${GITHUB_SHA}^{}" origin/main
      - uses: actions-rust-lang/setup-rust-toolchain@v1
        with:
          components: rustfmt, clippy
      - uses: Swatinem/rust-cache@v2

      - name: Format check
        run: cargo fmt --check

      - name: Clippy
        run: cargo clippy --all-targets --all-features -- -D warnings

      - name: Tests
        run: cargo test --all-features --tests

      - name: Docs
        run: cargo doc --no-deps --all-features
        env:
          RUSTDOCFLAGS: -Dwarnings

      - name: Package verification
        run: |
          cargo package
          cargo publish --dry-run

  release:
    name: GitHub Release
    runs-on: ubuntu-latest
    needs: validate
    steps:
      - uses: actions/checkout@v6
      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          generate_release_notes: true

  publish:
    name: Publish to crates.io
    runs-on: ubuntu-latest
    permissions:
      id-token: write
    needs: validate
    steps:
      - uses: actions/checkout@v6
      - uses: rust-lang/crates-io-auth-action@v1
        id: auth
      - run: cargo publish
        env:
          CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }}
