name: Rust CI

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main
      - 'v*'

env:
  CARGO_TERM_COLOR: always
  RUST_BACKTRACE: 1
  CARGO_INCREMENTAL: 0

jobs:
  test:
    name: Test Suite
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        os: [ ubuntu-latest, macos-latest, windows-latest ]
        rust: [ stable, beta ]
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@master
        with:
          toolchain: ${{ matrix.rust }}

      - name: Cache Rust dependencies
        uses: Swatinem/rust-cache@v2
        with:
          shared-key: ${{ runner.os }}-${{ matrix.rust }}

      - name: Run tests
        run: cargo test --workspace --all-features --verbose

      - name: Run doc tests
        run: cargo test --doc --all-features --verbose

  clippy:
    name: Clippy (Linting)
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

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

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

      - name: Run clippy
        run: |
          cargo clippy --workspace --all-targets --all-features -- \
            --deny warnings \
            -W clippy::correctness \
            -W clippy::suspicious \
            -W clippy::complexity \
            -W clippy::perf \
            -W clippy::style \
            -W clippy::pedantic

  fmt:
    name: Formatting
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

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

      - name: Check formatting
        run: cargo fmt --all -- --check

  build-release:
    name: Build Release
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

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

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

      - name: Build release
        run: cargo build --release --all-features --verbose

      - name: Build examples
        run: |
          if [ -d "examples" ]; then
            cargo build --release --examples --verbose
          fi